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::desc("Maximum number of iterations SCEV will "
154                                      "symbolically execute a constant "
155                                      "derived loop"),
156                             cl::init(100));
157 
158 static cl::opt<bool, true> VerifySCEVOpt(
159     "verify-scev", cl::Hidden, cl::location(VerifySCEV),
160     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
161 static cl::opt<bool> VerifySCEVStrict(
162     "verify-scev-strict", cl::Hidden,
163     cl::desc("Enable stricter verification with -verify-scev is passed"));
164 static cl::opt<bool>
165     VerifySCEVMap("verify-scev-maps", cl::Hidden,
166                   cl::desc("Verify no dangling value in ScalarEvolution's "
167                            "ExprValueMap (slow)"));
168 
169 static cl::opt<bool> VerifyIR(
170     "scev-verify-ir", cl::Hidden,
171     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
172     cl::init(false));
173 
174 static cl::opt<unsigned> MulOpsInlineThreshold(
175     "scev-mulops-inline-threshold", cl::Hidden,
176     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> AddOpsInlineThreshold(
180     "scev-addops-inline-threshold", cl::Hidden,
181     cl::desc("Threshold for inlining addition operands into a SCEV"),
182     cl::init(500));
183 
184 static cl::opt<unsigned> MaxSCEVCompareDepth(
185     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
187     cl::init(32));
188 
189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
190     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
191     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
192     cl::init(2));
193 
194 static cl::opt<unsigned> MaxValueCompareDepth(
195     "scalar-evolution-max-value-compare-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive value complexity comparisons"),
197     cl::init(2));
198 
199 static cl::opt<unsigned>
200     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
201                   cl::desc("Maximum depth of recursive arithmetics"),
202                   cl::init(32));
203 
204 static cl::opt<unsigned> MaxConstantEvolvingDepth(
205     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
206     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
207 
208 static cl::opt<unsigned>
209     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
210                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
211                  cl::init(8));
212 
213 static cl::opt<unsigned>
214     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
215                   cl::desc("Max coefficients in AddRec during evolving"),
216                   cl::init(8));
217 
218 static cl::opt<unsigned>
219     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
220                   cl::desc("Size of the expression which is considered huge"),
221                   cl::init(4096));
222 
223 static cl::opt<bool>
224 ClassifyExpressions("scalar-evolution-classify-expressions",
225     cl::Hidden, cl::init(true),
226     cl::desc("When printing analysis, include information on every instruction"));
227 
228 static cl::opt<bool> UseExpensiveRangeSharpening(
229     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
230     cl::init(false),
231     cl::desc("Use more powerful methods of sharpening expression ranges. May "
232              "be costly in terms of compile time"));
233 
234 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
235     "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
236     cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
237              "Phi strongly connected components"),
238     cl::init(8));
239 
240 static cl::opt<bool>
241     EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
242                             cl::desc("Handle <= and >= in finite loops"),
243                             cl::init(true));
244 
245 //===----------------------------------------------------------------------===//
246 //                           SCEV class definitions
247 //===----------------------------------------------------------------------===//
248 
249 //===----------------------------------------------------------------------===//
250 // Implementation of the SCEV class.
251 //
252 
253 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
254 LLVM_DUMP_METHOD void SCEV::dump() const {
255   print(dbgs());
256   dbgs() << '\n';
257 }
258 #endif
259 
260 void SCEV::print(raw_ostream &OS) const {
261   switch (getSCEVType()) {
262   case scConstant:
263     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
264     return;
265   case scPtrToInt: {
266     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
267     const SCEV *Op = PtrToInt->getOperand();
268     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
269        << *PtrToInt->getType() << ")";
270     return;
271   }
272   case scTruncate: {
273     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
274     const SCEV *Op = Trunc->getOperand();
275     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
276        << *Trunc->getType() << ")";
277     return;
278   }
279   case scZeroExtend: {
280     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
281     const SCEV *Op = ZExt->getOperand();
282     OS << "(zext " << *Op->getType() << " " << *Op << " to "
283        << *ZExt->getType() << ")";
284     return;
285   }
286   case scSignExtend: {
287     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
288     const SCEV *Op = SExt->getOperand();
289     OS << "(sext " << *Op->getType() << " " << *Op << " to "
290        << *SExt->getType() << ")";
291     return;
292   }
293   case scAddRecExpr: {
294     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
295     OS << "{" << *AR->getOperand(0);
296     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
297       OS << ",+," << *AR->getOperand(i);
298     OS << "}<";
299     if (AR->hasNoUnsignedWrap())
300       OS << "nuw><";
301     if (AR->hasNoSignedWrap())
302       OS << "nsw><";
303     if (AR->hasNoSelfWrap() &&
304         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
305       OS << "nw><";
306     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
307     OS << ">";
308     return;
309   }
310   case scAddExpr:
311   case scMulExpr:
312   case scUMaxExpr:
313   case scSMaxExpr:
314   case scUMinExpr:
315   case scSMinExpr:
316   case scSequentialUMinExpr: {
317     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
318     const char *OpStr = nullptr;
319     switch (NAry->getSCEVType()) {
320     case scAddExpr: OpStr = " + "; break;
321     case scMulExpr: OpStr = " * "; break;
322     case scUMaxExpr: OpStr = " umax "; break;
323     case scSMaxExpr: OpStr = " smax "; break;
324     case scUMinExpr:
325       OpStr = " umin ";
326       break;
327     case scSMinExpr:
328       OpStr = " smin ";
329       break;
330     case scSequentialUMinExpr:
331       OpStr = " umin_seq ";
332       break;
333     default:
334       llvm_unreachable("There are no other nary expression types.");
335     }
336     OS << "(";
337     ListSeparator LS(OpStr);
338     for (const SCEV *Op : NAry->operands())
339       OS << LS << *Op;
340     OS << ")";
341     switch (NAry->getSCEVType()) {
342     case scAddExpr:
343     case scMulExpr:
344       if (NAry->hasNoUnsignedWrap())
345         OS << "<nuw>";
346       if (NAry->hasNoSignedWrap())
347         OS << "<nsw>";
348       break;
349     default:
350       // Nothing to print for other nary expressions.
351       break;
352     }
353     return;
354   }
355   case scUDivExpr: {
356     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
357     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
358     return;
359   }
360   case scUnknown: {
361     const SCEVUnknown *U = cast<SCEVUnknown>(this);
362     Type *AllocTy;
363     if (U->isSizeOf(AllocTy)) {
364       OS << "sizeof(" << *AllocTy << ")";
365       return;
366     }
367     if (U->isAlignOf(AllocTy)) {
368       OS << "alignof(" << *AllocTy << ")";
369       return;
370     }
371 
372     Type *CTy;
373     Constant *FieldNo;
374     if (U->isOffsetOf(CTy, FieldNo)) {
375       OS << "offsetof(" << *CTy << ", ";
376       FieldNo->printAsOperand(OS, false);
377       OS << ")";
378       return;
379     }
380 
381     // Otherwise just print it normally.
382     U->getValue()->printAsOperand(OS, false);
383     return;
384   }
385   case scCouldNotCompute:
386     OS << "***COULDNOTCOMPUTE***";
387     return;
388   }
389   llvm_unreachable("Unknown SCEV kind!");
390 }
391 
392 Type *SCEV::getType() const {
393   switch (getSCEVType()) {
394   case scConstant:
395     return cast<SCEVConstant>(this)->getType();
396   case scPtrToInt:
397   case scTruncate:
398   case scZeroExtend:
399   case scSignExtend:
400     return cast<SCEVCastExpr>(this)->getType();
401   case scAddRecExpr:
402     return cast<SCEVAddRecExpr>(this)->getType();
403   case scMulExpr:
404     return cast<SCEVMulExpr>(this)->getType();
405   case scUMaxExpr:
406   case scSMaxExpr:
407   case scUMinExpr:
408   case scSMinExpr:
409     return cast<SCEVMinMaxExpr>(this)->getType();
410   case scSequentialUMinExpr:
411     return cast<SCEVSequentialMinMaxExpr>(this)->getType();
412   case scAddExpr:
413     return cast<SCEVAddExpr>(this)->getType();
414   case scUDivExpr:
415     return cast<SCEVUDivExpr>(this)->getType();
416   case scUnknown:
417     return cast<SCEVUnknown>(this)->getType();
418   case scCouldNotCompute:
419     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
420   }
421   llvm_unreachable("Unknown SCEV kind!");
422 }
423 
424 bool SCEV::isZero() const {
425   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
426     return SC->getValue()->isZero();
427   return false;
428 }
429 
430 bool SCEV::isOne() const {
431   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
432     return SC->getValue()->isOne();
433   return false;
434 }
435 
436 bool SCEV::isAllOnesValue() const {
437   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
438     return SC->getValue()->isMinusOne();
439   return false;
440 }
441 
442 bool SCEV::isNonConstantNegative() const {
443   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
444   if (!Mul) return false;
445 
446   // If there is a constant factor, it will be first.
447   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
448   if (!SC) return false;
449 
450   // Return true if the value is negative, this matches things like (-42 * V).
451   return SC->getAPInt().isNegative();
452 }
453 
454 SCEVCouldNotCompute::SCEVCouldNotCompute() :
455   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
456 
457 bool SCEVCouldNotCompute::classof(const SCEV *S) {
458   return S->getSCEVType() == scCouldNotCompute;
459 }
460 
461 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
462   FoldingSetNodeID ID;
463   ID.AddInteger(scConstant);
464   ID.AddPointer(V);
465   void *IP = nullptr;
466   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
467   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
468   UniqueSCEVs.InsertNode(S, IP);
469   return S;
470 }
471 
472 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
473   return getConstant(ConstantInt::get(getContext(), Val));
474 }
475 
476 const SCEV *
477 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
478   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
479   return getConstant(ConstantInt::get(ITy, V, isSigned));
480 }
481 
482 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
483                            const SCEV *op, Type *ty)
484     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
485   Operands[0] = op;
486 }
487 
488 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
489                                    Type *ITy)
490     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
491   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
492          "Must be a non-bit-width-changing pointer-to-integer cast!");
493 }
494 
495 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
496                                            SCEVTypes SCEVTy, const SCEV *op,
497                                            Type *ty)
498     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
499 
500 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
501                                    Type *ty)
502     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
503   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
504          "Cannot truncate non-integer value!");
505 }
506 
507 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
508                                        const SCEV *op, Type *ty)
509     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
510   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
511          "Cannot zero extend non-integer value!");
512 }
513 
514 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
515                                        const SCEV *op, Type *ty)
516     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
517   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
518          "Cannot sign extend non-integer value!");
519 }
520 
521 void SCEVUnknown::deleted() {
522   // Clear this SCEVUnknown from various maps.
523   SE->forgetMemoizedResults(this);
524 
525   // Remove this SCEVUnknown from the uniquing map.
526   SE->UniqueSCEVs.RemoveNode(this);
527 
528   // Release the value.
529   setValPtr(nullptr);
530 }
531 
532 void SCEVUnknown::allUsesReplacedWith(Value *New) {
533   // Clear this SCEVUnknown from various maps.
534   SE->forgetMemoizedResults(this);
535 
536   // Remove this SCEVUnknown from the uniquing map.
537   SE->UniqueSCEVs.RemoveNode(this);
538 
539   // Replace the value pointer in case someone is still using this SCEVUnknown.
540   setValPtr(New);
541 }
542 
543 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
544   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
545     if (VCE->getOpcode() == Instruction::PtrToInt)
546       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
547         if (CE->getOpcode() == Instruction::GetElementPtr &&
548             CE->getOperand(0)->isNullValue() &&
549             CE->getNumOperands() == 2)
550           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
551             if (CI->isOne()) {
552               AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
553               return true;
554             }
555 
556   return false;
557 }
558 
559 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
560   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
561     if (VCE->getOpcode() == Instruction::PtrToInt)
562       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
563         if (CE->getOpcode() == Instruction::GetElementPtr &&
564             CE->getOperand(0)->isNullValue()) {
565           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
566           if (StructType *STy = dyn_cast<StructType>(Ty))
567             if (!STy->isPacked() &&
568                 CE->getNumOperands() == 3 &&
569                 CE->getOperand(1)->isNullValue()) {
570               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
571                 if (CI->isOne() &&
572                     STy->getNumElements() == 2 &&
573                     STy->getElementType(0)->isIntegerTy(1)) {
574                   AllocTy = STy->getElementType(1);
575                   return true;
576                 }
577             }
578         }
579 
580   return false;
581 }
582 
583 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
584   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
585     if (VCE->getOpcode() == Instruction::PtrToInt)
586       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
587         if (CE->getOpcode() == Instruction::GetElementPtr &&
588             CE->getNumOperands() == 3 &&
589             CE->getOperand(0)->isNullValue() &&
590             CE->getOperand(1)->isNullValue()) {
591           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
592           // Ignore vector types here so that ScalarEvolutionExpander doesn't
593           // emit getelementptrs that index into vectors.
594           if (Ty->isStructTy() || Ty->isArrayTy()) {
595             CTy = Ty;
596             FieldNo = CE->getOperand(2);
597             return true;
598           }
599         }
600 
601   return false;
602 }
603 
604 //===----------------------------------------------------------------------===//
605 //                               SCEV Utilities
606 //===----------------------------------------------------------------------===//
607 
608 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
609 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
610 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
611 /// have been previously deemed to be "equally complex" by this routine.  It is
612 /// intended to avoid exponential time complexity in cases like:
613 ///
614 ///   %a = f(%x, %y)
615 ///   %b = f(%a, %a)
616 ///   %c = f(%b, %b)
617 ///
618 ///   %d = f(%x, %y)
619 ///   %e = f(%d, %d)
620 ///   %f = f(%e, %e)
621 ///
622 ///   CompareValueComplexity(%f, %c)
623 ///
624 /// Since we do not continue running this routine on expression trees once we
625 /// have seen unequal values, there is no need to track them in the cache.
626 static int
627 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
628                        const LoopInfo *const LI, Value *LV, Value *RV,
629                        unsigned Depth) {
630   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
631     return 0;
632 
633   // Order pointer values after integer values. This helps SCEVExpander form
634   // GEPs.
635   bool LIsPointer = LV->getType()->isPointerTy(),
636        RIsPointer = RV->getType()->isPointerTy();
637   if (LIsPointer != RIsPointer)
638     return (int)LIsPointer - (int)RIsPointer;
639 
640   // Compare getValueID values.
641   unsigned LID = LV->getValueID(), RID = RV->getValueID();
642   if (LID != RID)
643     return (int)LID - (int)RID;
644 
645   // Sort arguments by their position.
646   if (const auto *LA = dyn_cast<Argument>(LV)) {
647     const auto *RA = cast<Argument>(RV);
648     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
649     return (int)LArgNo - (int)RArgNo;
650   }
651 
652   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
653     const auto *RGV = cast<GlobalValue>(RV);
654 
655     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
656       auto LT = GV->getLinkage();
657       return !(GlobalValue::isPrivateLinkage(LT) ||
658                GlobalValue::isInternalLinkage(LT));
659     };
660 
661     // Use the names to distinguish the two values, but only if the
662     // names are semantically important.
663     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
664       return LGV->getName().compare(RGV->getName());
665   }
666 
667   // For instructions, compare their loop depth, and their operand count.  This
668   // is pretty loose.
669   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
670     const auto *RInst = cast<Instruction>(RV);
671 
672     // Compare loop depths.
673     const BasicBlock *LParent = LInst->getParent(),
674                      *RParent = RInst->getParent();
675     if (LParent != RParent) {
676       unsigned LDepth = LI->getLoopDepth(LParent),
677                RDepth = LI->getLoopDepth(RParent);
678       if (LDepth != RDepth)
679         return (int)LDepth - (int)RDepth;
680     }
681 
682     // Compare the number of operands.
683     unsigned LNumOps = LInst->getNumOperands(),
684              RNumOps = RInst->getNumOperands();
685     if (LNumOps != RNumOps)
686       return (int)LNumOps - (int)RNumOps;
687 
688     for (unsigned Idx : seq(0u, LNumOps)) {
689       int Result =
690           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
691                                  RInst->getOperand(Idx), Depth + 1);
692       if (Result != 0)
693         return Result;
694     }
695   }
696 
697   EqCacheValue.unionSets(LV, RV);
698   return 0;
699 }
700 
701 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
702 // than RHS, respectively. A three-way result allows recursive comparisons to be
703 // more efficient.
704 // If the max analysis depth was reached, return None, assuming we do not know
705 // if they are equivalent for sure.
706 static Optional<int>
707 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
708                       EquivalenceClasses<const Value *> &EqCacheValue,
709                       const LoopInfo *const LI, const SCEV *LHS,
710                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
711   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
712   if (LHS == RHS)
713     return 0;
714 
715   // Primarily, sort the SCEVs by their getSCEVType().
716   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
717   if (LType != RType)
718     return (int)LType - (int)RType;
719 
720   if (EqCacheSCEV.isEquivalent(LHS, RHS))
721     return 0;
722 
723   if (Depth > MaxSCEVCompareDepth)
724     return None;
725 
726   // Aside from the getSCEVType() ordering, the particular ordering
727   // isn't very important except that it's beneficial to be consistent,
728   // so that (a + b) and (b + a) don't end up as different expressions.
729   switch (LType) {
730   case scUnknown: {
731     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
732     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
733 
734     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
735                                    RU->getValue(), Depth + 1);
736     if (X == 0)
737       EqCacheSCEV.unionSets(LHS, RHS);
738     return X;
739   }
740 
741   case scConstant: {
742     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
743     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
744 
745     // Compare constant values.
746     const APInt &LA = LC->getAPInt();
747     const APInt &RA = RC->getAPInt();
748     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
749     if (LBitWidth != RBitWidth)
750       return (int)LBitWidth - (int)RBitWidth;
751     return LA.ult(RA) ? -1 : 1;
752   }
753 
754   case scAddRecExpr: {
755     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
756     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
757 
758     // There is always a dominance between two recs that are used by one SCEV,
759     // so we can safely sort recs by loop header dominance. We require such
760     // order in getAddExpr.
761     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
762     if (LLoop != RLoop) {
763       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
764       assert(LHead != RHead && "Two loops share the same header?");
765       if (DT.dominates(LHead, RHead))
766         return 1;
767       else
768         assert(DT.dominates(RHead, LHead) &&
769                "No dominance between recurrences used by one SCEV?");
770       return -1;
771     }
772 
773     // Addrec complexity grows with operand count.
774     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
775     if (LNumOps != RNumOps)
776       return (int)LNumOps - (int)RNumOps;
777 
778     // Lexicographically compare.
779     for (unsigned i = 0; i != LNumOps; ++i) {
780       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
781                                      LA->getOperand(i), RA->getOperand(i), DT,
782                                      Depth + 1);
783       if (X != 0)
784         return X;
785     }
786     EqCacheSCEV.unionSets(LHS, RHS);
787     return 0;
788   }
789 
790   case scAddExpr:
791   case scMulExpr:
792   case scSMaxExpr:
793   case scUMaxExpr:
794   case scSMinExpr:
795   case scUMinExpr:
796   case scSequentialUMinExpr: {
797     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
798     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
799 
800     // Lexicographically compare n-ary expressions.
801     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
802     if (LNumOps != RNumOps)
803       return (int)LNumOps - (int)RNumOps;
804 
805     for (unsigned i = 0; i != LNumOps; ++i) {
806       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
807                                      LC->getOperand(i), RC->getOperand(i), DT,
808                                      Depth + 1);
809       if (X != 0)
810         return X;
811     }
812     EqCacheSCEV.unionSets(LHS, RHS);
813     return 0;
814   }
815 
816   case scUDivExpr: {
817     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
818     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
819 
820     // Lexicographically compare udiv expressions.
821     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
822                                    RC->getLHS(), DT, Depth + 1);
823     if (X != 0)
824       return X;
825     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
826                               RC->getRHS(), DT, Depth + 1);
827     if (X == 0)
828       EqCacheSCEV.unionSets(LHS, RHS);
829     return X;
830   }
831 
832   case scPtrToInt:
833   case scTruncate:
834   case scZeroExtend:
835   case scSignExtend: {
836     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
837     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
838 
839     // Compare cast expressions by operand.
840     auto X =
841         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
842                               RC->getOperand(), DT, Depth + 1);
843     if (X == 0)
844       EqCacheSCEV.unionSets(LHS, RHS);
845     return X;
846   }
847 
848   case scCouldNotCompute:
849     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
850   }
851   llvm_unreachable("Unknown SCEV kind!");
852 }
853 
854 /// Given a list of SCEV objects, order them by their complexity, and group
855 /// objects of the same complexity together by value.  When this routine is
856 /// finished, we know that any duplicates in the vector are consecutive and that
857 /// complexity is monotonically increasing.
858 ///
859 /// Note that we go take special precautions to ensure that we get deterministic
860 /// results from this routine.  In other words, we don't want the results of
861 /// this to depend on where the addresses of various SCEV objects happened to
862 /// land in memory.
863 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
864                               LoopInfo *LI, DominatorTree &DT) {
865   if (Ops.size() < 2) return;  // Noop
866 
867   EquivalenceClasses<const SCEV *> EqCacheSCEV;
868   EquivalenceClasses<const Value *> EqCacheValue;
869 
870   // Whether LHS has provably less complexity than RHS.
871   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
872     auto Complexity =
873         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
874     return Complexity && *Complexity < 0;
875   };
876   if (Ops.size() == 2) {
877     // This is the common case, which also happens to be trivially simple.
878     // Special case it.
879     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
880     if (IsLessComplex(RHS, LHS))
881       std::swap(LHS, RHS);
882     return;
883   }
884 
885   // Do the rough sort by complexity.
886   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
887     return IsLessComplex(LHS, RHS);
888   });
889 
890   // Now that we are sorted by complexity, group elements of the same
891   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
892   // be extremely short in practice.  Note that we take this approach because we
893   // do not want to depend on the addresses of the objects we are grouping.
894   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
895     const SCEV *S = Ops[i];
896     unsigned Complexity = S->getSCEVType();
897 
898     // If there are any objects of the same complexity and same value as this
899     // one, group them.
900     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
901       if (Ops[j] == S) { // Found a duplicate.
902         // Move it to immediately after i'th element.
903         std::swap(Ops[i+1], Ops[j]);
904         ++i;   // no need to rescan it.
905         if (i == e-2) return;  // Done!
906       }
907     }
908   }
909 }
910 
911 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
912 /// least HugeExprThreshold nodes).
913 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
914   return any_of(Ops, [](const SCEV *S) {
915     return S->getExpressionSize() >= HugeExprThreshold;
916   });
917 }
918 
919 //===----------------------------------------------------------------------===//
920 //                      Simple SCEV method implementations
921 //===----------------------------------------------------------------------===//
922 
923 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
924 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
925                                        ScalarEvolution &SE,
926                                        Type *ResultTy) {
927   // Handle the simplest case efficiently.
928   if (K == 1)
929     return SE.getTruncateOrZeroExtend(It, ResultTy);
930 
931   // We are using the following formula for BC(It, K):
932   //
933   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
934   //
935   // Suppose, W is the bitwidth of the return value.  We must be prepared for
936   // overflow.  Hence, we must assure that the result of our computation is
937   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
938   // safe in modular arithmetic.
939   //
940   // However, this code doesn't use exactly that formula; the formula it uses
941   // is something like the following, where T is the number of factors of 2 in
942   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
943   // exponentiation:
944   //
945   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
946   //
947   // This formula is trivially equivalent to the previous formula.  However,
948   // this formula can be implemented much more efficiently.  The trick is that
949   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
950   // arithmetic.  To do exact division in modular arithmetic, all we have
951   // to do is multiply by the inverse.  Therefore, this step can be done at
952   // width W.
953   //
954   // The next issue is how to safely do the division by 2^T.  The way this
955   // is done is by doing the multiplication step at a width of at least W + T
956   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
957   // when we perform the division by 2^T (which is equivalent to a right shift
958   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
959   // truncated out after the division by 2^T.
960   //
961   // In comparison to just directly using the first formula, this technique
962   // is much more efficient; using the first formula requires W * K bits,
963   // but this formula less than W + K bits. Also, the first formula requires
964   // a division step, whereas this formula only requires multiplies and shifts.
965   //
966   // It doesn't matter whether the subtraction step is done in the calculation
967   // width or the input iteration count's width; if the subtraction overflows,
968   // the result must be zero anyway.  We prefer here to do it in the width of
969   // the induction variable because it helps a lot for certain cases; CodeGen
970   // isn't smart enough to ignore the overflow, which leads to much less
971   // efficient code if the width of the subtraction is wider than the native
972   // register width.
973   //
974   // (It's possible to not widen at all by pulling out factors of 2 before
975   // the multiplication; for example, K=2 can be calculated as
976   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
977   // extra arithmetic, so it's not an obvious win, and it gets
978   // much more complicated for K > 3.)
979 
980   // Protection from insane SCEVs; this bound is conservative,
981   // but it probably doesn't matter.
982   if (K > 1000)
983     return SE.getCouldNotCompute();
984 
985   unsigned W = SE.getTypeSizeInBits(ResultTy);
986 
987   // Calculate K! / 2^T and T; we divide out the factors of two before
988   // multiplying for calculating K! / 2^T to avoid overflow.
989   // Other overflow doesn't matter because we only care about the bottom
990   // W bits of the result.
991   APInt OddFactorial(W, 1);
992   unsigned T = 1;
993   for (unsigned i = 3; i <= K; ++i) {
994     APInt Mult(W, i);
995     unsigned TwoFactors = Mult.countTrailingZeros();
996     T += TwoFactors;
997     Mult.lshrInPlace(TwoFactors);
998     OddFactorial *= Mult;
999   }
1000 
1001   // We need at least W + T bits for the multiplication step
1002   unsigned CalculationBits = W + T;
1003 
1004   // Calculate 2^T, at width T+W.
1005   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1006 
1007   // Calculate the multiplicative inverse of K! / 2^T;
1008   // this multiplication factor will perform the exact division by
1009   // K! / 2^T.
1010   APInt Mod = APInt::getSignedMinValue(W+1);
1011   APInt MultiplyFactor = OddFactorial.zext(W+1);
1012   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1013   MultiplyFactor = MultiplyFactor.trunc(W);
1014 
1015   // Calculate the product, at width T+W
1016   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1017                                                       CalculationBits);
1018   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1019   for (unsigned i = 1; i != K; ++i) {
1020     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1021     Dividend = SE.getMulExpr(Dividend,
1022                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1023   }
1024 
1025   // Divide by 2^T
1026   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1027 
1028   // Truncate the result, and divide by K! / 2^T.
1029 
1030   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1031                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1032 }
1033 
1034 /// Return the value of this chain of recurrences at the specified iteration
1035 /// number.  We can evaluate this recurrence by multiplying each element in the
1036 /// chain by the binomial coefficient corresponding to it.  In other words, we
1037 /// can evaluate {A,+,B,+,C,+,D} as:
1038 ///
1039 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1040 ///
1041 /// where BC(It, k) stands for binomial coefficient.
1042 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1043                                                 ScalarEvolution &SE) const {
1044   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1045 }
1046 
1047 const SCEV *
1048 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1049                                     const SCEV *It, ScalarEvolution &SE) {
1050   assert(Operands.size() > 0);
1051   const SCEV *Result = Operands[0];
1052   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1053     // The computation is correct in the face of overflow provided that the
1054     // multiplication is performed _after_ the evaluation of the binomial
1055     // coefficient.
1056     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1057     if (isa<SCEVCouldNotCompute>(Coeff))
1058       return Coeff;
1059 
1060     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1061   }
1062   return Result;
1063 }
1064 
1065 //===----------------------------------------------------------------------===//
1066 //                    SCEV Expression folder implementations
1067 //===----------------------------------------------------------------------===//
1068 
1069 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1070                                                      unsigned Depth) {
1071   assert(Depth <= 1 &&
1072          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1073 
1074   // We could be called with an integer-typed operands during SCEV rewrites.
1075   // Since the operand is an integer already, just perform zext/trunc/self cast.
1076   if (!Op->getType()->isPointerTy())
1077     return Op;
1078 
1079   // What would be an ID for such a SCEV cast expression?
1080   FoldingSetNodeID ID;
1081   ID.AddInteger(scPtrToInt);
1082   ID.AddPointer(Op);
1083 
1084   void *IP = nullptr;
1085 
1086   // Is there already an expression for such a cast?
1087   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1088     return S;
1089 
1090   // It isn't legal for optimizations to construct new ptrtoint expressions
1091   // for non-integral pointers.
1092   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1093     return getCouldNotCompute();
1094 
1095   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1096 
1097   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1098   // is sufficiently wide to represent all possible pointer values.
1099   // We could theoretically teach SCEV to truncate wider pointers, but
1100   // that isn't implemented for now.
1101   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1102       getDataLayout().getTypeSizeInBits(IntPtrTy))
1103     return getCouldNotCompute();
1104 
1105   // If not, is this expression something we can't reduce any further?
1106   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1107     // Perform some basic constant folding. If the operand of the ptr2int cast
1108     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1109     // left as-is), but produce a zero constant.
1110     // NOTE: We could handle a more general case, but lack motivational cases.
1111     if (isa<ConstantPointerNull>(U->getValue()))
1112       return getZero(IntPtrTy);
1113 
1114     // Create an explicit cast node.
1115     // We can reuse the existing insert position since if we get here,
1116     // we won't have made any changes which would invalidate it.
1117     SCEV *S = new (SCEVAllocator)
1118         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1119     UniqueSCEVs.InsertNode(S, IP);
1120     registerUser(S, Op);
1121     return S;
1122   }
1123 
1124   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1125                        "non-SCEVUnknown's.");
1126 
1127   // Otherwise, we've got some expression that is more complex than just a
1128   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1129   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1130   // only, and the expressions must otherwise be integer-typed.
1131   // So sink the cast down to the SCEVUnknown's.
1132 
1133   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1134   /// which computes a pointer-typed value, and rewrites the whole expression
1135   /// tree so that *all* the computations are done on integers, and the only
1136   /// pointer-typed operands in the expression are SCEVUnknown.
1137   class SCEVPtrToIntSinkingRewriter
1138       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1139     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1140 
1141   public:
1142     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1143 
1144     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1145       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1146       return Rewriter.visit(Scev);
1147     }
1148 
1149     const SCEV *visit(const SCEV *S) {
1150       Type *STy = S->getType();
1151       // If the expression is not pointer-typed, just keep it as-is.
1152       if (!STy->isPointerTy())
1153         return S;
1154       // Else, recursively sink the cast down into it.
1155       return Base::visit(S);
1156     }
1157 
1158     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1159       SmallVector<const SCEV *, 2> Operands;
1160       bool Changed = false;
1161       for (auto *Op : Expr->operands()) {
1162         Operands.push_back(visit(Op));
1163         Changed |= Op != Operands.back();
1164       }
1165       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1166     }
1167 
1168     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1169       SmallVector<const SCEV *, 2> Operands;
1170       bool Changed = false;
1171       for (auto *Op : Expr->operands()) {
1172         Operands.push_back(visit(Op));
1173         Changed |= Op != Operands.back();
1174       }
1175       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1176     }
1177 
1178     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1179       assert(Expr->getType()->isPointerTy() &&
1180              "Should only reach pointer-typed SCEVUnknown's.");
1181       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1182     }
1183   };
1184 
1185   // And actually perform the cast sinking.
1186   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1187   assert(IntOp->getType()->isIntegerTy() &&
1188          "We must have succeeded in sinking the cast, "
1189          "and ending up with an integer-typed expression!");
1190   return IntOp;
1191 }
1192 
1193 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1194   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1195 
1196   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1197   if (isa<SCEVCouldNotCompute>(IntOp))
1198     return IntOp;
1199 
1200   return getTruncateOrZeroExtend(IntOp, Ty);
1201 }
1202 
1203 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1204                                              unsigned Depth) {
1205   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1206          "This is not a truncating conversion!");
1207   assert(isSCEVable(Ty) &&
1208          "This is not a conversion to a SCEVable type!");
1209   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1210   Ty = getEffectiveSCEVType(Ty);
1211 
1212   FoldingSetNodeID ID;
1213   ID.AddInteger(scTruncate);
1214   ID.AddPointer(Op);
1215   ID.AddPointer(Ty);
1216   void *IP = nullptr;
1217   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1218 
1219   // Fold if the operand is constant.
1220   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1221     return getConstant(
1222       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1223 
1224   // trunc(trunc(x)) --> trunc(x)
1225   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1226     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1227 
1228   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1229   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1230     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1231 
1232   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1233   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1234     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1235 
1236   if (Depth > MaxCastDepth) {
1237     SCEV *S =
1238         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1239     UniqueSCEVs.InsertNode(S, IP);
1240     registerUser(S, Op);
1241     return S;
1242   }
1243 
1244   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1245   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1246   // if after transforming we have at most one truncate, not counting truncates
1247   // that replace other casts.
1248   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1249     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1250     SmallVector<const SCEV *, 4> Operands;
1251     unsigned numTruncs = 0;
1252     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1253          ++i) {
1254       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1255       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1256           isa<SCEVTruncateExpr>(S))
1257         numTruncs++;
1258       Operands.push_back(S);
1259     }
1260     if (numTruncs < 2) {
1261       if (isa<SCEVAddExpr>(Op))
1262         return getAddExpr(Operands);
1263       else if (isa<SCEVMulExpr>(Op))
1264         return getMulExpr(Operands);
1265       else
1266         llvm_unreachable("Unexpected SCEV type for Op.");
1267     }
1268     // Although we checked in the beginning that ID is not in the cache, it is
1269     // possible that during recursion and different modification ID was inserted
1270     // into the cache. So if we find it, just return it.
1271     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1272       return S;
1273   }
1274 
1275   // If the input value is a chrec scev, truncate the chrec's operands.
1276   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1277     SmallVector<const SCEV *, 4> Operands;
1278     for (const SCEV *Op : AddRec->operands())
1279       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1280     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1281   }
1282 
1283   // Return zero if truncating to known zeros.
1284   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1285   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1286     return getZero(Ty);
1287 
1288   // The cast wasn't folded; create an explicit cast node. We can reuse
1289   // the existing insert position since if we get here, we won't have
1290   // made any changes which would invalidate it.
1291   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1292                                                  Op, Ty);
1293   UniqueSCEVs.InsertNode(S, IP);
1294   registerUser(S, Op);
1295   return S;
1296 }
1297 
1298 // Get the limit of a recurrence such that incrementing by Step cannot cause
1299 // signed overflow as long as the value of the recurrence within the
1300 // loop does not exceed this limit before incrementing.
1301 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1302                                                  ICmpInst::Predicate *Pred,
1303                                                  ScalarEvolution *SE) {
1304   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1305   if (SE->isKnownPositive(Step)) {
1306     *Pred = ICmpInst::ICMP_SLT;
1307     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1308                            SE->getSignedRangeMax(Step));
1309   }
1310   if (SE->isKnownNegative(Step)) {
1311     *Pred = ICmpInst::ICMP_SGT;
1312     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1313                            SE->getSignedRangeMin(Step));
1314   }
1315   return nullptr;
1316 }
1317 
1318 // Get the limit of a recurrence such that incrementing by Step cannot cause
1319 // unsigned overflow as long as the value of the recurrence within the loop does
1320 // not exceed this limit before incrementing.
1321 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1322                                                    ICmpInst::Predicate *Pred,
1323                                                    ScalarEvolution *SE) {
1324   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1325   *Pred = ICmpInst::ICMP_ULT;
1326 
1327   return SE->getConstant(APInt::getMinValue(BitWidth) -
1328                          SE->getUnsignedRangeMax(Step));
1329 }
1330 
1331 namespace {
1332 
1333 struct ExtendOpTraitsBase {
1334   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1335                                                           unsigned);
1336 };
1337 
1338 // Used to make code generic over signed and unsigned overflow.
1339 template <typename ExtendOp> struct ExtendOpTraits {
1340   // Members present:
1341   //
1342   // static const SCEV::NoWrapFlags WrapType;
1343   //
1344   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1345   //
1346   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1347   //                                           ICmpInst::Predicate *Pred,
1348   //                                           ScalarEvolution *SE);
1349 };
1350 
1351 template <>
1352 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1353   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1354 
1355   static const GetExtendExprTy GetExtendExpr;
1356 
1357   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1358                                              ICmpInst::Predicate *Pred,
1359                                              ScalarEvolution *SE) {
1360     return getSignedOverflowLimitForStep(Step, Pred, SE);
1361   }
1362 };
1363 
1364 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1365     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1366 
1367 template <>
1368 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1369   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1370 
1371   static const GetExtendExprTy GetExtendExpr;
1372 
1373   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1374                                              ICmpInst::Predicate *Pred,
1375                                              ScalarEvolution *SE) {
1376     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1377   }
1378 };
1379 
1380 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1381     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1382 
1383 } // end anonymous namespace
1384 
1385 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1386 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1387 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1388 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1389 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1390 // expression "Step + sext/zext(PreIncAR)" is congruent with
1391 // "sext/zext(PostIncAR)"
1392 template <typename ExtendOpTy>
1393 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1394                                         ScalarEvolution *SE, unsigned Depth) {
1395   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1396   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1397 
1398   const Loop *L = AR->getLoop();
1399   const SCEV *Start = AR->getStart();
1400   const SCEV *Step = AR->getStepRecurrence(*SE);
1401 
1402   // Check for a simple looking step prior to loop entry.
1403   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1404   if (!SA)
1405     return nullptr;
1406 
1407   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1408   // subtraction is expensive. For this purpose, perform a quick and dirty
1409   // difference, by checking for Step in the operand list.
1410   SmallVector<const SCEV *, 4> DiffOps;
1411   for (const SCEV *Op : SA->operands())
1412     if (Op != Step)
1413       DiffOps.push_back(Op);
1414 
1415   if (DiffOps.size() == SA->getNumOperands())
1416     return nullptr;
1417 
1418   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1419   // `Step`:
1420 
1421   // 1. NSW/NUW flags on the step increment.
1422   auto PreStartFlags =
1423     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1424   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1425   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1426       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1427 
1428   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1429   // "S+X does not sign/unsign-overflow".
1430   //
1431 
1432   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1433   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1434       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1435     return PreStart;
1436 
1437   // 2. Direct overflow check on the step operation's expression.
1438   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1439   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1440   const SCEV *OperandExtendedStart =
1441       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1442                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1443   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1444     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1445       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1446       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1447       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1448       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1449     }
1450     return PreStart;
1451   }
1452 
1453   // 3. Loop precondition.
1454   ICmpInst::Predicate Pred;
1455   const SCEV *OverflowLimit =
1456       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1457 
1458   if (OverflowLimit &&
1459       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1460     return PreStart;
1461 
1462   return nullptr;
1463 }
1464 
1465 // Get the normalized zero or sign extended expression for this AddRec's Start.
1466 template <typename ExtendOpTy>
1467 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1468                                         ScalarEvolution *SE,
1469                                         unsigned Depth) {
1470   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1471 
1472   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1473   if (!PreStart)
1474     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1475 
1476   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1477                                              Depth),
1478                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1479 }
1480 
1481 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1482 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1483 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1484 //
1485 // Formally:
1486 //
1487 //     {S,+,X} == {S-T,+,X} + T
1488 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1489 //
1490 // If ({S-T,+,X} + T) does not overflow  ... (1)
1491 //
1492 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1493 //
1494 // If {S-T,+,X} does not overflow  ... (2)
1495 //
1496 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1497 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1498 //
1499 // If (S-T)+T does not overflow  ... (3)
1500 //
1501 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1502 //      == {Ext(S),+,Ext(X)} == LHS
1503 //
1504 // Thus, if (1), (2) and (3) are true for some T, then
1505 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1506 //
1507 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1508 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1509 // to check for (1) and (2).
1510 //
1511 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1512 // is `Delta` (defined below).
1513 template <typename ExtendOpTy>
1514 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1515                                                 const SCEV *Step,
1516                                                 const Loop *L) {
1517   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1518 
1519   // We restrict `Start` to a constant to prevent SCEV from spending too much
1520   // time here.  It is correct (but more expensive) to continue with a
1521   // non-constant `Start` and do a general SCEV subtraction to compute
1522   // `PreStart` below.
1523   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1524   if (!StartC)
1525     return false;
1526 
1527   APInt StartAI = StartC->getAPInt();
1528 
1529   for (unsigned Delta : {-2, -1, 1, 2}) {
1530     const SCEV *PreStart = getConstant(StartAI - Delta);
1531 
1532     FoldingSetNodeID ID;
1533     ID.AddInteger(scAddRecExpr);
1534     ID.AddPointer(PreStart);
1535     ID.AddPointer(Step);
1536     ID.AddPointer(L);
1537     void *IP = nullptr;
1538     const auto *PreAR =
1539       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1540 
1541     // Give up if we don't already have the add recurrence we need because
1542     // actually constructing an add recurrence is relatively expensive.
1543     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1544       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1545       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1546       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1547           DeltaS, &Pred, this);
1548       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1549         return true;
1550     }
1551   }
1552 
1553   return false;
1554 }
1555 
1556 // Finds an integer D for an expression (C + x + y + ...) such that the top
1557 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1558 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1559 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1560 // the (C + x + y + ...) expression is \p WholeAddExpr.
1561 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1562                                             const SCEVConstant *ConstantTerm,
1563                                             const SCEVAddExpr *WholeAddExpr) {
1564   const APInt &C = ConstantTerm->getAPInt();
1565   const unsigned BitWidth = C.getBitWidth();
1566   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1567   uint32_t TZ = BitWidth;
1568   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1569     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1570   if (TZ) {
1571     // Set D to be as many least significant bits of C as possible while still
1572     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1573     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1574   }
1575   return APInt(BitWidth, 0);
1576 }
1577 
1578 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1579 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1580 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1581 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1582 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1583                                             const APInt &ConstantStart,
1584                                             const SCEV *Step) {
1585   const unsigned BitWidth = ConstantStart.getBitWidth();
1586   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1587   if (TZ)
1588     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1589                          : ConstantStart;
1590   return APInt(BitWidth, 0);
1591 }
1592 
1593 const SCEV *
1594 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1595   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1596          "This is not an extending conversion!");
1597   assert(isSCEVable(Ty) &&
1598          "This is not a conversion to a SCEVable type!");
1599   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1600   Ty = getEffectiveSCEVType(Ty);
1601 
1602   // Fold if the operand is constant.
1603   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1604     return getConstant(
1605       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1606 
1607   // zext(zext(x)) --> zext(x)
1608   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1609     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1610 
1611   // Before doing any expensive analysis, check to see if we've already
1612   // computed a SCEV for this Op and Ty.
1613   FoldingSetNodeID ID;
1614   ID.AddInteger(scZeroExtend);
1615   ID.AddPointer(Op);
1616   ID.AddPointer(Ty);
1617   void *IP = nullptr;
1618   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1619   if (Depth > MaxCastDepth) {
1620     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1621                                                      Op, Ty);
1622     UniqueSCEVs.InsertNode(S, IP);
1623     registerUser(S, Op);
1624     return S;
1625   }
1626 
1627   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1628   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1629     // It's possible the bits taken off by the truncate were all zero bits. If
1630     // so, we should be able to simplify this further.
1631     const SCEV *X = ST->getOperand();
1632     ConstantRange CR = getUnsignedRange(X);
1633     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1634     unsigned NewBits = getTypeSizeInBits(Ty);
1635     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1636             CR.zextOrTrunc(NewBits)))
1637       return getTruncateOrZeroExtend(X, Ty, Depth);
1638   }
1639 
1640   // If the input value is a chrec scev, and we can prove that the value
1641   // did not overflow the old, smaller, value, we can zero extend all of the
1642   // operands (often constants).  This allows analysis of something like
1643   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1644   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1645     if (AR->isAffine()) {
1646       const SCEV *Start = AR->getStart();
1647       const SCEV *Step = AR->getStepRecurrence(*this);
1648       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1649       const Loop *L = AR->getLoop();
1650 
1651       if (!AR->hasNoUnsignedWrap()) {
1652         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1653         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1654       }
1655 
1656       // If we have special knowledge that this addrec won't overflow,
1657       // we don't need to do any further analysis.
1658       if (AR->hasNoUnsignedWrap()) {
1659         Start =
1660             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1661         Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1662         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1663       }
1664 
1665       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1666       // Note that this serves two purposes: It filters out loops that are
1667       // simply not analyzable, and it covers the case where this code is
1668       // being called from within backedge-taken count analysis, such that
1669       // attempting to ask for the backedge-taken count would likely result
1670       // in infinite recursion. In the later case, the analysis code will
1671       // cope with a conservative value, and it will take care to purge
1672       // that value once it has finished.
1673       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1674       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1675         // Manually compute the final value for AR, checking for overflow.
1676 
1677         // Check whether the backedge-taken count can be losslessly casted to
1678         // the addrec's type. The count is always unsigned.
1679         const SCEV *CastedMaxBECount =
1680             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1681         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1682             CastedMaxBECount, MaxBECount->getType(), Depth);
1683         if (MaxBECount == RecastedMaxBECount) {
1684           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1685           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1686           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1687                                         SCEV::FlagAnyWrap, Depth + 1);
1688           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1689                                                           SCEV::FlagAnyWrap,
1690                                                           Depth + 1),
1691                                                WideTy, Depth + 1);
1692           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1693           const SCEV *WideMaxBECount =
1694             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1695           const SCEV *OperandExtendedAdd =
1696             getAddExpr(WideStart,
1697                        getMulExpr(WideMaxBECount,
1698                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1699                                   SCEV::FlagAnyWrap, Depth + 1),
1700                        SCEV::FlagAnyWrap, Depth + 1);
1701           if (ZAdd == OperandExtendedAdd) {
1702             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1703             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1704             // Return the expression with the addrec on the outside.
1705             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1706                                                              Depth + 1);
1707             Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1708             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1709           }
1710           // Similar to above, only this time treat the step value as signed.
1711           // This covers loops that count down.
1712           OperandExtendedAdd =
1713             getAddExpr(WideStart,
1714                        getMulExpr(WideMaxBECount,
1715                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1716                                   SCEV::FlagAnyWrap, Depth + 1),
1717                        SCEV::FlagAnyWrap, Depth + 1);
1718           if (ZAdd == OperandExtendedAdd) {
1719             // Cache knowledge of AR NW, which is propagated to this AddRec.
1720             // Negative step causes unsigned wrap, but it still can't self-wrap.
1721             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1722             // Return the expression with the addrec on the outside.
1723             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1724                                                              Depth + 1);
1725             Step = getSignExtendExpr(Step, Ty, Depth + 1);
1726             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1727           }
1728         }
1729       }
1730 
1731       // Normally, in the cases we can prove no-overflow via a
1732       // backedge guarding condition, we can also compute a backedge
1733       // taken count for the loop.  The exceptions are assumptions and
1734       // guards present in the loop -- SCEV is not great at exploiting
1735       // these to compute max backedge taken counts, but can still use
1736       // these to prove lack of overflow.  Use this fact to avoid
1737       // doing extra work that may not pay off.
1738       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1739           !AC.assumptions().empty()) {
1740 
1741         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1742         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1743         if (AR->hasNoUnsignedWrap()) {
1744           // Same as nuw case above - duplicated here to avoid a compile time
1745           // issue.  It's not clear that the order of checks does matter, but
1746           // it's one of two issue possible causes for a change which was
1747           // reverted.  Be conservative for the moment.
1748           Start =
1749               getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1750           Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1751           return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1752         }
1753 
1754         // For a negative step, we can extend the operands iff doing so only
1755         // traverses values in the range zext([0,UINT_MAX]).
1756         if (isKnownNegative(Step)) {
1757           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1758                                       getSignedRangeMin(Step));
1759           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1760               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1761             // Cache knowledge of AR NW, which is propagated to this
1762             // AddRec.  Negative step causes unsigned wrap, but it
1763             // still can't self-wrap.
1764             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1765             // Return the expression with the addrec on the outside.
1766             Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1767                                                              Depth + 1);
1768             Step = getSignExtendExpr(Step, Ty, Depth + 1);
1769             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1770           }
1771         }
1772       }
1773 
1774       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1775       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1776       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1777       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1778         const APInt &C = SC->getAPInt();
1779         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1780         if (D != 0) {
1781           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1782           const SCEV *SResidual =
1783               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1784           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1785           return getAddExpr(SZExtD, SZExtR,
1786                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1787                             Depth + 1);
1788         }
1789       }
1790 
1791       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1792         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1793         Start =
1794             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1795         Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1796         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1797       }
1798     }
1799 
1800   // zext(A % B) --> zext(A) % zext(B)
1801   {
1802     const SCEV *LHS;
1803     const SCEV *RHS;
1804     if (matchURem(Op, LHS, RHS))
1805       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1806                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1807   }
1808 
1809   // zext(A / B) --> zext(A) / zext(B).
1810   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1811     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1812                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1813 
1814   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1815     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1816     if (SA->hasNoUnsignedWrap()) {
1817       // If the addition does not unsign overflow then we can, by definition,
1818       // commute the zero extension with the addition operation.
1819       SmallVector<const SCEV *, 4> Ops;
1820       for (const auto *Op : SA->operands())
1821         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1822       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1823     }
1824 
1825     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1826     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1827     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1828     //
1829     // Often address arithmetics contain expressions like
1830     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1831     // This transformation is useful while proving that such expressions are
1832     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1833     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1834       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1835       if (D != 0) {
1836         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1837         const SCEV *SResidual =
1838             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1839         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1840         return getAddExpr(SZExtD, SZExtR,
1841                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1842                           Depth + 1);
1843       }
1844     }
1845   }
1846 
1847   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1848     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1849     if (SM->hasNoUnsignedWrap()) {
1850       // If the multiply does not unsign overflow then we can, by definition,
1851       // commute the zero extension with the multiply operation.
1852       SmallVector<const SCEV *, 4> Ops;
1853       for (const auto *Op : SM->operands())
1854         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1855       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1856     }
1857 
1858     // zext(2^K * (trunc X to iN)) to iM ->
1859     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1860     //
1861     // Proof:
1862     //
1863     //     zext(2^K * (trunc X to iN)) to iM
1864     //   = zext((trunc X to iN) << K) to iM
1865     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1866     //     (because shl removes the top K bits)
1867     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1868     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1869     //
1870     if (SM->getNumOperands() == 2)
1871       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1872         if (MulLHS->getAPInt().isPowerOf2())
1873           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1874             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1875                                MulLHS->getAPInt().logBase2();
1876             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1877             return getMulExpr(
1878                 getZeroExtendExpr(MulLHS, Ty),
1879                 getZeroExtendExpr(
1880                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1881                 SCEV::FlagNUW, Depth + 1);
1882           }
1883   }
1884 
1885   // The cast wasn't folded; create an explicit cast node.
1886   // Recompute the insert position, as it may have been invalidated.
1887   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1888   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1889                                                    Op, Ty);
1890   UniqueSCEVs.InsertNode(S, IP);
1891   registerUser(S, Op);
1892   return S;
1893 }
1894 
1895 const SCEV *
1896 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1897   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1898          "This is not an extending conversion!");
1899   assert(isSCEVable(Ty) &&
1900          "This is not a conversion to a SCEVable type!");
1901   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1902   Ty = getEffectiveSCEVType(Ty);
1903 
1904   // Fold if the operand is constant.
1905   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1906     return getConstant(
1907       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1908 
1909   // sext(sext(x)) --> sext(x)
1910   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1911     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1912 
1913   // sext(zext(x)) --> zext(x)
1914   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1915     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1916 
1917   // Before doing any expensive analysis, check to see if we've already
1918   // computed a SCEV for this Op and Ty.
1919   FoldingSetNodeID ID;
1920   ID.AddInteger(scSignExtend);
1921   ID.AddPointer(Op);
1922   ID.AddPointer(Ty);
1923   void *IP = nullptr;
1924   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1925   // Limit recursion depth.
1926   if (Depth > MaxCastDepth) {
1927     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1928                                                      Op, Ty);
1929     UniqueSCEVs.InsertNode(S, IP);
1930     registerUser(S, Op);
1931     return S;
1932   }
1933 
1934   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1935   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1936     // It's possible the bits taken off by the truncate were all sign bits. If
1937     // so, we should be able to simplify this further.
1938     const SCEV *X = ST->getOperand();
1939     ConstantRange CR = getSignedRange(X);
1940     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1941     unsigned NewBits = getTypeSizeInBits(Ty);
1942     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1943             CR.sextOrTrunc(NewBits)))
1944       return getTruncateOrSignExtend(X, Ty, Depth);
1945   }
1946 
1947   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1948     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1949     if (SA->hasNoSignedWrap()) {
1950       // If the addition does not sign overflow then we can, by definition,
1951       // commute the sign extension with the addition operation.
1952       SmallVector<const SCEV *, 4> Ops;
1953       for (const auto *Op : SA->operands())
1954         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1955       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1956     }
1957 
1958     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1959     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1960     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1961     //
1962     // For instance, this will bring two seemingly different expressions:
1963     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1964     //         sext(6 + 20 * %x + 24 * %y)
1965     // to the same form:
1966     //     2 + sext(4 + 20 * %x + 24 * %y)
1967     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1968       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1969       if (D != 0) {
1970         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1971         const SCEV *SResidual =
1972             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1973         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1974         return getAddExpr(SSExtD, SSExtR,
1975                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1976                           Depth + 1);
1977       }
1978     }
1979   }
1980   // If the input value is a chrec scev, and we can prove that the value
1981   // did not overflow the old, smaller, value, we can sign extend all of the
1982   // operands (often constants).  This allows analysis of something like
1983   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1984   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1985     if (AR->isAffine()) {
1986       const SCEV *Start = AR->getStart();
1987       const SCEV *Step = AR->getStepRecurrence(*this);
1988       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1989       const Loop *L = AR->getLoop();
1990 
1991       if (!AR->hasNoSignedWrap()) {
1992         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1993         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1994       }
1995 
1996       // If we have special knowledge that this addrec won't overflow,
1997       // we don't need to do any further analysis.
1998       if (AR->hasNoSignedWrap()) {
1999         Start =
2000             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2001         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2002         return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2003       }
2004 
2005       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2006       // Note that this serves two purposes: It filters out loops that are
2007       // simply not analyzable, and it covers the case where this code is
2008       // being called from within backedge-taken count analysis, such that
2009       // attempting to ask for the backedge-taken count would likely result
2010       // in infinite recursion. In the later case, the analysis code will
2011       // cope with a conservative value, and it will take care to purge
2012       // that value once it has finished.
2013       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2014       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2015         // Manually compute the final value for AR, checking for
2016         // overflow.
2017 
2018         // Check whether the backedge-taken count can be losslessly casted to
2019         // the addrec's type. The count is always unsigned.
2020         const SCEV *CastedMaxBECount =
2021             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2022         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2023             CastedMaxBECount, MaxBECount->getType(), Depth);
2024         if (MaxBECount == RecastedMaxBECount) {
2025           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2026           // Check whether Start+Step*MaxBECount has no signed overflow.
2027           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2028                                         SCEV::FlagAnyWrap, Depth + 1);
2029           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2030                                                           SCEV::FlagAnyWrap,
2031                                                           Depth + 1),
2032                                                WideTy, Depth + 1);
2033           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2034           const SCEV *WideMaxBECount =
2035             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2036           const SCEV *OperandExtendedAdd =
2037             getAddExpr(WideStart,
2038                        getMulExpr(WideMaxBECount,
2039                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2040                                   SCEV::FlagAnyWrap, Depth + 1),
2041                        SCEV::FlagAnyWrap, Depth + 1);
2042           if (SAdd == OperandExtendedAdd) {
2043             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2044             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2045             // Return the expression with the addrec on the outside.
2046             Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2047                                                              Depth + 1);
2048             Step = getSignExtendExpr(Step, Ty, Depth + 1);
2049             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2050           }
2051           // Similar to above, only this time treat the step value as unsigned.
2052           // This covers loops that count up with an unsigned step.
2053           OperandExtendedAdd =
2054             getAddExpr(WideStart,
2055                        getMulExpr(WideMaxBECount,
2056                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2057                                   SCEV::FlagAnyWrap, Depth + 1),
2058                        SCEV::FlagAnyWrap, Depth + 1);
2059           if (SAdd == OperandExtendedAdd) {
2060             // If AR wraps around then
2061             //
2062             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2063             // => SAdd != OperandExtendedAdd
2064             //
2065             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2066             // (SAdd == OperandExtendedAdd => AR is NW)
2067 
2068             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2069 
2070             // Return the expression with the addrec on the outside.
2071             Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2072                                                              Depth + 1);
2073             Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2074             return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2075           }
2076         }
2077       }
2078 
2079       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2080       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2081       if (AR->hasNoSignedWrap()) {
2082         // Same as nsw case above - duplicated here to avoid a compile time
2083         // issue.  It's not clear that the order of checks does matter, but
2084         // it's one of two issue possible causes for a change which was
2085         // reverted.  Be conservative for the moment.
2086         Start =
2087             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2088         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2089         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2090       }
2091 
2092       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2093       // if D + (C - D + Step * n) could be proven to not signed wrap
2094       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2095       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2096         const APInt &C = SC->getAPInt();
2097         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2098         if (D != 0) {
2099           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2100           const SCEV *SResidual =
2101               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2102           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2103           return getAddExpr(SSExtD, SSExtR,
2104                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2105                             Depth + 1);
2106         }
2107       }
2108 
2109       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2110         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2111         Start =
2112             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2113         Step = getSignExtendExpr(Step, Ty, Depth + 1);
2114         return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2115       }
2116     }
2117 
2118   // If the input value is provably positive and we could not simplify
2119   // away the sext build a zext instead.
2120   if (isKnownNonNegative(Op))
2121     return getZeroExtendExpr(Op, Ty, Depth + 1);
2122 
2123   // The cast wasn't folded; create an explicit cast node.
2124   // Recompute the insert position, as it may have been invalidated.
2125   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2126   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2127                                                    Op, Ty);
2128   UniqueSCEVs.InsertNode(S, IP);
2129   registerUser(S, { Op });
2130   return S;
2131 }
2132 
2133 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2134                                          Type *Ty) {
2135   switch (Kind) {
2136   case scTruncate:
2137     return getTruncateExpr(Op, Ty);
2138   case scZeroExtend:
2139     return getZeroExtendExpr(Op, Ty);
2140   case scSignExtend:
2141     return getSignExtendExpr(Op, Ty);
2142   case scPtrToInt:
2143     return getPtrToIntExpr(Op, Ty);
2144   default:
2145     llvm_unreachable("Not a SCEV cast expression!");
2146   }
2147 }
2148 
2149 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2150 /// unspecified bits out to the given type.
2151 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2152                                               Type *Ty) {
2153   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2154          "This is not an extending conversion!");
2155   assert(isSCEVable(Ty) &&
2156          "This is not a conversion to a SCEVable type!");
2157   Ty = getEffectiveSCEVType(Ty);
2158 
2159   // Sign-extend negative constants.
2160   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2161     if (SC->getAPInt().isNegative())
2162       return getSignExtendExpr(Op, Ty);
2163 
2164   // Peel off a truncate cast.
2165   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2166     const SCEV *NewOp = T->getOperand();
2167     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2168       return getAnyExtendExpr(NewOp, Ty);
2169     return getTruncateOrNoop(NewOp, Ty);
2170   }
2171 
2172   // Next try a zext cast. If the cast is folded, use it.
2173   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2174   if (!isa<SCEVZeroExtendExpr>(ZExt))
2175     return ZExt;
2176 
2177   // Next try a sext cast. If the cast is folded, use it.
2178   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2179   if (!isa<SCEVSignExtendExpr>(SExt))
2180     return SExt;
2181 
2182   // Force the cast to be folded into the operands of an addrec.
2183   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2184     SmallVector<const SCEV *, 4> Ops;
2185     for (const SCEV *Op : AR->operands())
2186       Ops.push_back(getAnyExtendExpr(Op, Ty));
2187     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2188   }
2189 
2190   // If the expression is obviously signed, use the sext cast value.
2191   if (isa<SCEVSMaxExpr>(Op))
2192     return SExt;
2193 
2194   // Absent any other information, use the zext cast value.
2195   return ZExt;
2196 }
2197 
2198 /// Process the given Ops list, which is a list of operands to be added under
2199 /// the given scale, update the given map. This is a helper function for
2200 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2201 /// that would form an add expression like this:
2202 ///
2203 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2204 ///
2205 /// where A and B are constants, update the map with these values:
2206 ///
2207 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2208 ///
2209 /// and add 13 + A*B*29 to AccumulatedConstant.
2210 /// This will allow getAddRecExpr to produce this:
2211 ///
2212 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2213 ///
2214 /// This form often exposes folding opportunities that are hidden in
2215 /// the original operand list.
2216 ///
2217 /// Return true iff it appears that any interesting folding opportunities
2218 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2219 /// the common case where no interesting opportunities are present, and
2220 /// is also used as a check to avoid infinite recursion.
2221 static bool
2222 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2223                              SmallVectorImpl<const SCEV *> &NewOps,
2224                              APInt &AccumulatedConstant,
2225                              const SCEV *const *Ops, size_t NumOperands,
2226                              const APInt &Scale,
2227                              ScalarEvolution &SE) {
2228   bool Interesting = false;
2229 
2230   // Iterate over the add operands. They are sorted, with constants first.
2231   unsigned i = 0;
2232   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2233     ++i;
2234     // Pull a buried constant out to the outside.
2235     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2236       Interesting = true;
2237     AccumulatedConstant += Scale * C->getAPInt();
2238   }
2239 
2240   // Next comes everything else. We're especially interested in multiplies
2241   // here, but they're in the middle, so just visit the rest with one loop.
2242   for (; i != NumOperands; ++i) {
2243     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2244     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2245       APInt NewScale =
2246           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2247       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2248         // A multiplication of a constant with another add; recurse.
2249         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2250         Interesting |=
2251           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2252                                        Add->op_begin(), Add->getNumOperands(),
2253                                        NewScale, SE);
2254       } else {
2255         // A multiplication of a constant with some other value. Update
2256         // the map.
2257         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2258         const SCEV *Key = SE.getMulExpr(MulOps);
2259         auto Pair = M.insert({Key, NewScale});
2260         if (Pair.second) {
2261           NewOps.push_back(Pair.first->first);
2262         } else {
2263           Pair.first->second += NewScale;
2264           // The map already had an entry for this value, which may indicate
2265           // a folding opportunity.
2266           Interesting = true;
2267         }
2268       }
2269     } else {
2270       // An ordinary operand. Update the map.
2271       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2272           M.insert({Ops[i], Scale});
2273       if (Pair.second) {
2274         NewOps.push_back(Pair.first->first);
2275       } else {
2276         Pair.first->second += Scale;
2277         // The map already had an entry for this value, which may indicate
2278         // a folding opportunity.
2279         Interesting = true;
2280       }
2281     }
2282   }
2283 
2284   return Interesting;
2285 }
2286 
2287 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2288                                       const SCEV *LHS, const SCEV *RHS) {
2289   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2290                                             SCEV::NoWrapFlags, unsigned);
2291   switch (BinOp) {
2292   default:
2293     llvm_unreachable("Unsupported binary op");
2294   case Instruction::Add:
2295     Operation = &ScalarEvolution::getAddExpr;
2296     break;
2297   case Instruction::Sub:
2298     Operation = &ScalarEvolution::getMinusSCEV;
2299     break;
2300   case Instruction::Mul:
2301     Operation = &ScalarEvolution::getMulExpr;
2302     break;
2303   }
2304 
2305   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2306       Signed ? &ScalarEvolution::getSignExtendExpr
2307              : &ScalarEvolution::getZeroExtendExpr;
2308 
2309   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2310   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2311   auto *WideTy =
2312       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2313 
2314   const SCEV *A = (this->*Extension)(
2315       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2316   const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2317   const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2318   const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2319   return A == B;
2320 }
2321 
2322 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2323 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2324     const OverflowingBinaryOperator *OBO) {
2325   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2326 
2327   if (OBO->hasNoUnsignedWrap())
2328     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2329   if (OBO->hasNoSignedWrap())
2330     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2331 
2332   bool Deduced = false;
2333 
2334   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2335     return {Flags, Deduced};
2336 
2337   if (OBO->getOpcode() != Instruction::Add &&
2338       OBO->getOpcode() != Instruction::Sub &&
2339       OBO->getOpcode() != Instruction::Mul)
2340     return {Flags, Deduced};
2341 
2342   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2343   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2344 
2345   if (!OBO->hasNoUnsignedWrap() &&
2346       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2347                       /* Signed */ false, LHS, RHS)) {
2348     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2349     Deduced = true;
2350   }
2351 
2352   if (!OBO->hasNoSignedWrap() &&
2353       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2354                       /* Signed */ true, LHS, RHS)) {
2355     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2356     Deduced = true;
2357   }
2358 
2359   return {Flags, Deduced};
2360 }
2361 
2362 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2363 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2364 // can't-overflow flags for the operation if possible.
2365 static SCEV::NoWrapFlags
2366 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2367                       const ArrayRef<const SCEV *> Ops,
2368                       SCEV::NoWrapFlags Flags) {
2369   using namespace std::placeholders;
2370 
2371   using OBO = OverflowingBinaryOperator;
2372 
2373   bool CanAnalyze =
2374       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2375   (void)CanAnalyze;
2376   assert(CanAnalyze && "don't call from other places!");
2377 
2378   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2379   SCEV::NoWrapFlags SignOrUnsignWrap =
2380       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2381 
2382   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2383   auto IsKnownNonNegative = [&](const SCEV *S) {
2384     return SE->isKnownNonNegative(S);
2385   };
2386 
2387   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2388     Flags =
2389         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2390 
2391   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2392 
2393   if (SignOrUnsignWrap != SignOrUnsignMask &&
2394       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2395       isa<SCEVConstant>(Ops[0])) {
2396 
2397     auto Opcode = [&] {
2398       switch (Type) {
2399       case scAddExpr:
2400         return Instruction::Add;
2401       case scMulExpr:
2402         return Instruction::Mul;
2403       default:
2404         llvm_unreachable("Unexpected SCEV op.");
2405       }
2406     }();
2407 
2408     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2409 
2410     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2411     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2412       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2413           Opcode, C, OBO::NoSignedWrap);
2414       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2415         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2416     }
2417 
2418     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2419     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2420       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2421           Opcode, C, OBO::NoUnsignedWrap);
2422       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2423         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2424     }
2425   }
2426 
2427   // <0,+,nonnegative><nw> is also nuw
2428   // TODO: Add corresponding nsw case
2429   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2430       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2431       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2432     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2433 
2434   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2435   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2436       Ops.size() == 2) {
2437     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2438       if (UDiv->getOperand(1) == Ops[1])
2439         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2440     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2441       if (UDiv->getOperand(1) == Ops[0])
2442         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2443   }
2444 
2445   return Flags;
2446 }
2447 
2448 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2449   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2450 }
2451 
2452 /// Get a canonical add expression, or something simpler if possible.
2453 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2454                                         SCEV::NoWrapFlags OrigFlags,
2455                                         unsigned Depth) {
2456   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2457          "only nuw or nsw allowed");
2458   assert(!Ops.empty() && "Cannot get empty add!");
2459   if (Ops.size() == 1) return Ops[0];
2460 #ifndef NDEBUG
2461   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2462   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2463     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2464            "SCEVAddExpr operand types don't match!");
2465   unsigned NumPtrs = count_if(
2466       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2467   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2468 #endif
2469 
2470   // Sort by complexity, this groups all similar expression types together.
2471   GroupByComplexity(Ops, &LI, DT);
2472 
2473   // If there are any constants, fold them together.
2474   unsigned Idx = 0;
2475   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2476     ++Idx;
2477     assert(Idx < Ops.size());
2478     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2479       // We found two constants, fold them together!
2480       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2481       if (Ops.size() == 2) return Ops[0];
2482       Ops.erase(Ops.begin()+1);  // Erase the folded element
2483       LHSC = cast<SCEVConstant>(Ops[0]);
2484     }
2485 
2486     // If we are left with a constant zero being added, strip it off.
2487     if (LHSC->getValue()->isZero()) {
2488       Ops.erase(Ops.begin());
2489       --Idx;
2490     }
2491 
2492     if (Ops.size() == 1) return Ops[0];
2493   }
2494 
2495   // Delay expensive flag strengthening until necessary.
2496   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2497     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2498   };
2499 
2500   // Limit recursion calls depth.
2501   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2502     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2503 
2504   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2505     // Don't strengthen flags if we have no new information.
2506     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2507     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2508       Add->setNoWrapFlags(ComputeFlags(Ops));
2509     return S;
2510   }
2511 
2512   // Okay, check to see if the same value occurs in the operand list more than
2513   // once.  If so, merge them together into an multiply expression.  Since we
2514   // sorted the list, these values are required to be adjacent.
2515   Type *Ty = Ops[0]->getType();
2516   bool FoundMatch = false;
2517   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2518     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2519       // Scan ahead to count how many equal operands there are.
2520       unsigned Count = 2;
2521       while (i+Count != e && Ops[i+Count] == Ops[i])
2522         ++Count;
2523       // Merge the values into a multiply.
2524       const SCEV *Scale = getConstant(Ty, Count);
2525       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2526       if (Ops.size() == Count)
2527         return Mul;
2528       Ops[i] = Mul;
2529       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2530       --i; e -= Count - 1;
2531       FoundMatch = true;
2532     }
2533   if (FoundMatch)
2534     return getAddExpr(Ops, OrigFlags, Depth + 1);
2535 
2536   // Check for truncates. If all the operands are truncated from the same
2537   // type, see if factoring out the truncate would permit the result to be
2538   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2539   // if the contents of the resulting outer trunc fold to something simple.
2540   auto FindTruncSrcType = [&]() -> Type * {
2541     // We're ultimately looking to fold an addrec of truncs and muls of only
2542     // constants and truncs, so if we find any other types of SCEV
2543     // as operands of the addrec then we bail and return nullptr here.
2544     // Otherwise, we return the type of the operand of a trunc that we find.
2545     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2546       return T->getOperand()->getType();
2547     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2548       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2549       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2550         return T->getOperand()->getType();
2551     }
2552     return nullptr;
2553   };
2554   if (auto *SrcType = FindTruncSrcType()) {
2555     SmallVector<const SCEV *, 8> LargeOps;
2556     bool Ok = true;
2557     // Check all the operands to see if they can be represented in the
2558     // source type of the truncate.
2559     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2560       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2561         if (T->getOperand()->getType() != SrcType) {
2562           Ok = false;
2563           break;
2564         }
2565         LargeOps.push_back(T->getOperand());
2566       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2567         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2568       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2569         SmallVector<const SCEV *, 8> LargeMulOps;
2570         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2571           if (const SCEVTruncateExpr *T =
2572                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2573             if (T->getOperand()->getType() != SrcType) {
2574               Ok = false;
2575               break;
2576             }
2577             LargeMulOps.push_back(T->getOperand());
2578           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2579             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2580           } else {
2581             Ok = false;
2582             break;
2583           }
2584         }
2585         if (Ok)
2586           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2587       } else {
2588         Ok = false;
2589         break;
2590       }
2591     }
2592     if (Ok) {
2593       // Evaluate the expression in the larger type.
2594       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2595       // If it folds to something simple, use it. Otherwise, don't.
2596       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2597         return getTruncateExpr(Fold, Ty);
2598     }
2599   }
2600 
2601   if (Ops.size() == 2) {
2602     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2603     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2604     // C1).
2605     const SCEV *A = Ops[0];
2606     const SCEV *B = Ops[1];
2607     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2608     auto *C = dyn_cast<SCEVConstant>(A);
2609     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2610       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2611       auto C2 = C->getAPInt();
2612       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2613 
2614       APInt ConstAdd = C1 + C2;
2615       auto AddFlags = AddExpr->getNoWrapFlags();
2616       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2617       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2618           ConstAdd.ule(C1)) {
2619         PreservedFlags =
2620             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2621       }
2622 
2623       // Adding a constant with the same sign and small magnitude is NSW, if the
2624       // original AddExpr was NSW.
2625       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2626           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2627           ConstAdd.abs().ule(C1.abs())) {
2628         PreservedFlags =
2629             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2630       }
2631 
2632       if (PreservedFlags != SCEV::FlagAnyWrap) {
2633         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2634         NewOps[0] = getConstant(ConstAdd);
2635         return getAddExpr(NewOps, PreservedFlags);
2636       }
2637     }
2638   }
2639 
2640   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2641   if (Ops.size() == 2) {
2642     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2643     if (Mul && Mul->getNumOperands() == 2 &&
2644         Mul->getOperand(0)->isAllOnesValue()) {
2645       const SCEV *X;
2646       const SCEV *Y;
2647       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2648         return getMulExpr(Y, getUDivExpr(X, Y));
2649       }
2650     }
2651   }
2652 
2653   // Skip past any other cast SCEVs.
2654   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2655     ++Idx;
2656 
2657   // If there are add operands they would be next.
2658   if (Idx < Ops.size()) {
2659     bool DeletedAdd = false;
2660     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2661     // common NUW flag for expression after inlining. Other flags cannot be
2662     // preserved, because they may depend on the original order of operations.
2663     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2664     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2665       if (Ops.size() > AddOpsInlineThreshold ||
2666           Add->getNumOperands() > AddOpsInlineThreshold)
2667         break;
2668       // If we have an add, expand the add operands onto the end of the operands
2669       // list.
2670       Ops.erase(Ops.begin()+Idx);
2671       Ops.append(Add->op_begin(), Add->op_end());
2672       DeletedAdd = true;
2673       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2674     }
2675 
2676     // If we deleted at least one add, we added operands to the end of the list,
2677     // and they are not necessarily sorted.  Recurse to resort and resimplify
2678     // any operands we just acquired.
2679     if (DeletedAdd)
2680       return getAddExpr(Ops, CommonFlags, Depth + 1);
2681   }
2682 
2683   // Skip over the add expression until we get to a multiply.
2684   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2685     ++Idx;
2686 
2687   // Check to see if there are any folding opportunities present with
2688   // operands multiplied by constant values.
2689   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2690     uint64_t BitWidth = getTypeSizeInBits(Ty);
2691     DenseMap<const SCEV *, APInt> M;
2692     SmallVector<const SCEV *, 8> NewOps;
2693     APInt AccumulatedConstant(BitWidth, 0);
2694     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2695                                      Ops.data(), Ops.size(),
2696                                      APInt(BitWidth, 1), *this)) {
2697       struct APIntCompare {
2698         bool operator()(const APInt &LHS, const APInt &RHS) const {
2699           return LHS.ult(RHS);
2700         }
2701       };
2702 
2703       // Some interesting folding opportunity is present, so its worthwhile to
2704       // re-generate the operands list. Group the operands by constant scale,
2705       // to avoid multiplying by the same constant scale multiple times.
2706       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2707       for (const SCEV *NewOp : NewOps)
2708         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2709       // Re-generate the operands list.
2710       Ops.clear();
2711       if (AccumulatedConstant != 0)
2712         Ops.push_back(getConstant(AccumulatedConstant));
2713       for (auto &MulOp : MulOpLists) {
2714         if (MulOp.first == 1) {
2715           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2716         } else if (MulOp.first != 0) {
2717           Ops.push_back(getMulExpr(
2718               getConstant(MulOp.first),
2719               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2720               SCEV::FlagAnyWrap, Depth + 1));
2721         }
2722       }
2723       if (Ops.empty())
2724         return getZero(Ty);
2725       if (Ops.size() == 1)
2726         return Ops[0];
2727       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2728     }
2729   }
2730 
2731   // If we are adding something to a multiply expression, make sure the
2732   // something is not already an operand of the multiply.  If so, merge it into
2733   // the multiply.
2734   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2735     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2736     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2737       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2738       if (isa<SCEVConstant>(MulOpSCEV))
2739         continue;
2740       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2741         if (MulOpSCEV == Ops[AddOp]) {
2742           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2743           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2744           if (Mul->getNumOperands() != 2) {
2745             // If the multiply has more than two operands, we must get the
2746             // Y*Z term.
2747             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2748                                                 Mul->op_begin()+MulOp);
2749             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2750             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2751           }
2752           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2753           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2754           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2755                                             SCEV::FlagAnyWrap, Depth + 1);
2756           if (Ops.size() == 2) return OuterMul;
2757           if (AddOp < Idx) {
2758             Ops.erase(Ops.begin()+AddOp);
2759             Ops.erase(Ops.begin()+Idx-1);
2760           } else {
2761             Ops.erase(Ops.begin()+Idx);
2762             Ops.erase(Ops.begin()+AddOp-1);
2763           }
2764           Ops.push_back(OuterMul);
2765           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2766         }
2767 
2768       // Check this multiply against other multiplies being added together.
2769       for (unsigned OtherMulIdx = Idx+1;
2770            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2771            ++OtherMulIdx) {
2772         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2773         // If MulOp occurs in OtherMul, we can fold the two multiplies
2774         // together.
2775         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2776              OMulOp != e; ++OMulOp)
2777           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2778             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2779             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2780             if (Mul->getNumOperands() != 2) {
2781               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2782                                                   Mul->op_begin()+MulOp);
2783               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2784               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2785             }
2786             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2787             if (OtherMul->getNumOperands() != 2) {
2788               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2789                                                   OtherMul->op_begin()+OMulOp);
2790               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2791               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2792             }
2793             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2794             const SCEV *InnerMulSum =
2795                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2796             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2797                                               SCEV::FlagAnyWrap, Depth + 1);
2798             if (Ops.size() == 2) return OuterMul;
2799             Ops.erase(Ops.begin()+Idx);
2800             Ops.erase(Ops.begin()+OtherMulIdx-1);
2801             Ops.push_back(OuterMul);
2802             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2803           }
2804       }
2805     }
2806   }
2807 
2808   // If there are any add recurrences in the operands list, see if any other
2809   // added values are loop invariant.  If so, we can fold them into the
2810   // recurrence.
2811   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2812     ++Idx;
2813 
2814   // Scan over all recurrences, trying to fold loop invariants into them.
2815   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2816     // Scan all of the other operands to this add and add them to the vector if
2817     // they are loop invariant w.r.t. the recurrence.
2818     SmallVector<const SCEV *, 8> LIOps;
2819     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2820     const Loop *AddRecLoop = AddRec->getLoop();
2821     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2822       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2823         LIOps.push_back(Ops[i]);
2824         Ops.erase(Ops.begin()+i);
2825         --i; --e;
2826       }
2827 
2828     // If we found some loop invariants, fold them into the recurrence.
2829     if (!LIOps.empty()) {
2830       // Compute nowrap flags for the addition of the loop-invariant ops and
2831       // the addrec. Temporarily push it as an operand for that purpose. These
2832       // flags are valid in the scope of the addrec only.
2833       LIOps.push_back(AddRec);
2834       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2835       LIOps.pop_back();
2836 
2837       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2838       LIOps.push_back(AddRec->getStart());
2839 
2840       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2841 
2842       // It is not in general safe to propagate flags valid on an add within
2843       // the addrec scope to one outside it.  We must prove that the inner
2844       // scope is guaranteed to execute if the outer one does to be able to
2845       // safely propagate.  We know the program is undefined if poison is
2846       // produced on the inner scoped addrec.  We also know that *for this use*
2847       // the outer scoped add can't overflow (because of the flags we just
2848       // computed for the inner scoped add) without the program being undefined.
2849       // Proving that entry to the outer scope neccesitates entry to the inner
2850       // scope, thus proves the program undefined if the flags would be violated
2851       // in the outer scope.
2852       SCEV::NoWrapFlags AddFlags = Flags;
2853       if (AddFlags != SCEV::FlagAnyWrap) {
2854         auto *DefI = getDefiningScopeBound(LIOps);
2855         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2856         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2857           AddFlags = SCEV::FlagAnyWrap;
2858       }
2859       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2860 
2861       // Build the new addrec. Propagate the NUW and NSW flags if both the
2862       // outer add and the inner addrec are guaranteed to have no overflow.
2863       // Always propagate NW.
2864       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2865       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2866 
2867       // If all of the other operands were loop invariant, we are done.
2868       if (Ops.size() == 1) return NewRec;
2869 
2870       // Otherwise, add the folded AddRec by the non-invariant parts.
2871       for (unsigned i = 0;; ++i)
2872         if (Ops[i] == AddRec) {
2873           Ops[i] = NewRec;
2874           break;
2875         }
2876       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2877     }
2878 
2879     // Okay, if there weren't any loop invariants to be folded, check to see if
2880     // there are multiple AddRec's with the same loop induction variable being
2881     // added together.  If so, we can fold them.
2882     for (unsigned OtherIdx = Idx+1;
2883          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2884          ++OtherIdx) {
2885       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2886       // so that the 1st found AddRecExpr is dominated by all others.
2887       assert(DT.dominates(
2888            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2889            AddRec->getLoop()->getHeader()) &&
2890         "AddRecExprs are not sorted in reverse dominance order?");
2891       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2892         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2893         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2894         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2895              ++OtherIdx) {
2896           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2897           if (OtherAddRec->getLoop() == AddRecLoop) {
2898             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2899                  i != e; ++i) {
2900               if (i >= AddRecOps.size()) {
2901                 AddRecOps.append(OtherAddRec->op_begin()+i,
2902                                  OtherAddRec->op_end());
2903                 break;
2904               }
2905               SmallVector<const SCEV *, 2> TwoOps = {
2906                   AddRecOps[i], OtherAddRec->getOperand(i)};
2907               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2908             }
2909             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2910           }
2911         }
2912         // Step size has changed, so we cannot guarantee no self-wraparound.
2913         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2914         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2915       }
2916     }
2917 
2918     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2919     // next one.
2920   }
2921 
2922   // Okay, it looks like we really DO need an add expr.  Check to see if we
2923   // already have one, otherwise create a new one.
2924   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2925 }
2926 
2927 const SCEV *
2928 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2929                                     SCEV::NoWrapFlags Flags) {
2930   FoldingSetNodeID ID;
2931   ID.AddInteger(scAddExpr);
2932   for (const SCEV *Op : Ops)
2933     ID.AddPointer(Op);
2934   void *IP = nullptr;
2935   SCEVAddExpr *S =
2936       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2937   if (!S) {
2938     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2939     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2940     S = new (SCEVAllocator)
2941         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2942     UniqueSCEVs.InsertNode(S, IP);
2943     registerUser(S, Ops);
2944   }
2945   S->setNoWrapFlags(Flags);
2946   return S;
2947 }
2948 
2949 const SCEV *
2950 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2951                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2952   FoldingSetNodeID ID;
2953   ID.AddInteger(scAddRecExpr);
2954   for (const SCEV *Op : Ops)
2955     ID.AddPointer(Op);
2956   ID.AddPointer(L);
2957   void *IP = nullptr;
2958   SCEVAddRecExpr *S =
2959       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2960   if (!S) {
2961     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2962     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2963     S = new (SCEVAllocator)
2964         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2965     UniqueSCEVs.InsertNode(S, IP);
2966     LoopUsers[L].push_back(S);
2967     registerUser(S, Ops);
2968   }
2969   setNoWrapFlags(S, Flags);
2970   return S;
2971 }
2972 
2973 const SCEV *
2974 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2975                                     SCEV::NoWrapFlags Flags) {
2976   FoldingSetNodeID ID;
2977   ID.AddInteger(scMulExpr);
2978   for (const SCEV *Op : Ops)
2979     ID.AddPointer(Op);
2980   void *IP = nullptr;
2981   SCEVMulExpr *S =
2982     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2983   if (!S) {
2984     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2985     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2986     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2987                                         O, Ops.size());
2988     UniqueSCEVs.InsertNode(S, IP);
2989     registerUser(S, Ops);
2990   }
2991   S->setNoWrapFlags(Flags);
2992   return S;
2993 }
2994 
2995 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2996   uint64_t k = i*j;
2997   if (j > 1 && k / j != i) Overflow = true;
2998   return k;
2999 }
3000 
3001 /// Compute the result of "n choose k", the binomial coefficient.  If an
3002 /// intermediate computation overflows, Overflow will be set and the return will
3003 /// be garbage. Overflow is not cleared on absence of overflow.
3004 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3005   // We use the multiplicative formula:
3006   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3007   // At each iteration, we take the n-th term of the numeral and divide by the
3008   // (k-n)th term of the denominator.  This division will always produce an
3009   // integral result, and helps reduce the chance of overflow in the
3010   // intermediate computations. However, we can still overflow even when the
3011   // final result would fit.
3012 
3013   if (n == 0 || n == k) return 1;
3014   if (k > n) return 0;
3015 
3016   if (k > n/2)
3017     k = n-k;
3018 
3019   uint64_t r = 1;
3020   for (uint64_t i = 1; i <= k; ++i) {
3021     r = umul_ov(r, n-(i-1), Overflow);
3022     r /= i;
3023   }
3024   return r;
3025 }
3026 
3027 /// Determine if any of the operands in this SCEV are a constant or if
3028 /// any of the add or multiply expressions in this SCEV contain a constant.
3029 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3030   struct FindConstantInAddMulChain {
3031     bool FoundConstant = false;
3032 
3033     bool follow(const SCEV *S) {
3034       FoundConstant |= isa<SCEVConstant>(S);
3035       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3036     }
3037 
3038     bool isDone() const {
3039       return FoundConstant;
3040     }
3041   };
3042 
3043   FindConstantInAddMulChain F;
3044   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3045   ST.visitAll(StartExpr);
3046   return F.FoundConstant;
3047 }
3048 
3049 /// Get a canonical multiply expression, or something simpler if possible.
3050 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3051                                         SCEV::NoWrapFlags OrigFlags,
3052                                         unsigned Depth) {
3053   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3054          "only nuw or nsw allowed");
3055   assert(!Ops.empty() && "Cannot get empty mul!");
3056   if (Ops.size() == 1) return Ops[0];
3057 #ifndef NDEBUG
3058   Type *ETy = Ops[0]->getType();
3059   assert(!ETy->isPointerTy());
3060   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3061     assert(Ops[i]->getType() == ETy &&
3062            "SCEVMulExpr operand types don't match!");
3063 #endif
3064 
3065   // Sort by complexity, this groups all similar expression types together.
3066   GroupByComplexity(Ops, &LI, DT);
3067 
3068   // If there are any constants, fold them together.
3069   unsigned Idx = 0;
3070   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3071     ++Idx;
3072     assert(Idx < Ops.size());
3073     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3074       // We found two constants, fold them together!
3075       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3076       if (Ops.size() == 2) return Ops[0];
3077       Ops.erase(Ops.begin()+1);  // Erase the folded element
3078       LHSC = cast<SCEVConstant>(Ops[0]);
3079     }
3080 
3081     // If we have a multiply of zero, it will always be zero.
3082     if (LHSC->getValue()->isZero())
3083       return LHSC;
3084 
3085     // If we are left with a constant one being multiplied, strip it off.
3086     if (LHSC->getValue()->isOne()) {
3087       Ops.erase(Ops.begin());
3088       --Idx;
3089     }
3090 
3091     if (Ops.size() == 1)
3092       return Ops[0];
3093   }
3094 
3095   // Delay expensive flag strengthening until necessary.
3096   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3097     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3098   };
3099 
3100   // Limit recursion calls depth.
3101   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3102     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3103 
3104   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3105     // Don't strengthen flags if we have no new information.
3106     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3107     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3108       Mul->setNoWrapFlags(ComputeFlags(Ops));
3109     return S;
3110   }
3111 
3112   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3113     if (Ops.size() == 2) {
3114       // C1*(C2+V) -> C1*C2 + C1*V
3115       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3116         // If any of Add's ops are Adds or Muls with a constant, apply this
3117         // transformation as well.
3118         //
3119         // TODO: There are some cases where this transformation is not
3120         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3121         // this transformation should be narrowed down.
3122         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3123           const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3124                                        SCEV::FlagAnyWrap, Depth + 1);
3125           const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3126                                        SCEV::FlagAnyWrap, Depth + 1);
3127           return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3128         }
3129 
3130       if (Ops[0]->isAllOnesValue()) {
3131         // If we have a mul by -1 of an add, try distributing the -1 among the
3132         // add operands.
3133         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3134           SmallVector<const SCEV *, 4> NewOps;
3135           bool AnyFolded = false;
3136           for (const SCEV *AddOp : Add->operands()) {
3137             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3138                                          Depth + 1);
3139             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3140             NewOps.push_back(Mul);
3141           }
3142           if (AnyFolded)
3143             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3144         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3145           // Negation preserves a recurrence's no self-wrap property.
3146           SmallVector<const SCEV *, 4> Operands;
3147           for (const SCEV *AddRecOp : AddRec->operands())
3148             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3149                                           Depth + 1));
3150 
3151           return getAddRecExpr(Operands, AddRec->getLoop(),
3152                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3153         }
3154       }
3155     }
3156   }
3157 
3158   // Skip over the add expression until we get to a multiply.
3159   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3160     ++Idx;
3161 
3162   // If there are mul operands inline them all into this expression.
3163   if (Idx < Ops.size()) {
3164     bool DeletedMul = false;
3165     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3166       if (Ops.size() > MulOpsInlineThreshold)
3167         break;
3168       // If we have an mul, expand the mul operands onto the end of the
3169       // operands list.
3170       Ops.erase(Ops.begin()+Idx);
3171       Ops.append(Mul->op_begin(), Mul->op_end());
3172       DeletedMul = true;
3173     }
3174 
3175     // If we deleted at least one mul, we added operands to the end of the
3176     // list, and they are not necessarily sorted.  Recurse to resort and
3177     // resimplify any operands we just acquired.
3178     if (DeletedMul)
3179       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3180   }
3181 
3182   // If there are any add recurrences in the operands list, see if any other
3183   // added values are loop invariant.  If so, we can fold them into the
3184   // recurrence.
3185   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3186     ++Idx;
3187 
3188   // Scan over all recurrences, trying to fold loop invariants into them.
3189   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3190     // Scan all of the other operands to this mul and add them to the vector
3191     // if they are loop invariant w.r.t. the recurrence.
3192     SmallVector<const SCEV *, 8> LIOps;
3193     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3194     const Loop *AddRecLoop = AddRec->getLoop();
3195     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3196       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3197         LIOps.push_back(Ops[i]);
3198         Ops.erase(Ops.begin()+i);
3199         --i; --e;
3200       }
3201 
3202     // If we found some loop invariants, fold them into the recurrence.
3203     if (!LIOps.empty()) {
3204       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3205       SmallVector<const SCEV *, 4> NewOps;
3206       NewOps.reserve(AddRec->getNumOperands());
3207       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3208       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3209         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3210                                     SCEV::FlagAnyWrap, Depth + 1));
3211 
3212       // Build the new addrec. Propagate the NUW and NSW flags if both the
3213       // outer mul and the inner addrec are guaranteed to have no overflow.
3214       //
3215       // No self-wrap cannot be guaranteed after changing the step size, but
3216       // will be inferred if either NUW or NSW is true.
3217       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3218       const SCEV *NewRec = getAddRecExpr(
3219           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3220 
3221       // If all of the other operands were loop invariant, we are done.
3222       if (Ops.size() == 1) return NewRec;
3223 
3224       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3225       for (unsigned i = 0;; ++i)
3226         if (Ops[i] == AddRec) {
3227           Ops[i] = NewRec;
3228           break;
3229         }
3230       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3231     }
3232 
3233     // Okay, if there weren't any loop invariants to be folded, check to see
3234     // if there are multiple AddRec's with the same loop induction variable
3235     // being multiplied together.  If so, we can fold them.
3236 
3237     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3238     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3239     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3240     //   ]]],+,...up to x=2n}.
3241     // Note that the arguments to choose() are always integers with values
3242     // known at compile time, never SCEV objects.
3243     //
3244     // The implementation avoids pointless extra computations when the two
3245     // addrec's are of different length (mathematically, it's equivalent to
3246     // an infinite stream of zeros on the right).
3247     bool OpsModified = false;
3248     for (unsigned OtherIdx = Idx+1;
3249          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3250          ++OtherIdx) {
3251       const SCEVAddRecExpr *OtherAddRec =
3252         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3253       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3254         continue;
3255 
3256       // Limit max number of arguments to avoid creation of unreasonably big
3257       // SCEVAddRecs with very complex operands.
3258       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3259           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3260         continue;
3261 
3262       bool Overflow = false;
3263       Type *Ty = AddRec->getType();
3264       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3265       SmallVector<const SCEV*, 7> AddRecOps;
3266       for (int x = 0, xe = AddRec->getNumOperands() +
3267              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3268         SmallVector <const SCEV *, 7> SumOps;
3269         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3270           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3271           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3272                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3273                z < ze && !Overflow; ++z) {
3274             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3275             uint64_t Coeff;
3276             if (LargerThan64Bits)
3277               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3278             else
3279               Coeff = Coeff1*Coeff2;
3280             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3281             const SCEV *Term1 = AddRec->getOperand(y-z);
3282             const SCEV *Term2 = OtherAddRec->getOperand(z);
3283             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3284                                         SCEV::FlagAnyWrap, Depth + 1));
3285           }
3286         }
3287         if (SumOps.empty())
3288           SumOps.push_back(getZero(Ty));
3289         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3290       }
3291       if (!Overflow) {
3292         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3293                                               SCEV::FlagAnyWrap);
3294         if (Ops.size() == 2) return NewAddRec;
3295         Ops[Idx] = NewAddRec;
3296         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3297         OpsModified = true;
3298         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3299         if (!AddRec)
3300           break;
3301       }
3302     }
3303     if (OpsModified)
3304       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3305 
3306     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3307     // next one.
3308   }
3309 
3310   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3311   // already have one, otherwise create a new one.
3312   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3313 }
3314 
3315 /// Represents an unsigned remainder expression based on unsigned division.
3316 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3317                                          const SCEV *RHS) {
3318   assert(getEffectiveSCEVType(LHS->getType()) ==
3319          getEffectiveSCEVType(RHS->getType()) &&
3320          "SCEVURemExpr operand types don't match!");
3321 
3322   // Short-circuit easy cases
3323   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3324     // If constant is one, the result is trivial
3325     if (RHSC->getValue()->isOne())
3326       return getZero(LHS->getType()); // X urem 1 --> 0
3327 
3328     // If constant is a power of two, fold into a zext(trunc(LHS)).
3329     if (RHSC->getAPInt().isPowerOf2()) {
3330       Type *FullTy = LHS->getType();
3331       Type *TruncTy =
3332           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3333       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3334     }
3335   }
3336 
3337   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3338   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3339   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3340   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3341 }
3342 
3343 /// Get a canonical unsigned division expression, or something simpler if
3344 /// possible.
3345 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3346                                          const SCEV *RHS) {
3347   assert(!LHS->getType()->isPointerTy() &&
3348          "SCEVUDivExpr operand can't be pointer!");
3349   assert(LHS->getType() == RHS->getType() &&
3350          "SCEVUDivExpr operand types don't match!");
3351 
3352   FoldingSetNodeID ID;
3353   ID.AddInteger(scUDivExpr);
3354   ID.AddPointer(LHS);
3355   ID.AddPointer(RHS);
3356   void *IP = nullptr;
3357   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3358     return S;
3359 
3360   // 0 udiv Y == 0
3361   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3362     if (LHSC->getValue()->isZero())
3363       return LHS;
3364 
3365   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3366     if (RHSC->getValue()->isOne())
3367       return LHS;                               // X udiv 1 --> x
3368     // If the denominator is zero, the result of the udiv is undefined. Don't
3369     // try to analyze it, because the resolution chosen here may differ from
3370     // the resolution chosen in other parts of the compiler.
3371     if (!RHSC->getValue()->isZero()) {
3372       // Determine if the division can be folded into the operands of
3373       // its operands.
3374       // TODO: Generalize this to non-constants by using known-bits information.
3375       Type *Ty = LHS->getType();
3376       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3377       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3378       // For non-power-of-two values, effectively round the value up to the
3379       // nearest power of two.
3380       if (!RHSC->getAPInt().isPowerOf2())
3381         ++MaxShiftAmt;
3382       IntegerType *ExtTy =
3383         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3384       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3385         if (const SCEVConstant *Step =
3386             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3387           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3388           const APInt &StepInt = Step->getAPInt();
3389           const APInt &DivInt = RHSC->getAPInt();
3390           if (!StepInt.urem(DivInt) &&
3391               getZeroExtendExpr(AR, ExtTy) ==
3392               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3393                             getZeroExtendExpr(Step, ExtTy),
3394                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3395             SmallVector<const SCEV *, 4> Operands;
3396             for (const SCEV *Op : AR->operands())
3397               Operands.push_back(getUDivExpr(Op, RHS));
3398             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3399           }
3400           /// Get a canonical UDivExpr for a recurrence.
3401           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3402           // We can currently only fold X%N if X is constant.
3403           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3404           if (StartC && !DivInt.urem(StepInt) &&
3405               getZeroExtendExpr(AR, ExtTy) ==
3406               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3407                             getZeroExtendExpr(Step, ExtTy),
3408                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3409             const APInt &StartInt = StartC->getAPInt();
3410             const APInt &StartRem = StartInt.urem(StepInt);
3411             if (StartRem != 0) {
3412               const SCEV *NewLHS =
3413                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3414                                 AR->getLoop(), SCEV::FlagNW);
3415               if (LHS != NewLHS) {
3416                 LHS = NewLHS;
3417 
3418                 // Reset the ID to include the new LHS, and check if it is
3419                 // already cached.
3420                 ID.clear();
3421                 ID.AddInteger(scUDivExpr);
3422                 ID.AddPointer(LHS);
3423                 ID.AddPointer(RHS);
3424                 IP = nullptr;
3425                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3426                   return S;
3427               }
3428             }
3429           }
3430         }
3431       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3432       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3433         SmallVector<const SCEV *, 4> Operands;
3434         for (const SCEV *Op : M->operands())
3435           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3436         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3437           // Find an operand that's safely divisible.
3438           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3439             const SCEV *Op = M->getOperand(i);
3440             const SCEV *Div = getUDivExpr(Op, RHSC);
3441             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3442               Operands = SmallVector<const SCEV *, 4>(M->operands());
3443               Operands[i] = Div;
3444               return getMulExpr(Operands);
3445             }
3446           }
3447       }
3448 
3449       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3450       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3451         if (auto *DivisorConstant =
3452                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3453           bool Overflow = false;
3454           APInt NewRHS =
3455               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3456           if (Overflow) {
3457             return getConstant(RHSC->getType(), 0, false);
3458           }
3459           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3460         }
3461       }
3462 
3463       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3464       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3465         SmallVector<const SCEV *, 4> Operands;
3466         for (const SCEV *Op : A->operands())
3467           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3468         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3469           Operands.clear();
3470           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3471             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3472             if (isa<SCEVUDivExpr>(Op) ||
3473                 getMulExpr(Op, RHS) != A->getOperand(i))
3474               break;
3475             Operands.push_back(Op);
3476           }
3477           if (Operands.size() == A->getNumOperands())
3478             return getAddExpr(Operands);
3479         }
3480       }
3481 
3482       // Fold if both operands are constant.
3483       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3484         Constant *LHSCV = LHSC->getValue();
3485         Constant *RHSCV = RHSC->getValue();
3486         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3487                                                                    RHSCV)));
3488       }
3489     }
3490   }
3491 
3492   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3493   // changes). Make sure we get a new one.
3494   IP = nullptr;
3495   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3496   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3497                                              LHS, RHS);
3498   UniqueSCEVs.InsertNode(S, IP);
3499   registerUser(S, {LHS, RHS});
3500   return S;
3501 }
3502 
3503 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3504   APInt A = C1->getAPInt().abs();
3505   APInt B = C2->getAPInt().abs();
3506   uint32_t ABW = A.getBitWidth();
3507   uint32_t BBW = B.getBitWidth();
3508 
3509   if (ABW > BBW)
3510     B = B.zext(ABW);
3511   else if (ABW < BBW)
3512     A = A.zext(BBW);
3513 
3514   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3515 }
3516 
3517 /// Get a canonical unsigned division expression, or something simpler if
3518 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3519 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3520 /// it's not exact because the udiv may be clearing bits.
3521 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3522                                               const SCEV *RHS) {
3523   // TODO: we could try to find factors in all sorts of things, but for now we
3524   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3525   // end of this file for inspiration.
3526 
3527   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3528   if (!Mul || !Mul->hasNoUnsignedWrap())
3529     return getUDivExpr(LHS, RHS);
3530 
3531   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3532     // If the mulexpr multiplies by a constant, then that constant must be the
3533     // first element of the mulexpr.
3534     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3535       if (LHSCst == RHSCst) {
3536         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3537         return getMulExpr(Operands);
3538       }
3539 
3540       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3541       // that there's a factor provided by one of the other terms. We need to
3542       // check.
3543       APInt Factor = gcd(LHSCst, RHSCst);
3544       if (!Factor.isIntN(1)) {
3545         LHSCst =
3546             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3547         RHSCst =
3548             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3549         SmallVector<const SCEV *, 2> Operands;
3550         Operands.push_back(LHSCst);
3551         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3552         LHS = getMulExpr(Operands);
3553         RHS = RHSCst;
3554         Mul = dyn_cast<SCEVMulExpr>(LHS);
3555         if (!Mul)
3556           return getUDivExactExpr(LHS, RHS);
3557       }
3558     }
3559   }
3560 
3561   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3562     if (Mul->getOperand(i) == RHS) {
3563       SmallVector<const SCEV *, 2> Operands;
3564       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3565       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3566       return getMulExpr(Operands);
3567     }
3568   }
3569 
3570   return getUDivExpr(LHS, RHS);
3571 }
3572 
3573 /// Get an add recurrence expression for the specified loop.  Simplify the
3574 /// expression as much as possible.
3575 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3576                                            const Loop *L,
3577                                            SCEV::NoWrapFlags Flags) {
3578   SmallVector<const SCEV *, 4> Operands;
3579   Operands.push_back(Start);
3580   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3581     if (StepChrec->getLoop() == L) {
3582       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3583       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3584     }
3585 
3586   Operands.push_back(Step);
3587   return getAddRecExpr(Operands, L, Flags);
3588 }
3589 
3590 /// Get an add recurrence expression for the specified loop.  Simplify the
3591 /// expression as much as possible.
3592 const SCEV *
3593 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3594                                const Loop *L, SCEV::NoWrapFlags Flags) {
3595   if (Operands.size() == 1) return Operands[0];
3596 #ifndef NDEBUG
3597   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3598   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3599     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3600            "SCEVAddRecExpr operand types don't match!");
3601     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3602   }
3603   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3604     assert(isLoopInvariant(Operands[i], L) &&
3605            "SCEVAddRecExpr operand is not loop-invariant!");
3606 #endif
3607 
3608   if (Operands.back()->isZero()) {
3609     Operands.pop_back();
3610     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3611   }
3612 
3613   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3614   // use that information to infer NUW and NSW flags. However, computing a
3615   // BE count requires calling getAddRecExpr, so we may not yet have a
3616   // meaningful BE count at this point (and if we don't, we'd be stuck
3617   // with a SCEVCouldNotCompute as the cached BE count).
3618 
3619   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3620 
3621   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3622   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3623     const Loop *NestedLoop = NestedAR->getLoop();
3624     if (L->contains(NestedLoop)
3625             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3626             : (!NestedLoop->contains(L) &&
3627                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3628       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3629       Operands[0] = NestedAR->getStart();
3630       // AddRecs require their operands be loop-invariant with respect to their
3631       // loops. Don't perform this transformation if it would break this
3632       // requirement.
3633       bool AllInvariant = all_of(
3634           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3635 
3636       if (AllInvariant) {
3637         // Create a recurrence for the outer loop with the same step size.
3638         //
3639         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3640         // inner recurrence has the same property.
3641         SCEV::NoWrapFlags OuterFlags =
3642           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3643 
3644         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3645         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3646           return isLoopInvariant(Op, NestedLoop);
3647         });
3648 
3649         if (AllInvariant) {
3650           // Ok, both add recurrences are valid after the transformation.
3651           //
3652           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3653           // the outer recurrence has the same property.
3654           SCEV::NoWrapFlags InnerFlags =
3655             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3656           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3657         }
3658       }
3659       // Reset Operands to its original state.
3660       Operands[0] = NestedAR;
3661     }
3662   }
3663 
3664   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3665   // already have one, otherwise create a new one.
3666   return getOrCreateAddRecExpr(Operands, L, Flags);
3667 }
3668 
3669 const SCEV *
3670 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3671                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3672   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3673   // getSCEV(Base)->getType() has the same address space as Base->getType()
3674   // because SCEV::getType() preserves the address space.
3675   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3676   const bool AssumeInBoundsFlags = [&]() {
3677     if (!GEP->isInBounds())
3678       return false;
3679 
3680     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3681     // but to do that, we have to ensure that said flag is valid in the entire
3682     // defined scope of the SCEV.
3683     auto *GEPI = dyn_cast<Instruction>(GEP);
3684     // TODO: non-instructions have global scope.  We might be able to prove
3685     // some global scope cases
3686     return GEPI && isSCEVExprNeverPoison(GEPI);
3687   }();
3688 
3689   SCEV::NoWrapFlags OffsetWrap =
3690     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3691 
3692   Type *CurTy = GEP->getType();
3693   bool FirstIter = true;
3694   SmallVector<const SCEV *, 4> Offsets;
3695   for (const SCEV *IndexExpr : IndexExprs) {
3696     // Compute the (potentially symbolic) offset in bytes for this index.
3697     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3698       // For a struct, add the member offset.
3699       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3700       unsigned FieldNo = Index->getZExtValue();
3701       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3702       Offsets.push_back(FieldOffset);
3703 
3704       // Update CurTy to the type of the field at Index.
3705       CurTy = STy->getTypeAtIndex(Index);
3706     } else {
3707       // Update CurTy to its element type.
3708       if (FirstIter) {
3709         assert(isa<PointerType>(CurTy) &&
3710                "The first index of a GEP indexes a pointer");
3711         CurTy = GEP->getSourceElementType();
3712         FirstIter = false;
3713       } else {
3714         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3715       }
3716       // For an array, add the element offset, explicitly scaled.
3717       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3718       // Getelementptr indices are signed.
3719       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3720 
3721       // Multiply the index by the element size to compute the element offset.
3722       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3723       Offsets.push_back(LocalOffset);
3724     }
3725   }
3726 
3727   // Handle degenerate case of GEP without offsets.
3728   if (Offsets.empty())
3729     return BaseExpr;
3730 
3731   // Add the offsets together, assuming nsw if inbounds.
3732   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3733   // Add the base address and the offset. We cannot use the nsw flag, as the
3734   // base address is unsigned. However, if we know that the offset is
3735   // non-negative, we can use nuw.
3736   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3737                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3738   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3739   assert(BaseExpr->getType() == GEPExpr->getType() &&
3740          "GEP should not change type mid-flight.");
3741   return GEPExpr;
3742 }
3743 
3744 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3745                                                ArrayRef<const SCEV *> Ops) {
3746   FoldingSetNodeID ID;
3747   ID.AddInteger(SCEVType);
3748   for (const SCEV *Op : Ops)
3749     ID.AddPointer(Op);
3750   void *IP = nullptr;
3751   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3752 }
3753 
3754 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3755   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3756   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3757 }
3758 
3759 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3760                                            SmallVectorImpl<const SCEV *> &Ops) {
3761   assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3762   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3763   if (Ops.size() == 1) return Ops[0];
3764 #ifndef NDEBUG
3765   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3766   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3767     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3768            "Operand types don't match!");
3769     assert(Ops[0]->getType()->isPointerTy() ==
3770                Ops[i]->getType()->isPointerTy() &&
3771            "min/max should be consistently pointerish");
3772   }
3773 #endif
3774 
3775   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3776   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3777 
3778   // Sort by complexity, this groups all similar expression types together.
3779   GroupByComplexity(Ops, &LI, DT);
3780 
3781   // Check if we have created the same expression before.
3782   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3783     return S;
3784   }
3785 
3786   // If there are any constants, fold them together.
3787   unsigned Idx = 0;
3788   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3789     ++Idx;
3790     assert(Idx < Ops.size());
3791     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3792       if (Kind == scSMaxExpr)
3793         return APIntOps::smax(LHS, RHS);
3794       else if (Kind == scSMinExpr)
3795         return APIntOps::smin(LHS, RHS);
3796       else if (Kind == scUMaxExpr)
3797         return APIntOps::umax(LHS, RHS);
3798       else if (Kind == scUMinExpr)
3799         return APIntOps::umin(LHS, RHS);
3800       llvm_unreachable("Unknown SCEV min/max opcode");
3801     };
3802 
3803     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3804       // We found two constants, fold them together!
3805       ConstantInt *Fold = ConstantInt::get(
3806           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3807       Ops[0] = getConstant(Fold);
3808       Ops.erase(Ops.begin()+1);  // Erase the folded element
3809       if (Ops.size() == 1) return Ops[0];
3810       LHSC = cast<SCEVConstant>(Ops[0]);
3811     }
3812 
3813     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3814     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3815 
3816     if (IsMax ? IsMinV : IsMaxV) {
3817       // If we are left with a constant minimum(/maximum)-int, strip it off.
3818       Ops.erase(Ops.begin());
3819       --Idx;
3820     } else if (IsMax ? IsMaxV : IsMinV) {
3821       // If we have a max(/min) with a constant maximum(/minimum)-int,
3822       // it will always be the extremum.
3823       return LHSC;
3824     }
3825 
3826     if (Ops.size() == 1) return Ops[0];
3827   }
3828 
3829   // Find the first operation of the same kind
3830   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3831     ++Idx;
3832 
3833   // Check to see if one of the operands is of the same kind. If so, expand its
3834   // operands onto our operand list, and recurse to simplify.
3835   if (Idx < Ops.size()) {
3836     bool DeletedAny = false;
3837     while (Ops[Idx]->getSCEVType() == Kind) {
3838       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3839       Ops.erase(Ops.begin()+Idx);
3840       Ops.append(SMME->op_begin(), SMME->op_end());
3841       DeletedAny = true;
3842     }
3843 
3844     if (DeletedAny)
3845       return getMinMaxExpr(Kind, Ops);
3846   }
3847 
3848   // Okay, check to see if the same value occurs in the operand list twice.  If
3849   // so, delete one.  Since we sorted the list, these values are required to
3850   // be adjacent.
3851   llvm::CmpInst::Predicate GEPred =
3852       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3853   llvm::CmpInst::Predicate LEPred =
3854       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3855   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3856   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3857   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3858     if (Ops[i] == Ops[i + 1] ||
3859         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3860       //  X op Y op Y  -->  X op Y
3861       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3862       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3863       --i;
3864       --e;
3865     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3866                                                Ops[i + 1])) {
3867       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3868       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3869       --i;
3870       --e;
3871     }
3872   }
3873 
3874   if (Ops.size() == 1) return Ops[0];
3875 
3876   assert(!Ops.empty() && "Reduced smax down to nothing!");
3877 
3878   // Okay, it looks like we really DO need an expr.  Check to see if we
3879   // already have one, otherwise create a new one.
3880   FoldingSetNodeID ID;
3881   ID.AddInteger(Kind);
3882   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3883     ID.AddPointer(Ops[i]);
3884   void *IP = nullptr;
3885   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3886   if (ExistingSCEV)
3887     return ExistingSCEV;
3888   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3889   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3890   SCEV *S = new (SCEVAllocator)
3891       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3892 
3893   UniqueSCEVs.InsertNode(S, IP);
3894   registerUser(S, Ops);
3895   return S;
3896 }
3897 
3898 namespace {
3899 
3900 class SCEVSequentialMinMaxDeduplicatingVisitor final
3901     : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3902                          Optional<const SCEV *>> {
3903   using RetVal = Optional<const SCEV *>;
3904   using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3905 
3906   ScalarEvolution &SE;
3907   const SCEVTypes RootKind; // Must be a sequential min/max expression.
3908   const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3909   SmallPtrSet<const SCEV *, 16> SeenOps;
3910 
3911   bool canRecurseInto(SCEVTypes Kind) const {
3912     // We can only recurse into the SCEV expression of the same effective type
3913     // as the type of our root SCEV expression.
3914     return RootKind == Kind || NonSequentialRootKind == Kind;
3915   };
3916 
3917   RetVal visitAnyMinMaxExpr(const SCEV *S) {
3918     assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3919            "Only for min/max expressions.");
3920     SCEVTypes Kind = S->getSCEVType();
3921 
3922     if (!canRecurseInto(Kind))
3923       return S;
3924 
3925     auto *NAry = cast<SCEVNAryExpr>(S);
3926     SmallVector<const SCEV *> NewOps;
3927     bool Changed =
3928         visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps);
3929 
3930     if (!Changed)
3931       return S;
3932     if (NewOps.empty())
3933       return None;
3934 
3935     return isa<SCEVSequentialMinMaxExpr>(S)
3936                ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3937                : SE.getMinMaxExpr(Kind, NewOps);
3938   }
3939 
3940   RetVal visit(const SCEV *S) {
3941     // Has the whole operand been seen already?
3942     if (!SeenOps.insert(S).second)
3943       return None;
3944     return Base::visit(S);
3945   }
3946 
3947 public:
3948   SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3949                                            SCEVTypes RootKind)
3950       : SE(SE), RootKind(RootKind),
3951         NonSequentialRootKind(
3952             SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3953                 RootKind)) {}
3954 
3955   bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
3956                          SmallVectorImpl<const SCEV *> &NewOps) {
3957     bool Changed = false;
3958     SmallVector<const SCEV *> Ops;
3959     Ops.reserve(OrigOps.size());
3960 
3961     for (const SCEV *Op : OrigOps) {
3962       RetVal NewOp = visit(Op);
3963       if (NewOp != Op)
3964         Changed = true;
3965       if (NewOp)
3966         Ops.emplace_back(*NewOp);
3967     }
3968 
3969     if (Changed)
3970       NewOps = std::move(Ops);
3971     return Changed;
3972   }
3973 
3974   RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
3975 
3976   RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
3977 
3978   RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
3979 
3980   RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
3981 
3982   RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
3983 
3984   RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
3985 
3986   RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
3987 
3988   RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
3989 
3990   RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
3991 
3992   RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
3993     return visitAnyMinMaxExpr(Expr);
3994   }
3995 
3996   RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
3997     return visitAnyMinMaxExpr(Expr);
3998   }
3999 
4000   RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4001     return visitAnyMinMaxExpr(Expr);
4002   }
4003 
4004   RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4005     return visitAnyMinMaxExpr(Expr);
4006   }
4007 
4008   RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4009     return visitAnyMinMaxExpr(Expr);
4010   }
4011 
4012   RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4013 
4014   RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4015 };
4016 
4017 } // namespace
4018 
4019 /// Return true if V is poison given that AssumedPoison is already poison.
4020 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4021   // The only way poison may be introduced in a SCEV expression is from a
4022   // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4023   // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4024   // introduce poison -- they encode guaranteed, non-speculated knowledge.
4025   //
4026   // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4027   // with the notable exception of umin_seq, where only poison from the first
4028   // operand is (unconditionally) propagated.
4029   struct SCEVPoisonCollector {
4030     bool LookThroughSeq;
4031     SmallPtrSet<const SCEV *, 4> MaybePoison;
4032     SCEVPoisonCollector(bool LookThroughSeq) : LookThroughSeq(LookThroughSeq) {}
4033 
4034     bool follow(const SCEV *S) {
4035       // TODO: We can always follow the first operand, but the SCEVTraversal
4036       // API doesn't support this.
4037       if (!LookThroughSeq && isa<SCEVSequentialMinMaxExpr>(S))
4038         return false;
4039 
4040       if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4041         if (!isGuaranteedNotToBePoison(SU->getValue()))
4042           MaybePoison.insert(S);
4043       }
4044       return true;
4045     }
4046     bool isDone() const { return false; }
4047   };
4048 
4049   // First collect all SCEVs that might result in AssumedPoison to be poison.
4050   // We need to look through umin_seq here, because we want to find all SCEVs
4051   // that *might* result in poison, not only those that are *required* to.
4052   SCEVPoisonCollector PC1(/* LookThroughSeq */ true);
4053   visitAll(AssumedPoison, PC1);
4054 
4055   // AssumedPoison is never poison. As the assumption is false, the implication
4056   // is true. Don't bother walking the other SCEV in this case.
4057   if (PC1.MaybePoison.empty())
4058     return true;
4059 
4060   // Collect all SCEVs in S that, if poison, *will* result in S being poison
4061   // as well. We cannot look through umin_seq here, as its argument only *may*
4062   // make the result poison.
4063   SCEVPoisonCollector PC2(/* LookThroughSeq */ false);
4064   visitAll(S, PC2);
4065 
4066   // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4067   // it will also make S poison by being part of PC2.MaybePoison.
4068   return all_of(PC1.MaybePoison,
4069                 [&](const SCEV *S) { return PC2.MaybePoison.contains(S); });
4070 }
4071 
4072 const SCEV *
4073 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4074                                          SmallVectorImpl<const SCEV *> &Ops) {
4075   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4076          "Not a SCEVSequentialMinMaxExpr!");
4077   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4078   if (Ops.size() == 1)
4079     return Ops[0];
4080 #ifndef NDEBUG
4081   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4082   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4083     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4084            "Operand types don't match!");
4085     assert(Ops[0]->getType()->isPointerTy() ==
4086                Ops[i]->getType()->isPointerTy() &&
4087            "min/max should be consistently pointerish");
4088   }
4089 #endif
4090 
4091   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4092   // so we can *NOT* do any kind of sorting of the expressions!
4093 
4094   // Check if we have created the same expression before.
4095   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4096     return S;
4097 
4098   // FIXME: there are *some* simplifications that we can do here.
4099 
4100   // Keep only the first instance of an operand.
4101   {
4102     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4103     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4104     if (Changed)
4105       return getSequentialMinMaxExpr(Kind, Ops);
4106   }
4107 
4108   // Check to see if one of the operands is of the same kind. If so, expand its
4109   // operands onto our operand list, and recurse to simplify.
4110   {
4111     unsigned Idx = 0;
4112     bool DeletedAny = false;
4113     while (Idx < Ops.size()) {
4114       if (Ops[Idx]->getSCEVType() != Kind) {
4115         ++Idx;
4116         continue;
4117       }
4118       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4119       Ops.erase(Ops.begin() + Idx);
4120       Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end());
4121       DeletedAny = true;
4122     }
4123 
4124     if (DeletedAny)
4125       return getSequentialMinMaxExpr(Kind, Ops);
4126   }
4127 
4128   const SCEV *SaturationPoint;
4129   ICmpInst::Predicate Pred;
4130   switch (Kind) {
4131   case scSequentialUMinExpr:
4132     SaturationPoint = getZero(Ops[0]->getType());
4133     Pred = ICmpInst::ICMP_ULE;
4134     break;
4135   default:
4136     llvm_unreachable("Not a sequential min/max type.");
4137   }
4138 
4139   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4140     // We can replace %x umin_seq %y with %x umin %y if either:
4141     //  * %y being poison implies %x is also poison.
4142     //  * %x cannot be the saturating value (e.g. zero for umin).
4143     if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4144         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4145                                         SaturationPoint)) {
4146       SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4147       Ops[i - 1] = getMinMaxExpr(
4148           SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4149           SeqOps);
4150       Ops.erase(Ops.begin() + i);
4151       return getSequentialMinMaxExpr(Kind, Ops);
4152     }
4153     // Fold %x umin_seq %y to %x if %x ule %y.
4154     // TODO: We might be able to prove the predicate for a later operand.
4155     if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4156       Ops.erase(Ops.begin() + i);
4157       return getSequentialMinMaxExpr(Kind, Ops);
4158     }
4159   }
4160 
4161   // Okay, it looks like we really DO need an expr.  Check to see if we
4162   // already have one, otherwise create a new one.
4163   FoldingSetNodeID ID;
4164   ID.AddInteger(Kind);
4165   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4166     ID.AddPointer(Ops[i]);
4167   void *IP = nullptr;
4168   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4169   if (ExistingSCEV)
4170     return ExistingSCEV;
4171 
4172   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4173   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4174   SCEV *S = new (SCEVAllocator)
4175       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4176 
4177   UniqueSCEVs.InsertNode(S, IP);
4178   registerUser(S, Ops);
4179   return S;
4180 }
4181 
4182 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4183   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4184   return getSMaxExpr(Ops);
4185 }
4186 
4187 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4188   return getMinMaxExpr(scSMaxExpr, Ops);
4189 }
4190 
4191 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4192   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4193   return getUMaxExpr(Ops);
4194 }
4195 
4196 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4197   return getMinMaxExpr(scUMaxExpr, Ops);
4198 }
4199 
4200 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4201                                          const SCEV *RHS) {
4202   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4203   return getSMinExpr(Ops);
4204 }
4205 
4206 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4207   return getMinMaxExpr(scSMinExpr, Ops);
4208 }
4209 
4210 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4211                                          bool Sequential) {
4212   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4213   return getUMinExpr(Ops, Sequential);
4214 }
4215 
4216 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4217                                          bool Sequential) {
4218   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4219                     : getMinMaxExpr(scUMinExpr, Ops);
4220 }
4221 
4222 const SCEV *
4223 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
4224                                              ScalableVectorType *ScalableTy) {
4225   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
4226   Constant *One = ConstantInt::get(IntTy, 1);
4227   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
4228   // Note that the expression we created is the final expression, we don't
4229   // want to simplify it any further Also, if we call a normal getSCEV(),
4230   // we'll end up in an endless recursion. So just create an SCEVUnknown.
4231   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
4232 }
4233 
4234 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4235   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
4236     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
4237   // We can bypass creating a target-independent constant expression and then
4238   // folding it back into a ConstantInt. This is just a compile-time
4239   // optimization.
4240   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4241 }
4242 
4243 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4244   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
4245     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
4246   // We can bypass creating a target-independent constant expression and then
4247   // folding it back into a ConstantInt. This is just a compile-time
4248   // optimization.
4249   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4250 }
4251 
4252 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4253                                              StructType *STy,
4254                                              unsigned FieldNo) {
4255   // We can bypass creating a target-independent constant expression and then
4256   // folding it back into a ConstantInt. This is just a compile-time
4257   // optimization.
4258   return getConstant(
4259       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4260 }
4261 
4262 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4263   // Don't attempt to do anything other than create a SCEVUnknown object
4264   // here.  createSCEV only calls getUnknown after checking for all other
4265   // interesting possibilities, and any other code that calls getUnknown
4266   // is doing so in order to hide a value from SCEV canonicalization.
4267 
4268   FoldingSetNodeID ID;
4269   ID.AddInteger(scUnknown);
4270   ID.AddPointer(V);
4271   void *IP = nullptr;
4272   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4273     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4274            "Stale SCEVUnknown in uniquing map!");
4275     return S;
4276   }
4277   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4278                                             FirstUnknown);
4279   FirstUnknown = cast<SCEVUnknown>(S);
4280   UniqueSCEVs.InsertNode(S, IP);
4281   return S;
4282 }
4283 
4284 //===----------------------------------------------------------------------===//
4285 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4286 //
4287 
4288 /// Test if values of the given type are analyzable within the SCEV
4289 /// framework. This primarily includes integer types, and it can optionally
4290 /// include pointer types if the ScalarEvolution class has access to
4291 /// target-specific information.
4292 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4293   // Integers and pointers are always SCEVable.
4294   return Ty->isIntOrPtrTy();
4295 }
4296 
4297 /// Return the size in bits of the specified type, for which isSCEVable must
4298 /// return true.
4299 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4300   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4301   if (Ty->isPointerTy())
4302     return getDataLayout().getIndexTypeSizeInBits(Ty);
4303   return getDataLayout().getTypeSizeInBits(Ty);
4304 }
4305 
4306 /// Return a type with the same bitwidth as the given type and which represents
4307 /// how SCEV will treat the given type, for which isSCEVable must return
4308 /// true. For pointer types, this is the pointer index sized integer type.
4309 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4310   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4311 
4312   if (Ty->isIntegerTy())
4313     return Ty;
4314 
4315   // The only other support type is pointer.
4316   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4317   return getDataLayout().getIndexType(Ty);
4318 }
4319 
4320 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4321   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4322 }
4323 
4324 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4325                                                          const SCEV *B) {
4326   /// For a valid use point to exist, the defining scope of one operand
4327   /// must dominate the other.
4328   bool PreciseA, PreciseB;
4329   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4330   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4331   if (!PreciseA || !PreciseB)
4332     // Can't tell.
4333     return false;
4334   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4335     DT.dominates(ScopeB, ScopeA);
4336 }
4337 
4338 
4339 const SCEV *ScalarEvolution::getCouldNotCompute() {
4340   return CouldNotCompute.get();
4341 }
4342 
4343 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4344   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4345     auto *SU = dyn_cast<SCEVUnknown>(S);
4346     return SU && SU->getValue() == nullptr;
4347   });
4348 
4349   return !ContainsNulls;
4350 }
4351 
4352 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4353   HasRecMapType::iterator I = HasRecMap.find(S);
4354   if (I != HasRecMap.end())
4355     return I->second;
4356 
4357   bool FoundAddRec =
4358       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4359   HasRecMap.insert({S, FoundAddRec});
4360   return FoundAddRec;
4361 }
4362 
4363 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4364 /// by the value and offset from any ValueOffsetPair in the set.
4365 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4366   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4367   if (SI == ExprValueMap.end())
4368     return None;
4369 #ifndef NDEBUG
4370   if (VerifySCEVMap) {
4371     // Check there is no dangling Value in the set returned.
4372     for (Value *V : SI->second)
4373       assert(ValueExprMap.count(V));
4374   }
4375 #endif
4376   return SI->second.getArrayRef();
4377 }
4378 
4379 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4380 /// cannot be used separately. eraseValueFromMap should be used to remove
4381 /// V from ValueExprMap and ExprValueMap at the same time.
4382 void ScalarEvolution::eraseValueFromMap(Value *V) {
4383   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4384   if (I != ValueExprMap.end()) {
4385     auto EVIt = ExprValueMap.find(I->second);
4386     bool Removed = EVIt->second.remove(V);
4387     (void) Removed;
4388     assert(Removed && "Value not in ExprValueMap?");
4389     ValueExprMap.erase(I);
4390   }
4391 }
4392 
4393 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4394   // A recursive query may have already computed the SCEV. It should be
4395   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4396   // inferred nowrap flags.
4397   auto It = ValueExprMap.find_as(V);
4398   if (It == ValueExprMap.end()) {
4399     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4400     ExprValueMap[S].insert(V);
4401   }
4402 }
4403 
4404 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4405 /// create a new one.
4406 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4407   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4408 
4409   const SCEV *S = getExistingSCEV(V);
4410   if (S == nullptr) {
4411     S = createSCEV(V);
4412     // During PHI resolution, it is possible to create two SCEVs for the same
4413     // V, so it is needed to double check whether V->S is inserted into
4414     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4415     std::pair<ValueExprMapType::iterator, bool> Pair =
4416         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4417     if (Pair.second)
4418       ExprValueMap[S].insert(V);
4419   }
4420   return S;
4421 }
4422 
4423 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4424   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4425 
4426   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4427   if (I != ValueExprMap.end()) {
4428     const SCEV *S = I->second;
4429     assert(checkValidity(S) &&
4430            "existing SCEV has not been properly invalidated");
4431     return S;
4432   }
4433   return nullptr;
4434 }
4435 
4436 /// Return a SCEV corresponding to -V = -1*V
4437 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4438                                              SCEV::NoWrapFlags Flags) {
4439   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4440     return getConstant(
4441                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4442 
4443   Type *Ty = V->getType();
4444   Ty = getEffectiveSCEVType(Ty);
4445   return getMulExpr(V, getMinusOne(Ty), Flags);
4446 }
4447 
4448 /// If Expr computes ~A, return A else return nullptr
4449 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4450   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4451   if (!Add || Add->getNumOperands() != 2 ||
4452       !Add->getOperand(0)->isAllOnesValue())
4453     return nullptr;
4454 
4455   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4456   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4457       !AddRHS->getOperand(0)->isAllOnesValue())
4458     return nullptr;
4459 
4460   return AddRHS->getOperand(1);
4461 }
4462 
4463 /// Return a SCEV corresponding to ~V = -1-V
4464 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4465   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4466 
4467   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4468     return getConstant(
4469                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4470 
4471   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4472   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4473     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4474       SmallVector<const SCEV *, 2> MatchedOperands;
4475       for (const SCEV *Operand : MME->operands()) {
4476         const SCEV *Matched = MatchNotExpr(Operand);
4477         if (!Matched)
4478           return (const SCEV *)nullptr;
4479         MatchedOperands.push_back(Matched);
4480       }
4481       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4482                            MatchedOperands);
4483     };
4484     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4485       return Replaced;
4486   }
4487 
4488   Type *Ty = V->getType();
4489   Ty = getEffectiveSCEVType(Ty);
4490   return getMinusSCEV(getMinusOne(Ty), V);
4491 }
4492 
4493 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4494   assert(P->getType()->isPointerTy());
4495 
4496   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4497     // The base of an AddRec is the first operand.
4498     SmallVector<const SCEV *> Ops{AddRec->operands()};
4499     Ops[0] = removePointerBase(Ops[0]);
4500     // Don't try to transfer nowrap flags for now. We could in some cases
4501     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4502     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4503   }
4504   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4505     // The base of an Add is the pointer operand.
4506     SmallVector<const SCEV *> Ops{Add->operands()};
4507     const SCEV **PtrOp = nullptr;
4508     for (const SCEV *&AddOp : Ops) {
4509       if (AddOp->getType()->isPointerTy()) {
4510         assert(!PtrOp && "Cannot have multiple pointer ops");
4511         PtrOp = &AddOp;
4512       }
4513     }
4514     *PtrOp = removePointerBase(*PtrOp);
4515     // Don't try to transfer nowrap flags for now. We could in some cases
4516     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4517     return getAddExpr(Ops);
4518   }
4519   // Any other expression must be a pointer base.
4520   return getZero(P->getType());
4521 }
4522 
4523 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4524                                           SCEV::NoWrapFlags Flags,
4525                                           unsigned Depth) {
4526   // Fast path: X - X --> 0.
4527   if (LHS == RHS)
4528     return getZero(LHS->getType());
4529 
4530   // If we subtract two pointers with different pointer bases, bail.
4531   // Eventually, we're going to add an assertion to getMulExpr that we
4532   // can't multiply by a pointer.
4533   if (RHS->getType()->isPointerTy()) {
4534     if (!LHS->getType()->isPointerTy() ||
4535         getPointerBase(LHS) != getPointerBase(RHS))
4536       return getCouldNotCompute();
4537     LHS = removePointerBase(LHS);
4538     RHS = removePointerBase(RHS);
4539   }
4540 
4541   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4542   // makes it so that we cannot make much use of NUW.
4543   auto AddFlags = SCEV::FlagAnyWrap;
4544   const bool RHSIsNotMinSigned =
4545       !getSignedRangeMin(RHS).isMinSignedValue();
4546   if (hasFlags(Flags, SCEV::FlagNSW)) {
4547     // Let M be the minimum representable signed value. Then (-1)*RHS
4548     // signed-wraps if and only if RHS is M. That can happen even for
4549     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4550     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4551     // (-1)*RHS, we need to prove that RHS != M.
4552     //
4553     // If LHS is non-negative and we know that LHS - RHS does not
4554     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4555     // either by proving that RHS > M or that LHS >= 0.
4556     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4557       AddFlags = SCEV::FlagNSW;
4558     }
4559   }
4560 
4561   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4562   // RHS is NSW and LHS >= 0.
4563   //
4564   // The difficulty here is that the NSW flag may have been proven
4565   // relative to a loop that is to be found in a recurrence in LHS and
4566   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4567   // larger scope than intended.
4568   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4569 
4570   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4571 }
4572 
4573 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4574                                                      unsigned Depth) {
4575   Type *SrcTy = V->getType();
4576   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4577          "Cannot truncate or zero extend with non-integer arguments!");
4578   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4579     return V;  // No conversion
4580   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4581     return getTruncateExpr(V, Ty, Depth);
4582   return getZeroExtendExpr(V, Ty, Depth);
4583 }
4584 
4585 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4586                                                      unsigned Depth) {
4587   Type *SrcTy = V->getType();
4588   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4589          "Cannot truncate or zero extend with non-integer arguments!");
4590   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4591     return V;  // No conversion
4592   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4593     return getTruncateExpr(V, Ty, Depth);
4594   return getSignExtendExpr(V, Ty, Depth);
4595 }
4596 
4597 const SCEV *
4598 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4599   Type *SrcTy = V->getType();
4600   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4601          "Cannot noop or zero extend with non-integer arguments!");
4602   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4603          "getNoopOrZeroExtend cannot truncate!");
4604   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4605     return V;  // No conversion
4606   return getZeroExtendExpr(V, Ty);
4607 }
4608 
4609 const SCEV *
4610 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4611   Type *SrcTy = V->getType();
4612   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4613          "Cannot noop or sign extend with non-integer arguments!");
4614   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4615          "getNoopOrSignExtend cannot truncate!");
4616   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4617     return V;  // No conversion
4618   return getSignExtendExpr(V, Ty);
4619 }
4620 
4621 const SCEV *
4622 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4623   Type *SrcTy = V->getType();
4624   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4625          "Cannot noop or any extend with non-integer arguments!");
4626   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4627          "getNoopOrAnyExtend cannot truncate!");
4628   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4629     return V;  // No conversion
4630   return getAnyExtendExpr(V, Ty);
4631 }
4632 
4633 const SCEV *
4634 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4635   Type *SrcTy = V->getType();
4636   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4637          "Cannot truncate or noop with non-integer arguments!");
4638   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4639          "getTruncateOrNoop cannot extend!");
4640   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4641     return V;  // No conversion
4642   return getTruncateExpr(V, Ty);
4643 }
4644 
4645 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4646                                                         const SCEV *RHS) {
4647   const SCEV *PromotedLHS = LHS;
4648   const SCEV *PromotedRHS = RHS;
4649 
4650   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4651     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4652   else
4653     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4654 
4655   return getUMaxExpr(PromotedLHS, PromotedRHS);
4656 }
4657 
4658 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4659                                                         const SCEV *RHS,
4660                                                         bool Sequential) {
4661   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4662   return getUMinFromMismatchedTypes(Ops, Sequential);
4663 }
4664 
4665 const SCEV *
4666 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4667                                             bool Sequential) {
4668   assert(!Ops.empty() && "At least one operand must be!");
4669   // Trivial case.
4670   if (Ops.size() == 1)
4671     return Ops[0];
4672 
4673   // Find the max type first.
4674   Type *MaxType = nullptr;
4675   for (auto *S : Ops)
4676     if (MaxType)
4677       MaxType = getWiderType(MaxType, S->getType());
4678     else
4679       MaxType = S->getType();
4680   assert(MaxType && "Failed to find maximum type!");
4681 
4682   // Extend all ops to max type.
4683   SmallVector<const SCEV *, 2> PromotedOps;
4684   for (auto *S : Ops)
4685     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4686 
4687   // Generate umin.
4688   return getUMinExpr(PromotedOps, Sequential);
4689 }
4690 
4691 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4692   // A pointer operand may evaluate to a nonpointer expression, such as null.
4693   if (!V->getType()->isPointerTy())
4694     return V;
4695 
4696   while (true) {
4697     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4698       V = AddRec->getStart();
4699     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4700       const SCEV *PtrOp = nullptr;
4701       for (const SCEV *AddOp : Add->operands()) {
4702         if (AddOp->getType()->isPointerTy()) {
4703           assert(!PtrOp && "Cannot have multiple pointer ops");
4704           PtrOp = AddOp;
4705         }
4706       }
4707       assert(PtrOp && "Must have pointer op");
4708       V = PtrOp;
4709     } else // Not something we can look further into.
4710       return V;
4711   }
4712 }
4713 
4714 /// Push users of the given Instruction onto the given Worklist.
4715 static void PushDefUseChildren(Instruction *I,
4716                                SmallVectorImpl<Instruction *> &Worklist,
4717                                SmallPtrSetImpl<Instruction *> &Visited) {
4718   // Push the def-use children onto the Worklist stack.
4719   for (User *U : I->users()) {
4720     auto *UserInsn = cast<Instruction>(U);
4721     if (Visited.insert(UserInsn).second)
4722       Worklist.push_back(UserInsn);
4723   }
4724 }
4725 
4726 namespace {
4727 
4728 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4729 /// expression in case its Loop is L. If it is not L then
4730 /// if IgnoreOtherLoops is true then use AddRec itself
4731 /// otherwise rewrite cannot be done.
4732 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4733 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4734 public:
4735   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4736                              bool IgnoreOtherLoops = true) {
4737     SCEVInitRewriter Rewriter(L, SE);
4738     const SCEV *Result = Rewriter.visit(S);
4739     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4740       return SE.getCouldNotCompute();
4741     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4742                ? SE.getCouldNotCompute()
4743                : Result;
4744   }
4745 
4746   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4747     if (!SE.isLoopInvariant(Expr, L))
4748       SeenLoopVariantSCEVUnknown = true;
4749     return Expr;
4750   }
4751 
4752   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4753     // Only re-write AddRecExprs for this loop.
4754     if (Expr->getLoop() == L)
4755       return Expr->getStart();
4756     SeenOtherLoops = true;
4757     return Expr;
4758   }
4759 
4760   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4761 
4762   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4763 
4764 private:
4765   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4766       : SCEVRewriteVisitor(SE), L(L) {}
4767 
4768   const Loop *L;
4769   bool SeenLoopVariantSCEVUnknown = false;
4770   bool SeenOtherLoops = false;
4771 };
4772 
4773 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4774 /// increment expression in case its Loop is L. If it is not L then
4775 /// use AddRec itself.
4776 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4777 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4778 public:
4779   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4780     SCEVPostIncRewriter Rewriter(L, SE);
4781     const SCEV *Result = Rewriter.visit(S);
4782     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4783         ? SE.getCouldNotCompute()
4784         : Result;
4785   }
4786 
4787   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4788     if (!SE.isLoopInvariant(Expr, L))
4789       SeenLoopVariantSCEVUnknown = true;
4790     return Expr;
4791   }
4792 
4793   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4794     // Only re-write AddRecExprs for this loop.
4795     if (Expr->getLoop() == L)
4796       return Expr->getPostIncExpr(SE);
4797     SeenOtherLoops = true;
4798     return Expr;
4799   }
4800 
4801   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4802 
4803   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4804 
4805 private:
4806   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4807       : SCEVRewriteVisitor(SE), L(L) {}
4808 
4809   const Loop *L;
4810   bool SeenLoopVariantSCEVUnknown = false;
4811   bool SeenOtherLoops = false;
4812 };
4813 
4814 /// This class evaluates the compare condition by matching it against the
4815 /// condition of loop latch. If there is a match we assume a true value
4816 /// for the condition while building SCEV nodes.
4817 class SCEVBackedgeConditionFolder
4818     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4819 public:
4820   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4821                              ScalarEvolution &SE) {
4822     bool IsPosBECond = false;
4823     Value *BECond = nullptr;
4824     if (BasicBlock *Latch = L->getLoopLatch()) {
4825       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4826       if (BI && BI->isConditional()) {
4827         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4828                "Both outgoing branches should not target same header!");
4829         BECond = BI->getCondition();
4830         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4831       } else {
4832         return S;
4833       }
4834     }
4835     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4836     return Rewriter.visit(S);
4837   }
4838 
4839   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4840     const SCEV *Result = Expr;
4841     bool InvariantF = SE.isLoopInvariant(Expr, L);
4842 
4843     if (!InvariantF) {
4844       Instruction *I = cast<Instruction>(Expr->getValue());
4845       switch (I->getOpcode()) {
4846       case Instruction::Select: {
4847         SelectInst *SI = cast<SelectInst>(I);
4848         Optional<const SCEV *> Res =
4849             compareWithBackedgeCondition(SI->getCondition());
4850         if (Res.hasValue()) {
4851           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4852           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4853         }
4854         break;
4855       }
4856       default: {
4857         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4858         if (Res.hasValue())
4859           Result = Res.getValue();
4860         break;
4861       }
4862       }
4863     }
4864     return Result;
4865   }
4866 
4867 private:
4868   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4869                                        bool IsPosBECond, ScalarEvolution &SE)
4870       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4871         IsPositiveBECond(IsPosBECond) {}
4872 
4873   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4874 
4875   const Loop *L;
4876   /// Loop back condition.
4877   Value *BackedgeCond = nullptr;
4878   /// Set to true if loop back is on positive branch condition.
4879   bool IsPositiveBECond;
4880 };
4881 
4882 Optional<const SCEV *>
4883 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4884 
4885   // If value matches the backedge condition for loop latch,
4886   // then return a constant evolution node based on loopback
4887   // branch taken.
4888   if (BackedgeCond == IC)
4889     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4890                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4891   return None;
4892 }
4893 
4894 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4895 public:
4896   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4897                              ScalarEvolution &SE) {
4898     SCEVShiftRewriter Rewriter(L, SE);
4899     const SCEV *Result = Rewriter.visit(S);
4900     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4901   }
4902 
4903   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4904     // Only allow AddRecExprs for this loop.
4905     if (!SE.isLoopInvariant(Expr, L))
4906       Valid = false;
4907     return Expr;
4908   }
4909 
4910   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4911     if (Expr->getLoop() == L && Expr->isAffine())
4912       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4913     Valid = false;
4914     return Expr;
4915   }
4916 
4917   bool isValid() { return Valid; }
4918 
4919 private:
4920   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4921       : SCEVRewriteVisitor(SE), L(L) {}
4922 
4923   const Loop *L;
4924   bool Valid = true;
4925 };
4926 
4927 } // end anonymous namespace
4928 
4929 SCEV::NoWrapFlags
4930 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4931   if (!AR->isAffine())
4932     return SCEV::FlagAnyWrap;
4933 
4934   using OBO = OverflowingBinaryOperator;
4935 
4936   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4937 
4938   if (!AR->hasNoSignedWrap()) {
4939     ConstantRange AddRecRange = getSignedRange(AR);
4940     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4941 
4942     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4943         Instruction::Add, IncRange, OBO::NoSignedWrap);
4944     if (NSWRegion.contains(AddRecRange))
4945       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4946   }
4947 
4948   if (!AR->hasNoUnsignedWrap()) {
4949     ConstantRange AddRecRange = getUnsignedRange(AR);
4950     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4951 
4952     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4953         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4954     if (NUWRegion.contains(AddRecRange))
4955       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4956   }
4957 
4958   return Result;
4959 }
4960 
4961 SCEV::NoWrapFlags
4962 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4963   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4964 
4965   if (AR->hasNoSignedWrap())
4966     return Result;
4967 
4968   if (!AR->isAffine())
4969     return Result;
4970 
4971   const SCEV *Step = AR->getStepRecurrence(*this);
4972   const Loop *L = AR->getLoop();
4973 
4974   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4975   // Note that this serves two purposes: It filters out loops that are
4976   // simply not analyzable, and it covers the case where this code is
4977   // being called from within backedge-taken count analysis, such that
4978   // attempting to ask for the backedge-taken count would likely result
4979   // in infinite recursion. In the later case, the analysis code will
4980   // cope with a conservative value, and it will take care to purge
4981   // that value once it has finished.
4982   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4983 
4984   // Normally, in the cases we can prove no-overflow via a
4985   // backedge guarding condition, we can also compute a backedge
4986   // taken count for the loop.  The exceptions are assumptions and
4987   // guards present in the loop -- SCEV is not great at exploiting
4988   // these to compute max backedge taken counts, but can still use
4989   // these to prove lack of overflow.  Use this fact to avoid
4990   // doing extra work that may not pay off.
4991 
4992   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4993       AC.assumptions().empty())
4994     return Result;
4995 
4996   // If the backedge is guarded by a comparison with the pre-inc  value the
4997   // addrec is safe. Also, if the entry is guarded by a comparison with the
4998   // start value and the backedge is guarded by a comparison with the post-inc
4999   // value, the addrec is safe.
5000   ICmpInst::Predicate Pred;
5001   const SCEV *OverflowLimit =
5002     getSignedOverflowLimitForStep(Step, &Pred, this);
5003   if (OverflowLimit &&
5004       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5005        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5006     Result = setFlags(Result, SCEV::FlagNSW);
5007   }
5008   return Result;
5009 }
5010 SCEV::NoWrapFlags
5011 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5012   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5013 
5014   if (AR->hasNoUnsignedWrap())
5015     return Result;
5016 
5017   if (!AR->isAffine())
5018     return Result;
5019 
5020   const SCEV *Step = AR->getStepRecurrence(*this);
5021   unsigned BitWidth = getTypeSizeInBits(AR->getType());
5022   const Loop *L = AR->getLoop();
5023 
5024   // Check whether the backedge-taken count is SCEVCouldNotCompute.
5025   // Note that this serves two purposes: It filters out loops that are
5026   // simply not analyzable, and it covers the case where this code is
5027   // being called from within backedge-taken count analysis, such that
5028   // attempting to ask for the backedge-taken count would likely result
5029   // in infinite recursion. In the later case, the analysis code will
5030   // cope with a conservative value, and it will take care to purge
5031   // that value once it has finished.
5032   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5033 
5034   // Normally, in the cases we can prove no-overflow via a
5035   // backedge guarding condition, we can also compute a backedge
5036   // taken count for the loop.  The exceptions are assumptions and
5037   // guards present in the loop -- SCEV is not great at exploiting
5038   // these to compute max backedge taken counts, but can still use
5039   // these to prove lack of overflow.  Use this fact to avoid
5040   // doing extra work that may not pay off.
5041 
5042   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5043       AC.assumptions().empty())
5044     return Result;
5045 
5046   // If the backedge is guarded by a comparison with the pre-inc  value the
5047   // addrec is safe. Also, if the entry is guarded by a comparison with the
5048   // start value and the backedge is guarded by a comparison with the post-inc
5049   // value, the addrec is safe.
5050   if (isKnownPositive(Step)) {
5051     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5052                                 getUnsignedRangeMax(Step));
5053     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5054         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5055       Result = setFlags(Result, SCEV::FlagNUW);
5056     }
5057   }
5058 
5059   return Result;
5060 }
5061 
5062 namespace {
5063 
5064 /// Represents an abstract binary operation.  This may exist as a
5065 /// normal instruction or constant expression, or may have been
5066 /// derived from an expression tree.
5067 struct BinaryOp {
5068   unsigned Opcode;
5069   Value *LHS;
5070   Value *RHS;
5071   bool IsNSW = false;
5072   bool IsNUW = false;
5073 
5074   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5075   /// constant expression.
5076   Operator *Op = nullptr;
5077 
5078   explicit BinaryOp(Operator *Op)
5079       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5080         Op(Op) {
5081     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5082       IsNSW = OBO->hasNoSignedWrap();
5083       IsNUW = OBO->hasNoUnsignedWrap();
5084     }
5085   }
5086 
5087   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5088                     bool IsNUW = false)
5089       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5090 };
5091 
5092 } // end anonymous namespace
5093 
5094 /// Try to map \p V into a BinaryOp, and return \c None on failure.
5095 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
5096   auto *Op = dyn_cast<Operator>(V);
5097   if (!Op)
5098     return None;
5099 
5100   // Implementation detail: all the cleverness here should happen without
5101   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5102   // SCEV expressions when possible, and we should not break that.
5103 
5104   switch (Op->getOpcode()) {
5105   case Instruction::Add:
5106   case Instruction::Sub:
5107   case Instruction::Mul:
5108   case Instruction::UDiv:
5109   case Instruction::URem:
5110   case Instruction::And:
5111   case Instruction::Or:
5112   case Instruction::AShr:
5113   case Instruction::Shl:
5114     return BinaryOp(Op);
5115 
5116   case Instruction::Xor:
5117     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5118       // If the RHS of the xor is a signmask, then this is just an add.
5119       // Instcombine turns add of signmask into xor as a strength reduction step.
5120       if (RHSC->getValue().isSignMask())
5121         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5122     // Binary `xor` is a bit-wise `add`.
5123     if (V->getType()->isIntegerTy(1))
5124       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5125     return BinaryOp(Op);
5126 
5127   case Instruction::LShr:
5128     // Turn logical shift right of a constant into a unsigned divide.
5129     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5130       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5131 
5132       // If the shift count is not less than the bitwidth, the result of
5133       // the shift is undefined. Don't try to analyze it, because the
5134       // resolution chosen here may differ from the resolution chosen in
5135       // other parts of the compiler.
5136       if (SA->getValue().ult(BitWidth)) {
5137         Constant *X =
5138             ConstantInt::get(SA->getContext(),
5139                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5140         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5141       }
5142     }
5143     return BinaryOp(Op);
5144 
5145   case Instruction::ExtractValue: {
5146     auto *EVI = cast<ExtractValueInst>(Op);
5147     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5148       break;
5149 
5150     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5151     if (!WO)
5152       break;
5153 
5154     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5155     bool Signed = WO->isSigned();
5156     // TODO: Should add nuw/nsw flags for mul as well.
5157     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5158       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5159 
5160     // Now that we know that all uses of the arithmetic-result component of
5161     // CI are guarded by the overflow check, we can go ahead and pretend
5162     // that the arithmetic is non-overflowing.
5163     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5164                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5165   }
5166 
5167   default:
5168     break;
5169   }
5170 
5171   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5172   // semantics as a Sub, return a binary sub expression.
5173   if (auto *II = dyn_cast<IntrinsicInst>(V))
5174     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5175       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5176 
5177   return None;
5178 }
5179 
5180 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5181 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5182 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5183 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5184 /// follows one of the following patterns:
5185 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5186 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5187 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5188 /// we return the type of the truncation operation, and indicate whether the
5189 /// truncated type should be treated as signed/unsigned by setting
5190 /// \p Signed to true/false, respectively.
5191 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5192                                bool &Signed, ScalarEvolution &SE) {
5193   // The case where Op == SymbolicPHI (that is, with no type conversions on
5194   // the way) is handled by the regular add recurrence creating logic and
5195   // would have already been triggered in createAddRecForPHI. Reaching it here
5196   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5197   // because one of the other operands of the SCEVAddExpr updating this PHI is
5198   // not invariant).
5199   //
5200   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5201   // this case predicates that allow us to prove that Op == SymbolicPHI will
5202   // be added.
5203   if (Op == SymbolicPHI)
5204     return nullptr;
5205 
5206   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5207   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5208   if (SourceBits != NewBits)
5209     return nullptr;
5210 
5211   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5212   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5213   if (!SExt && !ZExt)
5214     return nullptr;
5215   const SCEVTruncateExpr *Trunc =
5216       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5217            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5218   if (!Trunc)
5219     return nullptr;
5220   const SCEV *X = Trunc->getOperand();
5221   if (X != SymbolicPHI)
5222     return nullptr;
5223   Signed = SExt != nullptr;
5224   return Trunc->getType();
5225 }
5226 
5227 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5228   if (!PN->getType()->isIntegerTy())
5229     return nullptr;
5230   const Loop *L = LI.getLoopFor(PN->getParent());
5231   if (!L || L->getHeader() != PN->getParent())
5232     return nullptr;
5233   return L;
5234 }
5235 
5236 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5237 // computation that updates the phi follows the following pattern:
5238 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5239 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5240 // If so, try to see if it can be rewritten as an AddRecExpr under some
5241 // Predicates. If successful, return them as a pair. Also cache the results
5242 // of the analysis.
5243 //
5244 // Example usage scenario:
5245 //    Say the Rewriter is called for the following SCEV:
5246 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5247 //    where:
5248 //         %X = phi i64 (%Start, %BEValue)
5249 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5250 //    and call this function with %SymbolicPHI = %X.
5251 //
5252 //    The analysis will find that the value coming around the backedge has
5253 //    the following SCEV:
5254 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5255 //    Upon concluding that this matches the desired pattern, the function
5256 //    will return the pair {NewAddRec, SmallPredsVec} where:
5257 //         NewAddRec = {%Start,+,%Step}
5258 //         SmallPredsVec = {P1, P2, P3} as follows:
5259 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5260 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5261 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5262 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5263 //    under the predicates {P1,P2,P3}.
5264 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5265 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5266 //
5267 // TODO's:
5268 //
5269 // 1) Extend the Induction descriptor to also support inductions that involve
5270 //    casts: When needed (namely, when we are called in the context of the
5271 //    vectorizer induction analysis), a Set of cast instructions will be
5272 //    populated by this method, and provided back to isInductionPHI. This is
5273 //    needed to allow the vectorizer to properly record them to be ignored by
5274 //    the cost model and to avoid vectorizing them (otherwise these casts,
5275 //    which are redundant under the runtime overflow checks, will be
5276 //    vectorized, which can be costly).
5277 //
5278 // 2) Support additional induction/PHISCEV patterns: We also want to support
5279 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5280 //    after the induction update operation (the induction increment):
5281 //
5282 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5283 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5284 //
5285 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5286 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5287 //
5288 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5289 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5290 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5291   SmallVector<const SCEVPredicate *, 3> Predicates;
5292 
5293   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5294   // return an AddRec expression under some predicate.
5295 
5296   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5297   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5298   assert(L && "Expecting an integer loop header phi");
5299 
5300   // The loop may have multiple entrances or multiple exits; we can analyze
5301   // this phi as an addrec if it has a unique entry value and a unique
5302   // backedge value.
5303   Value *BEValueV = nullptr, *StartValueV = nullptr;
5304   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5305     Value *V = PN->getIncomingValue(i);
5306     if (L->contains(PN->getIncomingBlock(i))) {
5307       if (!BEValueV) {
5308         BEValueV = V;
5309       } else if (BEValueV != V) {
5310         BEValueV = nullptr;
5311         break;
5312       }
5313     } else if (!StartValueV) {
5314       StartValueV = V;
5315     } else if (StartValueV != V) {
5316       StartValueV = nullptr;
5317       break;
5318     }
5319   }
5320   if (!BEValueV || !StartValueV)
5321     return None;
5322 
5323   const SCEV *BEValue = getSCEV(BEValueV);
5324 
5325   // If the value coming around the backedge is an add with the symbolic
5326   // value we just inserted, possibly with casts that we can ignore under
5327   // an appropriate runtime guard, then we found a simple induction variable!
5328   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5329   if (!Add)
5330     return None;
5331 
5332   // If there is a single occurrence of the symbolic value, possibly
5333   // casted, replace it with a recurrence.
5334   unsigned FoundIndex = Add->getNumOperands();
5335   Type *TruncTy = nullptr;
5336   bool Signed;
5337   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5338     if ((TruncTy =
5339              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5340       if (FoundIndex == e) {
5341         FoundIndex = i;
5342         break;
5343       }
5344 
5345   if (FoundIndex == Add->getNumOperands())
5346     return None;
5347 
5348   // Create an add with everything but the specified operand.
5349   SmallVector<const SCEV *, 8> Ops;
5350   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5351     if (i != FoundIndex)
5352       Ops.push_back(Add->getOperand(i));
5353   const SCEV *Accum = getAddExpr(Ops);
5354 
5355   // The runtime checks will not be valid if the step amount is
5356   // varying inside the loop.
5357   if (!isLoopInvariant(Accum, L))
5358     return None;
5359 
5360   // *** Part2: Create the predicates
5361 
5362   // Analysis was successful: we have a phi-with-cast pattern for which we
5363   // can return an AddRec expression under the following predicates:
5364   //
5365   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5366   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5367   // P2: An Equal predicate that guarantees that
5368   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5369   // P3: An Equal predicate that guarantees that
5370   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5371   //
5372   // As we next prove, the above predicates guarantee that:
5373   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5374   //
5375   //
5376   // More formally, we want to prove that:
5377   //     Expr(i+1) = Start + (i+1) * Accum
5378   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5379   //
5380   // Given that:
5381   // 1) Expr(0) = Start
5382   // 2) Expr(1) = Start + Accum
5383   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5384   // 3) Induction hypothesis (step i):
5385   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5386   //
5387   // Proof:
5388   //  Expr(i+1) =
5389   //   = Start + (i+1)*Accum
5390   //   = (Start + i*Accum) + Accum
5391   //   = Expr(i) + Accum
5392   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5393   //                                                             :: from step i
5394   //
5395   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5396   //
5397   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5398   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5399   //     + Accum                                                     :: from P3
5400   //
5401   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5402   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5403   //
5404   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5405   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5406   //
5407   // By induction, the same applies to all iterations 1<=i<n:
5408   //
5409 
5410   // Create a truncated addrec for which we will add a no overflow check (P1).
5411   const SCEV *StartVal = getSCEV(StartValueV);
5412   const SCEV *PHISCEV =
5413       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5414                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5415 
5416   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5417   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5418   // will be constant.
5419   //
5420   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5421   // add P1.
5422   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5423     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5424         Signed ? SCEVWrapPredicate::IncrementNSSW
5425                : SCEVWrapPredicate::IncrementNUSW;
5426     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5427     Predicates.push_back(AddRecPred);
5428   }
5429 
5430   // Create the Equal Predicates P2,P3:
5431 
5432   // It is possible that the predicates P2 and/or P3 are computable at
5433   // compile time due to StartVal and/or Accum being constants.
5434   // If either one is, then we can check that now and escape if either P2
5435   // or P3 is false.
5436 
5437   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5438   // for each of StartVal and Accum
5439   auto getExtendedExpr = [&](const SCEV *Expr,
5440                              bool CreateSignExtend) -> const SCEV * {
5441     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5442     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5443     const SCEV *ExtendedExpr =
5444         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5445                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5446     return ExtendedExpr;
5447   };
5448 
5449   // Given:
5450   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5451   //               = getExtendedExpr(Expr)
5452   // Determine whether the predicate P: Expr == ExtendedExpr
5453   // is known to be false at compile time
5454   auto PredIsKnownFalse = [&](const SCEV *Expr,
5455                               const SCEV *ExtendedExpr) -> bool {
5456     return Expr != ExtendedExpr &&
5457            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5458   };
5459 
5460   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5461   if (PredIsKnownFalse(StartVal, StartExtended)) {
5462     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5463     return None;
5464   }
5465 
5466   // The Step is always Signed (because the overflow checks are either
5467   // NSSW or NUSW)
5468   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5469   if (PredIsKnownFalse(Accum, AccumExtended)) {
5470     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5471     return None;
5472   }
5473 
5474   auto AppendPredicate = [&](const SCEV *Expr,
5475                              const SCEV *ExtendedExpr) -> void {
5476     if (Expr != ExtendedExpr &&
5477         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5478       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5479       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5480       Predicates.push_back(Pred);
5481     }
5482   };
5483 
5484   AppendPredicate(StartVal, StartExtended);
5485   AppendPredicate(Accum, AccumExtended);
5486 
5487   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5488   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5489   // into NewAR if it will also add the runtime overflow checks specified in
5490   // Predicates.
5491   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5492 
5493   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5494       std::make_pair(NewAR, Predicates);
5495   // Remember the result of the analysis for this SCEV at this locayyytion.
5496   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5497   return PredRewrite;
5498 }
5499 
5500 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5501 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5502   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5503   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5504   if (!L)
5505     return None;
5506 
5507   // Check to see if we already analyzed this PHI.
5508   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5509   if (I != PredicatedSCEVRewrites.end()) {
5510     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5511         I->second;
5512     // Analysis was done before and failed to create an AddRec:
5513     if (Rewrite.first == SymbolicPHI)
5514       return None;
5515     // Analysis was done before and succeeded to create an AddRec under
5516     // a predicate:
5517     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5518     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5519     return Rewrite;
5520   }
5521 
5522   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5523     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5524 
5525   // Record in the cache that the analysis failed
5526   if (!Rewrite) {
5527     SmallVector<const SCEVPredicate *, 3> Predicates;
5528     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5529     return None;
5530   }
5531 
5532   return Rewrite;
5533 }
5534 
5535 // FIXME: This utility is currently required because the Rewriter currently
5536 // does not rewrite this expression:
5537 // {0, +, (sext ix (trunc iy to ix) to iy)}
5538 // into {0, +, %step},
5539 // even when the following Equal predicate exists:
5540 // "%step == (sext ix (trunc iy to ix) to iy)".
5541 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5542     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5543   if (AR1 == AR2)
5544     return true;
5545 
5546   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5547     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5548         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5549       return false;
5550     return true;
5551   };
5552 
5553   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5554       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5555     return false;
5556   return true;
5557 }
5558 
5559 /// A helper function for createAddRecFromPHI to handle simple cases.
5560 ///
5561 /// This function tries to find an AddRec expression for the simplest (yet most
5562 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5563 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5564 /// technique for finding the AddRec expression.
5565 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5566                                                       Value *BEValueV,
5567                                                       Value *StartValueV) {
5568   const Loop *L = LI.getLoopFor(PN->getParent());
5569   assert(L && L->getHeader() == PN->getParent());
5570   assert(BEValueV && StartValueV);
5571 
5572   auto BO = MatchBinaryOp(BEValueV, DT);
5573   if (!BO)
5574     return nullptr;
5575 
5576   if (BO->Opcode != Instruction::Add)
5577     return nullptr;
5578 
5579   const SCEV *Accum = nullptr;
5580   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5581     Accum = getSCEV(BO->RHS);
5582   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5583     Accum = getSCEV(BO->LHS);
5584 
5585   if (!Accum)
5586     return nullptr;
5587 
5588   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5589   if (BO->IsNUW)
5590     Flags = setFlags(Flags, SCEV::FlagNUW);
5591   if (BO->IsNSW)
5592     Flags = setFlags(Flags, SCEV::FlagNSW);
5593 
5594   const SCEV *StartVal = getSCEV(StartValueV);
5595   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5596   insertValueToMap(PN, PHISCEV);
5597 
5598   // We can add Flags to the post-inc expression only if we
5599   // know that it is *undefined behavior* for BEValueV to
5600   // overflow.
5601   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5602     assert(isLoopInvariant(Accum, L) &&
5603            "Accum is defined outside L, but is not invariant?");
5604     if (isAddRecNeverPoison(BEInst, L))
5605       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5606   }
5607 
5608   return PHISCEV;
5609 }
5610 
5611 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5612   const Loop *L = LI.getLoopFor(PN->getParent());
5613   if (!L || L->getHeader() != PN->getParent())
5614     return nullptr;
5615 
5616   // The loop may have multiple entrances or multiple exits; we can analyze
5617   // this phi as an addrec if it has a unique entry value and a unique
5618   // backedge value.
5619   Value *BEValueV = nullptr, *StartValueV = nullptr;
5620   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5621     Value *V = PN->getIncomingValue(i);
5622     if (L->contains(PN->getIncomingBlock(i))) {
5623       if (!BEValueV) {
5624         BEValueV = V;
5625       } else if (BEValueV != V) {
5626         BEValueV = nullptr;
5627         break;
5628       }
5629     } else if (!StartValueV) {
5630       StartValueV = V;
5631     } else if (StartValueV != V) {
5632       StartValueV = nullptr;
5633       break;
5634     }
5635   }
5636   if (!BEValueV || !StartValueV)
5637     return nullptr;
5638 
5639   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5640          "PHI node already processed?");
5641 
5642   // First, try to find AddRec expression without creating a fictituos symbolic
5643   // value for PN.
5644   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5645     return S;
5646 
5647   // Handle PHI node value symbolically.
5648   const SCEV *SymbolicName = getUnknown(PN);
5649   insertValueToMap(PN, SymbolicName);
5650 
5651   // Using this symbolic name for the PHI, analyze the value coming around
5652   // the back-edge.
5653   const SCEV *BEValue = getSCEV(BEValueV);
5654 
5655   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5656   // has a special value for the first iteration of the loop.
5657 
5658   // If the value coming around the backedge is an add with the symbolic
5659   // value we just inserted, then we found a simple induction variable!
5660   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5661     // If there is a single occurrence of the symbolic value, replace it
5662     // with a recurrence.
5663     unsigned FoundIndex = Add->getNumOperands();
5664     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5665       if (Add->getOperand(i) == SymbolicName)
5666         if (FoundIndex == e) {
5667           FoundIndex = i;
5668           break;
5669         }
5670 
5671     if (FoundIndex != Add->getNumOperands()) {
5672       // Create an add with everything but the specified operand.
5673       SmallVector<const SCEV *, 8> Ops;
5674       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5675         if (i != FoundIndex)
5676           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5677                                                              L, *this));
5678       const SCEV *Accum = getAddExpr(Ops);
5679 
5680       // This is not a valid addrec if the step amount is varying each
5681       // loop iteration, but is not itself an addrec in this loop.
5682       if (isLoopInvariant(Accum, L) ||
5683           (isa<SCEVAddRecExpr>(Accum) &&
5684            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5685         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5686 
5687         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5688           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5689             if (BO->IsNUW)
5690               Flags = setFlags(Flags, SCEV::FlagNUW);
5691             if (BO->IsNSW)
5692               Flags = setFlags(Flags, SCEV::FlagNSW);
5693           }
5694         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5695           // If the increment is an inbounds GEP, then we know the address
5696           // space cannot be wrapped around. We cannot make any guarantee
5697           // about signed or unsigned overflow because pointers are
5698           // unsigned but we may have a negative index from the base
5699           // pointer. We can guarantee that no unsigned wrap occurs if the
5700           // indices form a positive value.
5701           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5702             Flags = setFlags(Flags, SCEV::FlagNW);
5703 
5704             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5705             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5706               Flags = setFlags(Flags, SCEV::FlagNUW);
5707           }
5708 
5709           // We cannot transfer nuw and nsw flags from subtraction
5710           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5711           // for instance.
5712         }
5713 
5714         const SCEV *StartVal = getSCEV(StartValueV);
5715         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5716 
5717         // Okay, for the entire analysis of this edge we assumed the PHI
5718         // to be symbolic.  We now need to go back and purge all of the
5719         // entries for the scalars that use the symbolic expression.
5720         forgetMemoizedResults(SymbolicName);
5721         insertValueToMap(PN, PHISCEV);
5722 
5723         // We can add Flags to the post-inc expression only if we
5724         // know that it is *undefined behavior* for BEValueV to
5725         // overflow.
5726         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5727           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5728             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5729 
5730         return PHISCEV;
5731       }
5732     }
5733   } else {
5734     // Otherwise, this could be a loop like this:
5735     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5736     // In this case, j = {1,+,1}  and BEValue is j.
5737     // Because the other in-value of i (0) fits the evolution of BEValue
5738     // i really is an addrec evolution.
5739     //
5740     // We can generalize this saying that i is the shifted value of BEValue
5741     // by one iteration:
5742     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5743     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5744     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5745     if (Shifted != getCouldNotCompute() &&
5746         Start != getCouldNotCompute()) {
5747       const SCEV *StartVal = getSCEV(StartValueV);
5748       if (Start == StartVal) {
5749         // Okay, for the entire analysis of this edge we assumed the PHI
5750         // to be symbolic.  We now need to go back and purge all of the
5751         // entries for the scalars that use the symbolic expression.
5752         forgetMemoizedResults(SymbolicName);
5753         insertValueToMap(PN, Shifted);
5754         return Shifted;
5755       }
5756     }
5757   }
5758 
5759   // Remove the temporary PHI node SCEV that has been inserted while intending
5760   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5761   // as it will prevent later (possibly simpler) SCEV expressions to be added
5762   // to the ValueExprMap.
5763   eraseValueFromMap(PN);
5764 
5765   return nullptr;
5766 }
5767 
5768 // Checks if the SCEV S is available at BB.  S is considered available at BB
5769 // if S can be materialized at BB without introducing a fault.
5770 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5771                                BasicBlock *BB) {
5772   struct CheckAvailable {
5773     bool TraversalDone = false;
5774     bool Available = true;
5775 
5776     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5777     BasicBlock *BB = nullptr;
5778     DominatorTree &DT;
5779 
5780     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5781       : L(L), BB(BB), DT(DT) {}
5782 
5783     bool setUnavailable() {
5784       TraversalDone = true;
5785       Available = false;
5786       return false;
5787     }
5788 
5789     bool follow(const SCEV *S) {
5790       switch (S->getSCEVType()) {
5791       case scConstant:
5792       case scPtrToInt:
5793       case scTruncate:
5794       case scZeroExtend:
5795       case scSignExtend:
5796       case scAddExpr:
5797       case scMulExpr:
5798       case scUMaxExpr:
5799       case scSMaxExpr:
5800       case scUMinExpr:
5801       case scSMinExpr:
5802       case scSequentialUMinExpr:
5803         // These expressions are available if their operand(s) is/are.
5804         return true;
5805 
5806       case scAddRecExpr: {
5807         // We allow add recurrences that are on the loop BB is in, or some
5808         // outer loop.  This guarantees availability because the value of the
5809         // add recurrence at BB is simply the "current" value of the induction
5810         // variable.  We can relax this in the future; for instance an add
5811         // recurrence on a sibling dominating loop is also available at BB.
5812         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5813         if (L && (ARLoop == L || ARLoop->contains(L)))
5814           return true;
5815 
5816         return setUnavailable();
5817       }
5818 
5819       case scUnknown: {
5820         // For SCEVUnknown, we check for simple dominance.
5821         const auto *SU = cast<SCEVUnknown>(S);
5822         Value *V = SU->getValue();
5823 
5824         if (isa<Argument>(V))
5825           return false;
5826 
5827         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5828           return false;
5829 
5830         return setUnavailable();
5831       }
5832 
5833       case scUDivExpr:
5834       case scCouldNotCompute:
5835         // We do not try to smart about these at all.
5836         return setUnavailable();
5837       }
5838       llvm_unreachable("Unknown SCEV kind!");
5839     }
5840 
5841     bool isDone() { return TraversalDone; }
5842   };
5843 
5844   CheckAvailable CA(L, BB, DT);
5845   SCEVTraversal<CheckAvailable> ST(CA);
5846 
5847   ST.visitAll(S);
5848   return CA.Available;
5849 }
5850 
5851 // Try to match a control flow sequence that branches out at BI and merges back
5852 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5853 // match.
5854 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5855                           Value *&C, Value *&LHS, Value *&RHS) {
5856   C = BI->getCondition();
5857 
5858   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5859   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5860 
5861   if (!LeftEdge.isSingleEdge())
5862     return false;
5863 
5864   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5865 
5866   Use &LeftUse = Merge->getOperandUse(0);
5867   Use &RightUse = Merge->getOperandUse(1);
5868 
5869   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5870     LHS = LeftUse;
5871     RHS = RightUse;
5872     return true;
5873   }
5874 
5875   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5876     LHS = RightUse;
5877     RHS = LeftUse;
5878     return true;
5879   }
5880 
5881   return false;
5882 }
5883 
5884 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5885   auto IsReachable =
5886       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5887   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5888     const Loop *L = LI.getLoopFor(PN->getParent());
5889 
5890     // We don't want to break LCSSA, even in a SCEV expression tree.
5891     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5892       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5893         return nullptr;
5894 
5895     // Try to match
5896     //
5897     //  br %cond, label %left, label %right
5898     // left:
5899     //  br label %merge
5900     // right:
5901     //  br label %merge
5902     // merge:
5903     //  V = phi [ %x, %left ], [ %y, %right ]
5904     //
5905     // as "select %cond, %x, %y"
5906 
5907     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5908     assert(IDom && "At least the entry block should dominate PN");
5909 
5910     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5911     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5912 
5913     if (BI && BI->isConditional() &&
5914         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5915         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5916         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5917       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5918   }
5919 
5920   return nullptr;
5921 }
5922 
5923 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5924   if (const SCEV *S = createAddRecFromPHI(PN))
5925     return S;
5926 
5927   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5928     return S;
5929 
5930   // If the PHI has a single incoming value, follow that value, unless the
5931   // PHI's incoming blocks are in a different loop, in which case doing so
5932   // risks breaking LCSSA form. Instcombine would normally zap these, but
5933   // it doesn't have DominatorTree information, so it may miss cases.
5934   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5935     if (LI.replacementPreservesLCSSAForm(PN, V))
5936       return getSCEV(V);
5937 
5938   // If it's not a loop phi, we can't handle it yet.
5939   return getUnknown(PN);
5940 }
5941 
5942 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5943                             SCEVTypes RootKind) {
5944   struct FindClosure {
5945     const SCEV *OperandToFind;
5946     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5947     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5948 
5949     bool Found = false;
5950 
5951     bool canRecurseInto(SCEVTypes Kind) const {
5952       // We can only recurse into the SCEV expression of the same effective type
5953       // as the type of our root SCEV expression, and into zero-extensions.
5954       return RootKind == Kind || NonSequentialRootKind == Kind ||
5955              scZeroExtend == Kind;
5956     };
5957 
5958     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5959         : OperandToFind(OperandToFind), RootKind(RootKind),
5960           NonSequentialRootKind(
5961               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5962                   RootKind)) {}
5963 
5964     bool follow(const SCEV *S) {
5965       Found = S == OperandToFind;
5966 
5967       return !isDone() && canRecurseInto(S->getSCEVType());
5968     }
5969 
5970     bool isDone() const { return Found; }
5971   };
5972 
5973   FindClosure FC(OperandToFind, RootKind);
5974   visitAll(Root, FC);
5975   return FC.Found;
5976 }
5977 
5978 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(
5979     Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) {
5980   // Try to match some simple smax or umax patterns.
5981   auto *ICI = Cond;
5982 
5983   Value *LHS = ICI->getOperand(0);
5984   Value *RHS = ICI->getOperand(1);
5985 
5986   switch (ICI->getPredicate()) {
5987   case ICmpInst::ICMP_SLT:
5988   case ICmpInst::ICMP_SLE:
5989   case ICmpInst::ICMP_ULT:
5990   case ICmpInst::ICMP_ULE:
5991     std::swap(LHS, RHS);
5992     LLVM_FALLTHROUGH;
5993   case ICmpInst::ICMP_SGT:
5994   case ICmpInst::ICMP_SGE:
5995   case ICmpInst::ICMP_UGT:
5996   case ICmpInst::ICMP_UGE:
5997     // a > b ? a+x : b+x  ->  max(a, b)+x
5998     // a > b ? b+x : a+x  ->  min(a, b)+x
5999     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
6000       bool Signed = ICI->isSigned();
6001       const SCEV *LA = getSCEV(TrueVal);
6002       const SCEV *RA = getSCEV(FalseVal);
6003       const SCEV *LS = getSCEV(LHS);
6004       const SCEV *RS = getSCEV(RHS);
6005       if (LA->getType()->isPointerTy()) {
6006         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6007         // Need to make sure we can't produce weird expressions involving
6008         // negated pointers.
6009         if (LA == LS && RA == RS)
6010           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6011         if (LA == RS && RA == LS)
6012           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6013       }
6014       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6015         if (Op->getType()->isPointerTy()) {
6016           Op = getLosslessPtrToIntExpr(Op);
6017           if (isa<SCEVCouldNotCompute>(Op))
6018             return Op;
6019         }
6020         if (Signed)
6021           Op = getNoopOrSignExtend(Op, I->getType());
6022         else
6023           Op = getNoopOrZeroExtend(Op, I->getType());
6024         return Op;
6025       };
6026       LS = CoerceOperand(LS);
6027       RS = CoerceOperand(RS);
6028       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6029         break;
6030       const SCEV *LDiff = getMinusSCEV(LA, LS);
6031       const SCEV *RDiff = getMinusSCEV(RA, RS);
6032       if (LDiff == RDiff)
6033         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6034                           LDiff);
6035       LDiff = getMinusSCEV(LA, RS);
6036       RDiff = getMinusSCEV(RA, LS);
6037       if (LDiff == RDiff)
6038         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6039                           LDiff);
6040     }
6041     break;
6042   case ICmpInst::ICMP_NE:
6043     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
6044     std::swap(TrueVal, FalseVal);
6045     LLVM_FALLTHROUGH;
6046   case ICmpInst::ICMP_EQ:
6047     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
6048     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
6049         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6050       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
6051       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
6052       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
6053       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6054       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
6055       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6056         return getAddExpr(getUMaxExpr(X, C), Y);
6057     }
6058     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
6059     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
6060     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
6061     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
6062     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6063         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6064       const SCEV *X = getSCEV(LHS);
6065       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6066         X = ZExt->getOperand();
6067       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) {
6068         const SCEV *FalseValExpr = getSCEV(FalseVal);
6069         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6070           return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr,
6071                              /*Sequential=*/true);
6072       }
6073     }
6074     break;
6075   default:
6076     break;
6077   }
6078 
6079   return getUnknown(I);
6080 }
6081 
6082 static Optional<const SCEV *>
6083 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6084                               const SCEV *TrueExpr, const SCEV *FalseExpr) {
6085   assert(CondExpr->getType()->isIntegerTy(1) &&
6086          TrueExpr->getType() == FalseExpr->getType() &&
6087          TrueExpr->getType()->isIntegerTy(1) &&
6088          "Unexpected operands of a select.");
6089 
6090   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6091   //                        -->  C + (umin_seq  cond, x - C)
6092   //
6093   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6094   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6095   //                        -->  C + (umin_seq ~cond, x - C)
6096 
6097   // FIXME: while we can't legally model the case where both of the hands
6098   // are fully variable, we only require that the *difference* is constant.
6099   if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6100     return None;
6101 
6102   const SCEV *X, *C;
6103   if (isa<SCEVConstant>(TrueExpr)) {
6104     CondExpr = SE->getNotSCEV(CondExpr);
6105     X = FalseExpr;
6106     C = TrueExpr;
6107   } else {
6108     X = TrueExpr;
6109     C = FalseExpr;
6110   }
6111   return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6112                                            /*Sequential=*/true));
6113 }
6114 
6115 static Optional<const SCEV *> createNodeForSelectViaUMinSeq(ScalarEvolution *SE,
6116                                                             Value *Cond,
6117                                                             Value *TrueVal,
6118                                                             Value *FalseVal) {
6119   if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6120     return None;
6121 
6122   const auto *SECond = SE->getSCEV(Cond);
6123   const auto *SETrue = SE->getSCEV(TrueVal);
6124   const auto *SEFalse = SE->getSCEV(FalseVal);
6125   return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6126 }
6127 
6128 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6129     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6130   assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6131   assert(TrueVal->getType() == FalseVal->getType() &&
6132          V->getType() == TrueVal->getType() &&
6133          "Types of select hands and of the result must match.");
6134 
6135   // For now, only deal with i1-typed `select`s.
6136   if (!V->getType()->isIntegerTy(1))
6137     return getUnknown(V);
6138 
6139   if (Optional<const SCEV *> S =
6140           createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6141     return *S;
6142 
6143   return getUnknown(V);
6144 }
6145 
6146 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6147                                                       Value *TrueVal,
6148                                                       Value *FalseVal) {
6149   // Handle "constant" branch or select. This can occur for instance when a
6150   // loop pass transforms an inner loop and moves on to process the outer loop.
6151   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6152     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6153 
6154   if (auto *I = dyn_cast<Instruction>(V)) {
6155     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6156       const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond(
6157           I, ICI, TrueVal, FalseVal);
6158       if (!isa<SCEVUnknown>(S))
6159         return S;
6160     }
6161   }
6162 
6163   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6164 }
6165 
6166 /// Expand GEP instructions into add and multiply operations. This allows them
6167 /// to be analyzed by regular SCEV code.
6168 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6169   // Don't attempt to analyze GEPs over unsized objects.
6170   if (!GEP->getSourceElementType()->isSized())
6171     return getUnknown(GEP);
6172 
6173   SmallVector<const SCEV *, 4> IndexExprs;
6174   for (Value *Index : GEP->indices())
6175     IndexExprs.push_back(getSCEV(Index));
6176   return getGEPExpr(GEP, IndexExprs);
6177 }
6178 
6179 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
6180   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6181     return C->getAPInt().countTrailingZeros();
6182 
6183   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
6184     return GetMinTrailingZeros(I->getOperand());
6185 
6186   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
6187     return std::min(GetMinTrailingZeros(T->getOperand()),
6188                     (uint32_t)getTypeSizeInBits(T->getType()));
6189 
6190   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
6191     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6192     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6193                ? getTypeSizeInBits(E->getType())
6194                : OpRes;
6195   }
6196 
6197   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
6198     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6199     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6200                ? getTypeSizeInBits(E->getType())
6201                : OpRes;
6202   }
6203 
6204   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
6205     // The result is the min of all operands results.
6206     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6207     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6208       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6209     return MinOpRes;
6210   }
6211 
6212   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
6213     // The result is the sum of all operands results.
6214     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
6215     uint32_t BitWidth = getTypeSizeInBits(M->getType());
6216     for (unsigned i = 1, e = M->getNumOperands();
6217          SumOpRes != BitWidth && i != e; ++i)
6218       SumOpRes =
6219           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
6220     return SumOpRes;
6221   }
6222 
6223   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
6224     // The result is the min of all operands results.
6225     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6226     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6227       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6228     return MinOpRes;
6229   }
6230 
6231   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
6232     // The result is the min of all operands results.
6233     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6234     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6235       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6236     return MinOpRes;
6237   }
6238 
6239   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
6240     // The result is the min of all operands results.
6241     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6242     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6243       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6244     return MinOpRes;
6245   }
6246 
6247   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6248     // For a SCEVUnknown, ask ValueTracking.
6249     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
6250     return Known.countMinTrailingZeros();
6251   }
6252 
6253   // SCEVUDivExpr
6254   return 0;
6255 }
6256 
6257 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
6258   auto I = MinTrailingZerosCache.find(S);
6259   if (I != MinTrailingZerosCache.end())
6260     return I->second;
6261 
6262   uint32_t Result = GetMinTrailingZerosImpl(S);
6263   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
6264   assert(InsertPair.second && "Should insert a new key");
6265   return InsertPair.first->second;
6266 }
6267 
6268 /// Helper method to assign a range to V from metadata present in the IR.
6269 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6270   if (Instruction *I = dyn_cast<Instruction>(V))
6271     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6272       return getConstantRangeFromMetadata(*MD);
6273 
6274   return None;
6275 }
6276 
6277 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6278                                      SCEV::NoWrapFlags Flags) {
6279   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6280     AddRec->setNoWrapFlags(Flags);
6281     UnsignedRanges.erase(AddRec);
6282     SignedRanges.erase(AddRec);
6283   }
6284 }
6285 
6286 ConstantRange ScalarEvolution::
6287 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6288   const DataLayout &DL = getDataLayout();
6289 
6290   unsigned BitWidth = getTypeSizeInBits(U->getType());
6291   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6292 
6293   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6294   // use information about the trip count to improve our available range.  Note
6295   // that the trip count independent cases are already handled by known bits.
6296   // WARNING: The definition of recurrence used here is subtly different than
6297   // the one used by AddRec (and thus most of this file).  Step is allowed to
6298   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6299   // and other addrecs in the same loop (for non-affine addrecs).  The code
6300   // below intentionally handles the case where step is not loop invariant.
6301   auto *P = dyn_cast<PHINode>(U->getValue());
6302   if (!P)
6303     return FullSet;
6304 
6305   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6306   // even the values that are not available in these blocks may come from them,
6307   // and this leads to false-positive recurrence test.
6308   for (auto *Pred : predecessors(P->getParent()))
6309     if (!DT.isReachableFromEntry(Pred))
6310       return FullSet;
6311 
6312   BinaryOperator *BO;
6313   Value *Start, *Step;
6314   if (!matchSimpleRecurrence(P, BO, Start, Step))
6315     return FullSet;
6316 
6317   // If we found a recurrence in reachable code, we must be in a loop. Note
6318   // that BO might be in some subloop of L, and that's completely okay.
6319   auto *L = LI.getLoopFor(P->getParent());
6320   assert(L && L->getHeader() == P->getParent());
6321   if (!L->contains(BO->getParent()))
6322     // NOTE: This bailout should be an assert instead.  However, asserting
6323     // the condition here exposes a case where LoopFusion is querying SCEV
6324     // with malformed loop information during the midst of the transform.
6325     // There doesn't appear to be an obvious fix, so for the moment bailout
6326     // until the caller issue can be fixed.  PR49566 tracks the bug.
6327     return FullSet;
6328 
6329   // TODO: Extend to other opcodes such as mul, and div
6330   switch (BO->getOpcode()) {
6331   default:
6332     return FullSet;
6333   case Instruction::AShr:
6334   case Instruction::LShr:
6335   case Instruction::Shl:
6336     break;
6337   };
6338 
6339   if (BO->getOperand(0) != P)
6340     // TODO: Handle the power function forms some day.
6341     return FullSet;
6342 
6343   unsigned TC = getSmallConstantMaxTripCount(L);
6344   if (!TC || TC >= BitWidth)
6345     return FullSet;
6346 
6347   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6348   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6349   assert(KnownStart.getBitWidth() == BitWidth &&
6350          KnownStep.getBitWidth() == BitWidth);
6351 
6352   // Compute total shift amount, being careful of overflow and bitwidths.
6353   auto MaxShiftAmt = KnownStep.getMaxValue();
6354   APInt TCAP(BitWidth, TC-1);
6355   bool Overflow = false;
6356   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6357   if (Overflow)
6358     return FullSet;
6359 
6360   switch (BO->getOpcode()) {
6361   default:
6362     llvm_unreachable("filtered out above");
6363   case Instruction::AShr: {
6364     // For each ashr, three cases:
6365     //   shift = 0 => unchanged value
6366     //   saturation => 0 or -1
6367     //   other => a value closer to zero (of the same sign)
6368     // Thus, the end value is closer to zero than the start.
6369     auto KnownEnd = KnownBits::ashr(KnownStart,
6370                                     KnownBits::makeConstant(TotalShift));
6371     if (KnownStart.isNonNegative())
6372       // Analogous to lshr (simply not yet canonicalized)
6373       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6374                                         KnownStart.getMaxValue() + 1);
6375     if (KnownStart.isNegative())
6376       // End >=u Start && End <=s Start
6377       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6378                                         KnownEnd.getMaxValue() + 1);
6379     break;
6380   }
6381   case Instruction::LShr: {
6382     // For each lshr, three cases:
6383     //   shift = 0 => unchanged value
6384     //   saturation => 0
6385     //   other => a smaller positive number
6386     // Thus, the low end of the unsigned range is the last value produced.
6387     auto KnownEnd = KnownBits::lshr(KnownStart,
6388                                     KnownBits::makeConstant(TotalShift));
6389     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6390                                       KnownStart.getMaxValue() + 1);
6391   }
6392   case Instruction::Shl: {
6393     // Iff no bits are shifted out, value increases on every shift.
6394     auto KnownEnd = KnownBits::shl(KnownStart,
6395                                    KnownBits::makeConstant(TotalShift));
6396     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6397       return ConstantRange(KnownStart.getMinValue(),
6398                            KnownEnd.getMaxValue() + 1);
6399     break;
6400   }
6401   };
6402   return FullSet;
6403 }
6404 
6405 /// Determine the range for a particular SCEV.  If SignHint is
6406 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6407 /// with a "cleaner" unsigned (resp. signed) representation.
6408 const ConstantRange &
6409 ScalarEvolution::getRangeRef(const SCEV *S,
6410                              ScalarEvolution::RangeSignHint SignHint) {
6411   DenseMap<const SCEV *, ConstantRange> &Cache =
6412       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6413                                                        : SignedRanges;
6414   ConstantRange::PreferredRangeType RangeType =
6415       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6416           ? ConstantRange::Unsigned : ConstantRange::Signed;
6417 
6418   // See if we've computed this range already.
6419   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6420   if (I != Cache.end())
6421     return I->second;
6422 
6423   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6424     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6425 
6426   unsigned BitWidth = getTypeSizeInBits(S->getType());
6427   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6428   using OBO = OverflowingBinaryOperator;
6429 
6430   // If the value has known zeros, the maximum value will have those known zeros
6431   // as well.
6432   uint32_t TZ = GetMinTrailingZeros(S);
6433   if (TZ != 0) {
6434     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6435       ConservativeResult =
6436           ConstantRange(APInt::getMinValue(BitWidth),
6437                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6438     else
6439       ConservativeResult = ConstantRange(
6440           APInt::getSignedMinValue(BitWidth),
6441           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6442   }
6443 
6444   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6445     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6446     unsigned WrapType = OBO::AnyWrap;
6447     if (Add->hasNoSignedWrap())
6448       WrapType |= OBO::NoSignedWrap;
6449     if (Add->hasNoUnsignedWrap())
6450       WrapType |= OBO::NoUnsignedWrap;
6451     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6452       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6453                           WrapType, RangeType);
6454     return setRange(Add, SignHint,
6455                     ConservativeResult.intersectWith(X, RangeType));
6456   }
6457 
6458   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6459     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6460     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6461       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6462     return setRange(Mul, SignHint,
6463                     ConservativeResult.intersectWith(X, RangeType));
6464   }
6465 
6466   if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) {
6467     Intrinsic::ID ID;
6468     switch (S->getSCEVType()) {
6469     case scUMaxExpr:
6470       ID = Intrinsic::umax;
6471       break;
6472     case scSMaxExpr:
6473       ID = Intrinsic::smax;
6474       break;
6475     case scUMinExpr:
6476     case scSequentialUMinExpr:
6477       ID = Intrinsic::umin;
6478       break;
6479     case scSMinExpr:
6480       ID = Intrinsic::smin;
6481       break;
6482     default:
6483       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6484     }
6485 
6486     const auto *NAry = cast<SCEVNAryExpr>(S);
6487     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint);
6488     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6489       X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)});
6490     return setRange(S, SignHint,
6491                     ConservativeResult.intersectWith(X, RangeType));
6492   }
6493 
6494   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6495     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6496     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6497     return setRange(UDiv, SignHint,
6498                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6499   }
6500 
6501   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6502     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6503     return setRange(ZExt, SignHint,
6504                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6505                                                      RangeType));
6506   }
6507 
6508   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6509     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6510     return setRange(SExt, SignHint,
6511                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6512                                                      RangeType));
6513   }
6514 
6515   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6516     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6517     return setRange(PtrToInt, SignHint, X);
6518   }
6519 
6520   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6521     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6522     return setRange(Trunc, SignHint,
6523                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6524                                                      RangeType));
6525   }
6526 
6527   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6528     // If there's no unsigned wrap, the value will never be less than its
6529     // initial value.
6530     if (AddRec->hasNoUnsignedWrap()) {
6531       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6532       if (!UnsignedMinValue.isZero())
6533         ConservativeResult = ConservativeResult.intersectWith(
6534             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6535     }
6536 
6537     // If there's no signed wrap, and all the operands except initial value have
6538     // the same sign or zero, the value won't ever be:
6539     // 1: smaller than initial value if operands are non negative,
6540     // 2: bigger than initial value if operands are non positive.
6541     // For both cases, value can not cross signed min/max boundary.
6542     if (AddRec->hasNoSignedWrap()) {
6543       bool AllNonNeg = true;
6544       bool AllNonPos = true;
6545       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6546         if (!isKnownNonNegative(AddRec->getOperand(i)))
6547           AllNonNeg = false;
6548         if (!isKnownNonPositive(AddRec->getOperand(i)))
6549           AllNonPos = false;
6550       }
6551       if (AllNonNeg)
6552         ConservativeResult = ConservativeResult.intersectWith(
6553             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6554                                        APInt::getSignedMinValue(BitWidth)),
6555             RangeType);
6556       else if (AllNonPos)
6557         ConservativeResult = ConservativeResult.intersectWith(
6558             ConstantRange::getNonEmpty(
6559                 APInt::getSignedMinValue(BitWidth),
6560                 getSignedRangeMax(AddRec->getStart()) + 1),
6561             RangeType);
6562     }
6563 
6564     // TODO: non-affine addrec
6565     if (AddRec->isAffine()) {
6566       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6567       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6568           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6569         auto RangeFromAffine = getRangeForAffineAR(
6570             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6571             BitWidth);
6572         ConservativeResult =
6573             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6574 
6575         auto RangeFromFactoring = getRangeViaFactoring(
6576             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6577             BitWidth);
6578         ConservativeResult =
6579             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6580       }
6581 
6582       // Now try symbolic BE count and more powerful methods.
6583       if (UseExpensiveRangeSharpening) {
6584         const SCEV *SymbolicMaxBECount =
6585             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6586         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6587             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6588             AddRec->hasNoSelfWrap()) {
6589           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6590               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6591           ConservativeResult =
6592               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6593         }
6594       }
6595     }
6596 
6597     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6598   }
6599 
6600   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6601 
6602     // Check if the IR explicitly contains !range metadata.
6603     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6604     if (MDRange.hasValue())
6605       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6606                                                             RangeType);
6607 
6608     // Use facts about recurrences in the underlying IR.  Note that add
6609     // recurrences are AddRecExprs and thus don't hit this path.  This
6610     // primarily handles shift recurrences.
6611     auto CR = getRangeForUnknownRecurrence(U);
6612     ConservativeResult = ConservativeResult.intersectWith(CR);
6613 
6614     // See if ValueTracking can give us a useful range.
6615     const DataLayout &DL = getDataLayout();
6616     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6617     if (Known.getBitWidth() != BitWidth)
6618       Known = Known.zextOrTrunc(BitWidth);
6619 
6620     // ValueTracking may be able to compute a tighter result for the number of
6621     // sign bits than for the value of those sign bits.
6622     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6623     if (U->getType()->isPointerTy()) {
6624       // If the pointer size is larger than the index size type, this can cause
6625       // NS to be larger than BitWidth. So compensate for this.
6626       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6627       int ptrIdxDiff = ptrSize - BitWidth;
6628       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6629         NS -= ptrIdxDiff;
6630     }
6631 
6632     if (NS > 1) {
6633       // If we know any of the sign bits, we know all of the sign bits.
6634       if (!Known.Zero.getHiBits(NS).isZero())
6635         Known.Zero.setHighBits(NS);
6636       if (!Known.One.getHiBits(NS).isZero())
6637         Known.One.setHighBits(NS);
6638     }
6639 
6640     if (Known.getMinValue() != Known.getMaxValue() + 1)
6641       ConservativeResult = ConservativeResult.intersectWith(
6642           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6643           RangeType);
6644     if (NS > 1)
6645       ConservativeResult = ConservativeResult.intersectWith(
6646           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6647                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6648           RangeType);
6649 
6650     // A range of Phi is a subset of union of all ranges of its input.
6651     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6652       // Make sure that we do not run over cycled Phis.
6653       if (PendingPhiRanges.insert(Phi).second) {
6654         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6655         for (auto &Op : Phi->operands()) {
6656           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
6657           RangeFromOps = RangeFromOps.unionWith(OpRange);
6658           // No point to continue if we already have a full set.
6659           if (RangeFromOps.isFullSet())
6660             break;
6661         }
6662         ConservativeResult =
6663             ConservativeResult.intersectWith(RangeFromOps, RangeType);
6664         bool Erased = PendingPhiRanges.erase(Phi);
6665         assert(Erased && "Failed to erase Phi properly?");
6666         (void) Erased;
6667       }
6668     }
6669 
6670     return setRange(U, SignHint, std::move(ConservativeResult));
6671   }
6672 
6673   return setRange(S, SignHint, std::move(ConservativeResult));
6674 }
6675 
6676 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6677 // values that the expression can take. Initially, the expression has a value
6678 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6679 // argument defines if we treat Step as signed or unsigned.
6680 static ConstantRange getRangeForAffineARHelper(APInt Step,
6681                                                const ConstantRange &StartRange,
6682                                                const APInt &MaxBECount,
6683                                                unsigned BitWidth, bool Signed) {
6684   // If either Step or MaxBECount is 0, then the expression won't change, and we
6685   // just need to return the initial range.
6686   if (Step == 0 || MaxBECount == 0)
6687     return StartRange;
6688 
6689   // If we don't know anything about the initial value (i.e. StartRange is
6690   // FullRange), then we don't know anything about the final range either.
6691   // Return FullRange.
6692   if (StartRange.isFullSet())
6693     return ConstantRange::getFull(BitWidth);
6694 
6695   // If Step is signed and negative, then we use its absolute value, but we also
6696   // note that we're moving in the opposite direction.
6697   bool Descending = Signed && Step.isNegative();
6698 
6699   if (Signed)
6700     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6701     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6702     // This equations hold true due to the well-defined wrap-around behavior of
6703     // APInt.
6704     Step = Step.abs();
6705 
6706   // Check if Offset is more than full span of BitWidth. If it is, the
6707   // expression is guaranteed to overflow.
6708   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6709     return ConstantRange::getFull(BitWidth);
6710 
6711   // Offset is by how much the expression can change. Checks above guarantee no
6712   // overflow here.
6713   APInt Offset = Step * MaxBECount;
6714 
6715   // Minimum value of the final range will match the minimal value of StartRange
6716   // if the expression is increasing and will be decreased by Offset otherwise.
6717   // Maximum value of the final range will match the maximal value of StartRange
6718   // if the expression is decreasing and will be increased by Offset otherwise.
6719   APInt StartLower = StartRange.getLower();
6720   APInt StartUpper = StartRange.getUpper() - 1;
6721   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6722                                    : (StartUpper + std::move(Offset));
6723 
6724   // It's possible that the new minimum/maximum value will fall into the initial
6725   // range (due to wrap around). This means that the expression can take any
6726   // value in this bitwidth, and we have to return full range.
6727   if (StartRange.contains(MovedBoundary))
6728     return ConstantRange::getFull(BitWidth);
6729 
6730   APInt NewLower =
6731       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6732   APInt NewUpper =
6733       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6734   NewUpper += 1;
6735 
6736   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6737   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6738 }
6739 
6740 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6741                                                    const SCEV *Step,
6742                                                    const SCEV *MaxBECount,
6743                                                    unsigned BitWidth) {
6744   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6745          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6746          "Precondition!");
6747 
6748   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6749   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6750 
6751   // First, consider step signed.
6752   ConstantRange StartSRange = getSignedRange(Start);
6753   ConstantRange StepSRange = getSignedRange(Step);
6754 
6755   // If Step can be both positive and negative, we need to find ranges for the
6756   // maximum absolute step values in both directions and union them.
6757   ConstantRange SR =
6758       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6759                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6760   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6761                                               StartSRange, MaxBECountValue,
6762                                               BitWidth, /* Signed = */ true));
6763 
6764   // Next, consider step unsigned.
6765   ConstantRange UR = getRangeForAffineARHelper(
6766       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6767       MaxBECountValue, BitWidth, /* Signed = */ false);
6768 
6769   // Finally, intersect signed and unsigned ranges.
6770   return SR.intersectWith(UR, ConstantRange::Smallest);
6771 }
6772 
6773 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6774     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6775     ScalarEvolution::RangeSignHint SignHint) {
6776   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6777   assert(AddRec->hasNoSelfWrap() &&
6778          "This only works for non-self-wrapping AddRecs!");
6779   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6780   const SCEV *Step = AddRec->getStepRecurrence(*this);
6781   // Only deal with constant step to save compile time.
6782   if (!isa<SCEVConstant>(Step))
6783     return ConstantRange::getFull(BitWidth);
6784   // Let's make sure that we can prove that we do not self-wrap during
6785   // MaxBECount iterations. We need this because MaxBECount is a maximum
6786   // iteration count estimate, and we might infer nw from some exit for which we
6787   // do not know max exit count (or any other side reasoning).
6788   // TODO: Turn into assert at some point.
6789   if (getTypeSizeInBits(MaxBECount->getType()) >
6790       getTypeSizeInBits(AddRec->getType()))
6791     return ConstantRange::getFull(BitWidth);
6792   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6793   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6794   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6795   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6796   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6797                                          MaxItersWithoutWrap))
6798     return ConstantRange::getFull(BitWidth);
6799 
6800   ICmpInst::Predicate LEPred =
6801       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6802   ICmpInst::Predicate GEPred =
6803       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6804   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6805 
6806   // We know that there is no self-wrap. Let's take Start and End values and
6807   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6808   // the iteration. They either lie inside the range [Min(Start, End),
6809   // Max(Start, End)] or outside it:
6810   //
6811   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6812   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6813   //
6814   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6815   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6816   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6817   // Start <= End and step is positive, or Start >= End and step is negative.
6818   const SCEV *Start = AddRec->getStart();
6819   ConstantRange StartRange = getRangeRef(Start, SignHint);
6820   ConstantRange EndRange = getRangeRef(End, SignHint);
6821   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6822   // If they already cover full iteration space, we will know nothing useful
6823   // even if we prove what we want to prove.
6824   if (RangeBetween.isFullSet())
6825     return RangeBetween;
6826   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6827   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6828                                : RangeBetween.isWrappedSet();
6829   if (IsWrappedSet)
6830     return ConstantRange::getFull(BitWidth);
6831 
6832   if (isKnownPositive(Step) &&
6833       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6834     return RangeBetween;
6835   else if (isKnownNegative(Step) &&
6836            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6837     return RangeBetween;
6838   return ConstantRange::getFull(BitWidth);
6839 }
6840 
6841 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6842                                                     const SCEV *Step,
6843                                                     const SCEV *MaxBECount,
6844                                                     unsigned BitWidth) {
6845   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6846   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6847 
6848   struct SelectPattern {
6849     Value *Condition = nullptr;
6850     APInt TrueValue;
6851     APInt FalseValue;
6852 
6853     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6854                            const SCEV *S) {
6855       Optional<unsigned> CastOp;
6856       APInt Offset(BitWidth, 0);
6857 
6858       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6859              "Should be!");
6860 
6861       // Peel off a constant offset:
6862       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6863         // In the future we could consider being smarter here and handle
6864         // {Start+Step,+,Step} too.
6865         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6866           return;
6867 
6868         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6869         S = SA->getOperand(1);
6870       }
6871 
6872       // Peel off a cast operation
6873       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6874         CastOp = SCast->getSCEVType();
6875         S = SCast->getOperand();
6876       }
6877 
6878       using namespace llvm::PatternMatch;
6879 
6880       auto *SU = dyn_cast<SCEVUnknown>(S);
6881       const APInt *TrueVal, *FalseVal;
6882       if (!SU ||
6883           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6884                                           m_APInt(FalseVal)))) {
6885         Condition = nullptr;
6886         return;
6887       }
6888 
6889       TrueValue = *TrueVal;
6890       FalseValue = *FalseVal;
6891 
6892       // Re-apply the cast we peeled off earlier
6893       if (CastOp.hasValue())
6894         switch (*CastOp) {
6895         default:
6896           llvm_unreachable("Unknown SCEV cast type!");
6897 
6898         case scTruncate:
6899           TrueValue = TrueValue.trunc(BitWidth);
6900           FalseValue = FalseValue.trunc(BitWidth);
6901           break;
6902         case scZeroExtend:
6903           TrueValue = TrueValue.zext(BitWidth);
6904           FalseValue = FalseValue.zext(BitWidth);
6905           break;
6906         case scSignExtend:
6907           TrueValue = TrueValue.sext(BitWidth);
6908           FalseValue = FalseValue.sext(BitWidth);
6909           break;
6910         }
6911 
6912       // Re-apply the constant offset we peeled off earlier
6913       TrueValue += Offset;
6914       FalseValue += Offset;
6915     }
6916 
6917     bool isRecognized() { return Condition != nullptr; }
6918   };
6919 
6920   SelectPattern StartPattern(*this, BitWidth, Start);
6921   if (!StartPattern.isRecognized())
6922     return ConstantRange::getFull(BitWidth);
6923 
6924   SelectPattern StepPattern(*this, BitWidth, Step);
6925   if (!StepPattern.isRecognized())
6926     return ConstantRange::getFull(BitWidth);
6927 
6928   if (StartPattern.Condition != StepPattern.Condition) {
6929     // We don't handle this case today; but we could, by considering four
6930     // possibilities below instead of two. I'm not sure if there are cases where
6931     // that will help over what getRange already does, though.
6932     return ConstantRange::getFull(BitWidth);
6933   }
6934 
6935   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6936   // construct arbitrary general SCEV expressions here.  This function is called
6937   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6938   // say) can end up caching a suboptimal value.
6939 
6940   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6941   // C2352 and C2512 (otherwise it isn't needed).
6942 
6943   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6944   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6945   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6946   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6947 
6948   ConstantRange TrueRange =
6949       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6950   ConstantRange FalseRange =
6951       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6952 
6953   return TrueRange.unionWith(FalseRange);
6954 }
6955 
6956 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6957   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6958   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6959 
6960   // Return early if there are no flags to propagate to the SCEV.
6961   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6962   if (BinOp->hasNoUnsignedWrap())
6963     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6964   if (BinOp->hasNoSignedWrap())
6965     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6966   if (Flags == SCEV::FlagAnyWrap)
6967     return SCEV::FlagAnyWrap;
6968 
6969   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6970 }
6971 
6972 const Instruction *
6973 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6974   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6975     return &*AddRec->getLoop()->getHeader()->begin();
6976   if (auto *U = dyn_cast<SCEVUnknown>(S))
6977     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6978       return I;
6979   return nullptr;
6980 }
6981 
6982 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6983 /// \p Ops remains unmodified.
6984 static void collectUniqueOps(const SCEV *S,
6985                              SmallVectorImpl<const SCEV *> &Ops) {
6986   SmallPtrSet<const SCEV *, 4> Unique;
6987   auto InsertUnique = [&](const SCEV *S) {
6988     if (Unique.insert(S).second)
6989       Ops.push_back(S);
6990   };
6991   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6992     for (auto *Op : S2->operands())
6993       InsertUnique(Op);
6994   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6995     for (auto *Op : S2->operands())
6996       InsertUnique(Op);
6997   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6998     for (auto *Op : S2->operands())
6999       InsertUnique(Op);
7000 }
7001 
7002 const Instruction *
7003 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7004                                        bool &Precise) {
7005   Precise = true;
7006   // Do a bounded search of the def relation of the requested SCEVs.
7007   SmallSet<const SCEV *, 16> Visited;
7008   SmallVector<const SCEV *> Worklist;
7009   auto pushOp = [&](const SCEV *S) {
7010     if (!Visited.insert(S).second)
7011       return;
7012     // Threshold of 30 here is arbitrary.
7013     if (Visited.size() > 30) {
7014       Precise = false;
7015       return;
7016     }
7017     Worklist.push_back(S);
7018   };
7019 
7020   for (auto *S : Ops)
7021     pushOp(S);
7022 
7023   const Instruction *Bound = nullptr;
7024   while (!Worklist.empty()) {
7025     auto *S = Worklist.pop_back_val();
7026     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7027       if (!Bound || DT.dominates(Bound, DefI))
7028         Bound = DefI;
7029     } else {
7030       SmallVector<const SCEV *, 4> Ops;
7031       collectUniqueOps(S, Ops);
7032       for (auto *Op : Ops)
7033         pushOp(Op);
7034     }
7035   }
7036   return Bound ? Bound : &*F.getEntryBlock().begin();
7037 }
7038 
7039 const Instruction *
7040 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7041   bool Discard;
7042   return getDefiningScopeBound(Ops, Discard);
7043 }
7044 
7045 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7046                                                         const Instruction *B) {
7047   if (A->getParent() == B->getParent() &&
7048       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7049                                                  B->getIterator()))
7050     return true;
7051 
7052   auto *BLoop = LI.getLoopFor(B->getParent());
7053   if (BLoop && BLoop->getHeader() == B->getParent() &&
7054       BLoop->getLoopPreheader() == A->getParent() &&
7055       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7056                                                  A->getParent()->end()) &&
7057       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7058                                                  B->getIterator()))
7059     return true;
7060   return false;
7061 }
7062 
7063 
7064 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7065   // Only proceed if we can prove that I does not yield poison.
7066   if (!programUndefinedIfPoison(I))
7067     return false;
7068 
7069   // At this point we know that if I is executed, then it does not wrap
7070   // according to at least one of NSW or NUW. If I is not executed, then we do
7071   // not know if the calculation that I represents would wrap. Multiple
7072   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7073   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7074   // derived from other instructions that map to the same SCEV. We cannot make
7075   // that guarantee for cases where I is not executed. So we need to find a
7076   // upper bound on the defining scope for the SCEV, and prove that I is
7077   // executed every time we enter that scope.  When the bounding scope is a
7078   // loop (the common case), this is equivalent to proving I executes on every
7079   // iteration of that loop.
7080   SmallVector<const SCEV *> SCEVOps;
7081   for (const Use &Op : I->operands()) {
7082     // I could be an extractvalue from a call to an overflow intrinsic.
7083     // TODO: We can do better here in some cases.
7084     if (isSCEVable(Op->getType()))
7085       SCEVOps.push_back(getSCEV(Op));
7086   }
7087   auto *DefI = getDefiningScopeBound(SCEVOps);
7088   return isGuaranteedToTransferExecutionTo(DefI, I);
7089 }
7090 
7091 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7092   // If we know that \c I can never be poison period, then that's enough.
7093   if (isSCEVExprNeverPoison(I))
7094     return true;
7095 
7096   // For an add recurrence specifically, we assume that infinite loops without
7097   // side effects are undefined behavior, and then reason as follows:
7098   //
7099   // If the add recurrence is poison in any iteration, it is poison on all
7100   // future iterations (since incrementing poison yields poison). If the result
7101   // of the add recurrence is fed into the loop latch condition and the loop
7102   // does not contain any throws or exiting blocks other than the latch, we now
7103   // have the ability to "choose" whether the backedge is taken or not (by
7104   // choosing a sufficiently evil value for the poison feeding into the branch)
7105   // for every iteration including and after the one in which \p I first became
7106   // poison.  There are two possibilities (let's call the iteration in which \p
7107   // I first became poison as K):
7108   //
7109   //  1. In the set of iterations including and after K, the loop body executes
7110   //     no side effects.  In this case executing the backege an infinte number
7111   //     of times will yield undefined behavior.
7112   //
7113   //  2. In the set of iterations including and after K, the loop body executes
7114   //     at least one side effect.  In this case, that specific instance of side
7115   //     effect is control dependent on poison, which also yields undefined
7116   //     behavior.
7117 
7118   auto *ExitingBB = L->getExitingBlock();
7119   auto *LatchBB = L->getLoopLatch();
7120   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
7121     return false;
7122 
7123   SmallPtrSet<const Instruction *, 16> Pushed;
7124   SmallVector<const Instruction *, 8> PoisonStack;
7125 
7126   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7127   // things that are known to be poison under that assumption go on the
7128   // PoisonStack.
7129   Pushed.insert(I);
7130   PoisonStack.push_back(I);
7131 
7132   bool LatchControlDependentOnPoison = false;
7133   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
7134     const Instruction *Poison = PoisonStack.pop_back_val();
7135 
7136     for (auto *PoisonUser : Poison->users()) {
7137       if (propagatesPoison(cast<Operator>(PoisonUser))) {
7138         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
7139           PoisonStack.push_back(cast<Instruction>(PoisonUser));
7140       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
7141         assert(BI->isConditional() && "Only possibility!");
7142         if (BI->getParent() == LatchBB) {
7143           LatchControlDependentOnPoison = true;
7144           break;
7145         }
7146       }
7147     }
7148   }
7149 
7150   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
7151 }
7152 
7153 ScalarEvolution::LoopProperties
7154 ScalarEvolution::getLoopProperties(const Loop *L) {
7155   using LoopProperties = ScalarEvolution::LoopProperties;
7156 
7157   auto Itr = LoopPropertiesCache.find(L);
7158   if (Itr == LoopPropertiesCache.end()) {
7159     auto HasSideEffects = [](Instruction *I) {
7160       if (auto *SI = dyn_cast<StoreInst>(I))
7161         return !SI->isSimple();
7162 
7163       return I->mayThrow() || I->mayWriteToMemory();
7164     };
7165 
7166     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7167                          /*HasNoSideEffects*/ true};
7168 
7169     for (auto *BB : L->getBlocks())
7170       for (auto &I : *BB) {
7171         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7172           LP.HasNoAbnormalExits = false;
7173         if (HasSideEffects(&I))
7174           LP.HasNoSideEffects = false;
7175         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7176           break; // We're already as pessimistic as we can get.
7177       }
7178 
7179     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7180     assert(InsertPair.second && "We just checked!");
7181     Itr = InsertPair.first;
7182   }
7183 
7184   return Itr->second;
7185 }
7186 
7187 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7188   // A mustprogress loop without side effects must be finite.
7189   // TODO: The check used here is very conservative.  It's only *specific*
7190   // side effects which are well defined in infinite loops.
7191   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7192 }
7193 
7194 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7195   if (!isSCEVable(V->getType()))
7196     return getUnknown(V);
7197 
7198   if (Instruction *I = dyn_cast<Instruction>(V)) {
7199     // Don't attempt to analyze instructions in blocks that aren't
7200     // reachable. Such instructions don't matter, and they aren't required
7201     // to obey basic rules for definitions dominating uses which this
7202     // analysis depends on.
7203     if (!DT.isReachableFromEntry(I->getParent()))
7204       return getUnknown(UndefValue::get(V->getType()));
7205   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7206     return getConstant(CI);
7207   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
7208     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
7209   else if (!isa<ConstantExpr>(V))
7210     return getUnknown(V);
7211 
7212   const SCEV *LHS;
7213   const SCEV *RHS;
7214 
7215   Operator *U = cast<Operator>(V);
7216   if (auto BO = MatchBinaryOp(U, DT)) {
7217     switch (BO->Opcode) {
7218     case Instruction::Add: {
7219       // The simple thing to do would be to just call getSCEV on both operands
7220       // and call getAddExpr with the result. However if we're looking at a
7221       // bunch of things all added together, this can be quite inefficient,
7222       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7223       // Instead, gather up all the operands and make a single getAddExpr call.
7224       // LLVM IR canonical form means we need only traverse the left operands.
7225       SmallVector<const SCEV *, 4> AddOps;
7226       do {
7227         if (BO->Op) {
7228           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7229             AddOps.push_back(OpSCEV);
7230             break;
7231           }
7232 
7233           // If a NUW or NSW flag can be applied to the SCEV for this
7234           // addition, then compute the SCEV for this addition by itself
7235           // with a separate call to getAddExpr. We need to do that
7236           // instead of pushing the operands of the addition onto AddOps,
7237           // since the flags are only known to apply to this particular
7238           // addition - they may not apply to other additions that can be
7239           // formed with operands from AddOps.
7240           const SCEV *RHS = getSCEV(BO->RHS);
7241           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7242           if (Flags != SCEV::FlagAnyWrap) {
7243             const SCEV *LHS = getSCEV(BO->LHS);
7244             if (BO->Opcode == Instruction::Sub)
7245               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7246             else
7247               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7248             break;
7249           }
7250         }
7251 
7252         if (BO->Opcode == Instruction::Sub)
7253           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7254         else
7255           AddOps.push_back(getSCEV(BO->RHS));
7256 
7257         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7258         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7259                        NewBO->Opcode != Instruction::Sub)) {
7260           AddOps.push_back(getSCEV(BO->LHS));
7261           break;
7262         }
7263         BO = NewBO;
7264       } while (true);
7265 
7266       return getAddExpr(AddOps);
7267     }
7268 
7269     case Instruction::Mul: {
7270       SmallVector<const SCEV *, 4> MulOps;
7271       do {
7272         if (BO->Op) {
7273           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7274             MulOps.push_back(OpSCEV);
7275             break;
7276           }
7277 
7278           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7279           if (Flags != SCEV::FlagAnyWrap) {
7280             LHS = getSCEV(BO->LHS);
7281             RHS = getSCEV(BO->RHS);
7282             MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7283             break;
7284           }
7285         }
7286 
7287         MulOps.push_back(getSCEV(BO->RHS));
7288         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7289         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7290           MulOps.push_back(getSCEV(BO->LHS));
7291           break;
7292         }
7293         BO = NewBO;
7294       } while (true);
7295 
7296       return getMulExpr(MulOps);
7297     }
7298     case Instruction::UDiv:
7299       LHS = getSCEV(BO->LHS);
7300       RHS = getSCEV(BO->RHS);
7301       return getUDivExpr(LHS, RHS);
7302     case Instruction::URem:
7303       LHS = getSCEV(BO->LHS);
7304       RHS = getSCEV(BO->RHS);
7305       return getURemExpr(LHS, RHS);
7306     case Instruction::Sub: {
7307       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7308       if (BO->Op)
7309         Flags = getNoWrapFlagsFromUB(BO->Op);
7310       LHS = getSCEV(BO->LHS);
7311       RHS = getSCEV(BO->RHS);
7312       return getMinusSCEV(LHS, RHS, Flags);
7313     }
7314     case Instruction::And:
7315       // For an expression like x&255 that merely masks off the high bits,
7316       // use zext(trunc(x)) as the SCEV expression.
7317       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7318         if (CI->isZero())
7319           return getSCEV(BO->RHS);
7320         if (CI->isMinusOne())
7321           return getSCEV(BO->LHS);
7322         const APInt &A = CI->getValue();
7323 
7324         // Instcombine's ShrinkDemandedConstant may strip bits out of
7325         // constants, obscuring what would otherwise be a low-bits mask.
7326         // Use computeKnownBits to compute what ShrinkDemandedConstant
7327         // knew about to reconstruct a low-bits mask value.
7328         unsigned LZ = A.countLeadingZeros();
7329         unsigned TZ = A.countTrailingZeros();
7330         unsigned BitWidth = A.getBitWidth();
7331         KnownBits Known(BitWidth);
7332         computeKnownBits(BO->LHS, Known, getDataLayout(),
7333                          0, &AC, nullptr, &DT);
7334 
7335         APInt EffectiveMask =
7336             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7337         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7338           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7339           const SCEV *LHS = getSCEV(BO->LHS);
7340           const SCEV *ShiftedLHS = nullptr;
7341           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7342             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7343               // For an expression like (x * 8) & 8, simplify the multiply.
7344               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
7345               unsigned GCD = std::min(MulZeros, TZ);
7346               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7347               SmallVector<const SCEV*, 4> MulOps;
7348               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7349               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
7350               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7351               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7352             }
7353           }
7354           if (!ShiftedLHS)
7355             ShiftedLHS = getUDivExpr(LHS, MulCount);
7356           return getMulExpr(
7357               getZeroExtendExpr(
7358                   getTruncateExpr(ShiftedLHS,
7359                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7360                   BO->LHS->getType()),
7361               MulCount);
7362         }
7363       }
7364       // Binary `and` is a bit-wise `umin`.
7365       if (BO->LHS->getType()->isIntegerTy(1)) {
7366         LHS = getSCEV(BO->LHS);
7367         RHS = getSCEV(BO->RHS);
7368         return getUMinExpr(LHS, RHS);
7369       }
7370       break;
7371 
7372     case Instruction::Or:
7373       // If the RHS of the Or is a constant, we may have something like:
7374       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
7375       // optimizations will transparently handle this case.
7376       //
7377       // In order for this transformation to be safe, the LHS must be of the
7378       // form X*(2^n) and the Or constant must be less than 2^n.
7379       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7380         const SCEV *LHS = getSCEV(BO->LHS);
7381         const APInt &CIVal = CI->getValue();
7382         if (GetMinTrailingZeros(LHS) >=
7383             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
7384           // Build a plain add SCEV.
7385           return getAddExpr(LHS, getSCEV(CI),
7386                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
7387         }
7388       }
7389       // Binary `or` is a bit-wise `umax`.
7390       if (BO->LHS->getType()->isIntegerTy(1)) {
7391         LHS = getSCEV(BO->LHS);
7392         RHS = getSCEV(BO->RHS);
7393         return getUMaxExpr(LHS, RHS);
7394       }
7395       break;
7396 
7397     case Instruction::Xor:
7398       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7399         // If the RHS of xor is -1, then this is a not operation.
7400         if (CI->isMinusOne())
7401           return getNotSCEV(getSCEV(BO->LHS));
7402 
7403         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7404         // This is a variant of the check for xor with -1, and it handles
7405         // the case where instcombine has trimmed non-demanded bits out
7406         // of an xor with -1.
7407         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7408           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7409             if (LBO->getOpcode() == Instruction::And &&
7410                 LCI->getValue() == CI->getValue())
7411               if (const SCEVZeroExtendExpr *Z =
7412                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7413                 Type *UTy = BO->LHS->getType();
7414                 const SCEV *Z0 = Z->getOperand();
7415                 Type *Z0Ty = Z0->getType();
7416                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7417 
7418                 // If C is a low-bits mask, the zero extend is serving to
7419                 // mask off the high bits. Complement the operand and
7420                 // re-apply the zext.
7421                 if (CI->getValue().isMask(Z0TySize))
7422                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7423 
7424                 // If C is a single bit, it may be in the sign-bit position
7425                 // before the zero-extend. In this case, represent the xor
7426                 // using an add, which is equivalent, and re-apply the zext.
7427                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7428                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7429                     Trunc.isSignMask())
7430                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7431                                            UTy);
7432               }
7433       }
7434       break;
7435 
7436     case Instruction::Shl:
7437       // Turn shift left of a constant amount into a multiply.
7438       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7439         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7440 
7441         // If the shift count is not less than the bitwidth, the result of
7442         // the shift is undefined. Don't try to analyze it, because the
7443         // resolution chosen here may differ from the resolution chosen in
7444         // other parts of the compiler.
7445         if (SA->getValue().uge(BitWidth))
7446           break;
7447 
7448         // We can safely preserve the nuw flag in all cases. It's also safe to
7449         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7450         // requires special handling. It can be preserved as long as we're not
7451         // left shifting by bitwidth - 1.
7452         auto Flags = SCEV::FlagAnyWrap;
7453         if (BO->Op) {
7454           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7455           if ((MulFlags & SCEV::FlagNSW) &&
7456               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7457             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7458           if (MulFlags & SCEV::FlagNUW)
7459             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7460         }
7461 
7462         ConstantInt *X = ConstantInt::get(
7463             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7464         return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7465       }
7466       break;
7467 
7468     case Instruction::AShr: {
7469       // AShr X, C, where C is a constant.
7470       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7471       if (!CI)
7472         break;
7473 
7474       Type *OuterTy = BO->LHS->getType();
7475       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7476       // If the shift count is not less than the bitwidth, the result of
7477       // the shift is undefined. Don't try to analyze it, because the
7478       // resolution chosen here may differ from the resolution chosen in
7479       // other parts of the compiler.
7480       if (CI->getValue().uge(BitWidth))
7481         break;
7482 
7483       if (CI->isZero())
7484         return getSCEV(BO->LHS); // shift by zero --> noop
7485 
7486       uint64_t AShrAmt = CI->getZExtValue();
7487       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7488 
7489       Operator *L = dyn_cast<Operator>(BO->LHS);
7490       if (L && L->getOpcode() == Instruction::Shl) {
7491         // X = Shl A, n
7492         // Y = AShr X, m
7493         // Both n and m are constant.
7494 
7495         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7496         if (L->getOperand(1) == BO->RHS)
7497           // For a two-shift sext-inreg, i.e. n = m,
7498           // use sext(trunc(x)) as the SCEV expression.
7499           return getSignExtendExpr(
7500               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7501 
7502         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7503         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7504           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7505           if (ShlAmt > AShrAmt) {
7506             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7507             // expression. We already checked that ShlAmt < BitWidth, so
7508             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7509             // ShlAmt - AShrAmt < Amt.
7510             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7511                                             ShlAmt - AShrAmt);
7512             return getSignExtendExpr(
7513                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7514                 getConstant(Mul)), OuterTy);
7515           }
7516         }
7517       }
7518       break;
7519     }
7520     }
7521   }
7522 
7523   switch (U->getOpcode()) {
7524   case Instruction::Trunc:
7525     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7526 
7527   case Instruction::ZExt:
7528     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7529 
7530   case Instruction::SExt:
7531     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7532       // The NSW flag of a subtract does not always survive the conversion to
7533       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7534       // more likely to preserve NSW and allow later AddRec optimisations.
7535       //
7536       // NOTE: This is effectively duplicating this logic from getSignExtend:
7537       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7538       // but by that point the NSW information has potentially been lost.
7539       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7540         Type *Ty = U->getType();
7541         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7542         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7543         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7544       }
7545     }
7546     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7547 
7548   case Instruction::BitCast:
7549     // BitCasts are no-op casts so we just eliminate the cast.
7550     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7551       return getSCEV(U->getOperand(0));
7552     break;
7553 
7554   case Instruction::PtrToInt: {
7555     // Pointer to integer cast is straight-forward, so do model it.
7556     const SCEV *Op = getSCEV(U->getOperand(0));
7557     Type *DstIntTy = U->getType();
7558     // But only if effective SCEV (integer) type is wide enough to represent
7559     // all possible pointer values.
7560     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7561     if (isa<SCEVCouldNotCompute>(IntOp))
7562       return getUnknown(V);
7563     return IntOp;
7564   }
7565   case Instruction::IntToPtr:
7566     // Just don't deal with inttoptr casts.
7567     return getUnknown(V);
7568 
7569   case Instruction::SDiv:
7570     // If both operands are non-negative, this is just an udiv.
7571     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7572         isKnownNonNegative(getSCEV(U->getOperand(1))))
7573       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7574     break;
7575 
7576   case Instruction::SRem:
7577     // If both operands are non-negative, this is just an urem.
7578     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7579         isKnownNonNegative(getSCEV(U->getOperand(1))))
7580       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7581     break;
7582 
7583   case Instruction::GetElementPtr:
7584     return createNodeForGEP(cast<GEPOperator>(U));
7585 
7586   case Instruction::PHI:
7587     return createNodeForPHI(cast<PHINode>(U));
7588 
7589   case Instruction::Select:
7590     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
7591                                     U->getOperand(2));
7592 
7593   case Instruction::Call:
7594   case Instruction::Invoke:
7595     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7596       return getSCEV(RV);
7597 
7598     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7599       switch (II->getIntrinsicID()) {
7600       case Intrinsic::abs:
7601         return getAbsExpr(
7602             getSCEV(II->getArgOperand(0)),
7603             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7604       case Intrinsic::umax:
7605         LHS = getSCEV(II->getArgOperand(0));
7606         RHS = getSCEV(II->getArgOperand(1));
7607         return getUMaxExpr(LHS, RHS);
7608       case Intrinsic::umin:
7609         LHS = getSCEV(II->getArgOperand(0));
7610         RHS = getSCEV(II->getArgOperand(1));
7611         return getUMinExpr(LHS, RHS);
7612       case Intrinsic::smax:
7613         LHS = getSCEV(II->getArgOperand(0));
7614         RHS = getSCEV(II->getArgOperand(1));
7615         return getSMaxExpr(LHS, RHS);
7616       case Intrinsic::smin:
7617         LHS = getSCEV(II->getArgOperand(0));
7618         RHS = getSCEV(II->getArgOperand(1));
7619         return getSMinExpr(LHS, RHS);
7620       case Intrinsic::usub_sat: {
7621         const SCEV *X = getSCEV(II->getArgOperand(0));
7622         const SCEV *Y = getSCEV(II->getArgOperand(1));
7623         const SCEV *ClampedY = getUMinExpr(X, Y);
7624         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7625       }
7626       case Intrinsic::uadd_sat: {
7627         const SCEV *X = getSCEV(II->getArgOperand(0));
7628         const SCEV *Y = getSCEV(II->getArgOperand(1));
7629         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7630         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7631       }
7632       case Intrinsic::start_loop_iterations:
7633         // A start_loop_iterations is just equivalent to the first operand for
7634         // SCEV purposes.
7635         return getSCEV(II->getArgOperand(0));
7636       default:
7637         break;
7638       }
7639     }
7640     break;
7641   }
7642 
7643   return getUnknown(V);
7644 }
7645 
7646 //===----------------------------------------------------------------------===//
7647 //                   Iteration Count Computation Code
7648 //
7649 
7650 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7651                                                        bool Extend) {
7652   if (isa<SCEVCouldNotCompute>(ExitCount))
7653     return getCouldNotCompute();
7654 
7655   auto *ExitCountType = ExitCount->getType();
7656   assert(ExitCountType->isIntegerTy());
7657 
7658   if (!Extend)
7659     return getAddExpr(ExitCount, getOne(ExitCountType));
7660 
7661   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7662                                     1 + ExitCountType->getScalarSizeInBits());
7663   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7664                     getOne(WiderType));
7665 }
7666 
7667 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7668   if (!ExitCount)
7669     return 0;
7670 
7671   ConstantInt *ExitConst = ExitCount->getValue();
7672 
7673   // Guard against huge trip counts.
7674   if (ExitConst->getValue().getActiveBits() > 32)
7675     return 0;
7676 
7677   // In case of integer overflow, this returns 0, which is correct.
7678   return ((unsigned)ExitConst->getZExtValue()) + 1;
7679 }
7680 
7681 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7682   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7683   return getConstantTripCount(ExitCount);
7684 }
7685 
7686 unsigned
7687 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7688                                            const BasicBlock *ExitingBlock) {
7689   assert(ExitingBlock && "Must pass a non-null exiting block!");
7690   assert(L->isLoopExiting(ExitingBlock) &&
7691          "Exiting block must actually branch out of the loop!");
7692   const SCEVConstant *ExitCount =
7693       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7694   return getConstantTripCount(ExitCount);
7695 }
7696 
7697 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7698   const auto *MaxExitCount =
7699       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7700   return getConstantTripCount(MaxExitCount);
7701 }
7702 
7703 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7704   // We can't infer from Array in Irregular Loop.
7705   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7706   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7707     return getCouldNotCompute();
7708 
7709   // FIXME: To make the scene more typical, we only analysis loops that have
7710   // one exiting block and that block must be the latch. To make it easier to
7711   // capture loops that have memory access and memory access will be executed
7712   // in each iteration.
7713   const BasicBlock *LoopLatch = L->getLoopLatch();
7714   assert(LoopLatch && "See defination of simplify form loop.");
7715   if (L->getExitingBlock() != LoopLatch)
7716     return getCouldNotCompute();
7717 
7718   const DataLayout &DL = getDataLayout();
7719   SmallVector<const SCEV *> InferCountColl;
7720   for (auto *BB : L->getBlocks()) {
7721     // Go here, we can know that Loop is a single exiting and simplified form
7722     // loop. Make sure that infer from Memory Operation in those BBs must be
7723     // executed in loop. First step, we can make sure that max execution time
7724     // of MemAccessBB in loop represents latch max excution time.
7725     // If MemAccessBB does not dom Latch, skip.
7726     //            Entry
7727     //              │
7728     //        ┌─────▼─────┐
7729     //        │Loop Header◄─────┐
7730     //        └──┬──────┬─┘     │
7731     //           │      │       │
7732     //  ┌────────▼──┐ ┌─▼─────┐ │
7733     //  │MemAccessBB│ │OtherBB│ │
7734     //  └────────┬──┘ └─┬─────┘ │
7735     //           │      │       │
7736     //         ┌─▼──────▼─┐     │
7737     //         │Loop Latch├─────┘
7738     //         └────┬─────┘
7739     //              ▼
7740     //             Exit
7741     if (!DT.dominates(BB, LoopLatch))
7742       continue;
7743 
7744     for (Instruction &Inst : *BB) {
7745       // Find Memory Operation Instruction.
7746       auto *GEP = getLoadStorePointerOperand(&Inst);
7747       if (!GEP)
7748         continue;
7749 
7750       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7751       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7752       if (!ElemSize)
7753         continue;
7754 
7755       // Use a existing polynomial recurrence on the trip count.
7756       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7757       if (!AddRec)
7758         continue;
7759       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7760       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7761       if (!ArrBase || !Step)
7762         continue;
7763       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7764 
7765       // Only handle { %array + step },
7766       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7767       if (AddRec->getStart() != ArrBase)
7768         continue;
7769 
7770       // Memory operation pattern which have gaps.
7771       // Or repeat memory opreation.
7772       // And index of GEP wraps arround.
7773       if (Step->getAPInt().getActiveBits() > 32 ||
7774           Step->getAPInt().getZExtValue() !=
7775               ElemSize->getAPInt().getZExtValue() ||
7776           Step->isZero() || Step->getAPInt().isNegative())
7777         continue;
7778 
7779       // Only infer from stack array which has certain size.
7780       // Make sure alloca instruction is not excuted in loop.
7781       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7782       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7783         continue;
7784 
7785       // Make sure only handle normal array.
7786       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7787       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7788       if (!Ty || !ArrSize || !ArrSize->isOne())
7789         continue;
7790 
7791       // FIXME: Since gep indices are silently zext to the indexing type,
7792       // we will have a narrow gep index which wraps around rather than
7793       // increasing strictly, we shoule ensure that step is increasing
7794       // strictly by the loop iteration.
7795       // Now we can infer a max execution time by MemLength/StepLength.
7796       const SCEV *MemSize =
7797           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7798       auto *MaxExeCount =
7799           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7800       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7801         continue;
7802 
7803       // If the loop reaches the maximum number of executions, we can not
7804       // access bytes starting outside the statically allocated size without
7805       // being immediate UB. But it is allowed to enter loop header one more
7806       // time.
7807       auto *InferCount = dyn_cast<SCEVConstant>(
7808           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7809       // Discard the maximum number of execution times under 32bits.
7810       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7811         continue;
7812 
7813       InferCountColl.push_back(InferCount);
7814     }
7815   }
7816 
7817   if (InferCountColl.size() == 0)
7818     return getCouldNotCompute();
7819 
7820   return getUMinFromMismatchedTypes(InferCountColl);
7821 }
7822 
7823 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7824   SmallVector<BasicBlock *, 8> ExitingBlocks;
7825   L->getExitingBlocks(ExitingBlocks);
7826 
7827   Optional<unsigned> Res = None;
7828   for (auto *ExitingBB : ExitingBlocks) {
7829     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7830     if (!Res)
7831       Res = Multiple;
7832     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7833   }
7834   return Res.getValueOr(1);
7835 }
7836 
7837 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7838                                                        const SCEV *ExitCount) {
7839   if (ExitCount == getCouldNotCompute())
7840     return 1;
7841 
7842   // Get the trip count
7843   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7844 
7845   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7846   if (!TC)
7847     // Attempt to factor more general cases. Returns the greatest power of
7848     // two divisor. If overflow happens, the trip count expression is still
7849     // divisible by the greatest power of 2 divisor returned.
7850     return 1U << std::min((uint32_t)31,
7851                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7852 
7853   ConstantInt *Result = TC->getValue();
7854 
7855   // Guard against huge trip counts (this requires checking
7856   // for zero to handle the case where the trip count == -1 and the
7857   // addition wraps).
7858   if (!Result || Result->getValue().getActiveBits() > 32 ||
7859       Result->getValue().getActiveBits() == 0)
7860     return 1;
7861 
7862   return (unsigned)Result->getZExtValue();
7863 }
7864 
7865 /// Returns the largest constant divisor of the trip count of this loop as a
7866 /// normal unsigned value, if possible. This means that the actual trip count is
7867 /// always a multiple of the returned value (don't forget the trip count could
7868 /// very well be zero as well!).
7869 ///
7870 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7871 /// multiple of a constant (which is also the case if the trip count is simply
7872 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7873 /// if the trip count is very large (>= 2^32).
7874 ///
7875 /// As explained in the comments for getSmallConstantTripCount, this assumes
7876 /// that control exits the loop via ExitingBlock.
7877 unsigned
7878 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7879                                               const BasicBlock *ExitingBlock) {
7880   assert(ExitingBlock && "Must pass a non-null exiting block!");
7881   assert(L->isLoopExiting(ExitingBlock) &&
7882          "Exiting block must actually branch out of the loop!");
7883   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7884   return getSmallConstantTripMultiple(L, ExitCount);
7885 }
7886 
7887 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7888                                           const BasicBlock *ExitingBlock,
7889                                           ExitCountKind Kind) {
7890   switch (Kind) {
7891   case Exact:
7892   case SymbolicMaximum:
7893     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7894   case ConstantMaximum:
7895     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7896   };
7897   llvm_unreachable("Invalid ExitCountKind!");
7898 }
7899 
7900 const SCEV *
7901 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7902                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
7903   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7904 }
7905 
7906 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7907                                                    ExitCountKind Kind) {
7908   switch (Kind) {
7909   case Exact:
7910     return getBackedgeTakenInfo(L).getExact(L, this);
7911   case ConstantMaximum:
7912     return getBackedgeTakenInfo(L).getConstantMax(this);
7913   case SymbolicMaximum:
7914     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7915   };
7916   llvm_unreachable("Invalid ExitCountKind!");
7917 }
7918 
7919 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7920   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7921 }
7922 
7923 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7924 static void PushLoopPHIs(const Loop *L,
7925                          SmallVectorImpl<Instruction *> &Worklist,
7926                          SmallPtrSetImpl<Instruction *> &Visited) {
7927   BasicBlock *Header = L->getHeader();
7928 
7929   // Push all Loop-header PHIs onto the Worklist stack.
7930   for (PHINode &PN : Header->phis())
7931     if (Visited.insert(&PN).second)
7932       Worklist.push_back(&PN);
7933 }
7934 
7935 const ScalarEvolution::BackedgeTakenInfo &
7936 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7937   auto &BTI = getBackedgeTakenInfo(L);
7938   if (BTI.hasFullInfo())
7939     return BTI;
7940 
7941   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7942 
7943   if (!Pair.second)
7944     return Pair.first->second;
7945 
7946   BackedgeTakenInfo Result =
7947       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7948 
7949   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7950 }
7951 
7952 ScalarEvolution::BackedgeTakenInfo &
7953 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7954   // Initially insert an invalid entry for this loop. If the insertion
7955   // succeeds, proceed to actually compute a backedge-taken count and
7956   // update the value. The temporary CouldNotCompute value tells SCEV
7957   // code elsewhere that it shouldn't attempt to request a new
7958   // backedge-taken count, which could result in infinite recursion.
7959   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7960       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7961   if (!Pair.second)
7962     return Pair.first->second;
7963 
7964   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7965   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7966   // must be cleared in this scope.
7967   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7968 
7969   // In product build, there are no usage of statistic.
7970   (void)NumTripCountsComputed;
7971   (void)NumTripCountsNotComputed;
7972 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7973   const SCEV *BEExact = Result.getExact(L, this);
7974   if (BEExact != getCouldNotCompute()) {
7975     assert(isLoopInvariant(BEExact, L) &&
7976            isLoopInvariant(Result.getConstantMax(this), L) &&
7977            "Computed backedge-taken count isn't loop invariant for loop!");
7978     ++NumTripCountsComputed;
7979   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7980              isa<PHINode>(L->getHeader()->begin())) {
7981     // Only count loops that have phi nodes as not being computable.
7982     ++NumTripCountsNotComputed;
7983   }
7984 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7985 
7986   // Now that we know more about the trip count for this loop, forget any
7987   // existing SCEV values for PHI nodes in this loop since they are only
7988   // conservative estimates made without the benefit of trip count
7989   // information. This invalidation is not necessary for correctness, and is
7990   // only done to produce more precise results.
7991   if (Result.hasAnyInfo()) {
7992     // Invalidate any expression using an addrec in this loop.
7993     SmallVector<const SCEV *, 8> ToForget;
7994     auto LoopUsersIt = LoopUsers.find(L);
7995     if (LoopUsersIt != LoopUsers.end())
7996       append_range(ToForget, LoopUsersIt->second);
7997     forgetMemoizedResults(ToForget);
7998 
7999     // Invalidate constant-evolved loop header phis.
8000     for (PHINode &PN : L->getHeader()->phis())
8001       ConstantEvolutionLoopExitValue.erase(&PN);
8002   }
8003 
8004   // Re-lookup the insert position, since the call to
8005   // computeBackedgeTakenCount above could result in a
8006   // recusive call to getBackedgeTakenInfo (on a different
8007   // loop), which would invalidate the iterator computed
8008   // earlier.
8009   return BackedgeTakenCounts.find(L)->second = std::move(Result);
8010 }
8011 
8012 void ScalarEvolution::forgetAllLoops() {
8013   // This method is intended to forget all info about loops. It should
8014   // invalidate caches as if the following happened:
8015   // - The trip counts of all loops have changed arbitrarily
8016   // - Every llvm::Value has been updated in place to produce a different
8017   // result.
8018   BackedgeTakenCounts.clear();
8019   PredicatedBackedgeTakenCounts.clear();
8020   BECountUsers.clear();
8021   LoopPropertiesCache.clear();
8022   ConstantEvolutionLoopExitValue.clear();
8023   ValueExprMap.clear();
8024   ValuesAtScopes.clear();
8025   ValuesAtScopesUsers.clear();
8026   LoopDispositions.clear();
8027   BlockDispositions.clear();
8028   UnsignedRanges.clear();
8029   SignedRanges.clear();
8030   ExprValueMap.clear();
8031   HasRecMap.clear();
8032   MinTrailingZerosCache.clear();
8033   PredicatedSCEVRewrites.clear();
8034 }
8035 
8036 void ScalarEvolution::forgetLoop(const Loop *L) {
8037   SmallVector<const Loop *, 16> LoopWorklist(1, L);
8038   SmallVector<Instruction *, 32> Worklist;
8039   SmallPtrSet<Instruction *, 16> Visited;
8040   SmallVector<const SCEV *, 16> ToForget;
8041 
8042   // Iterate over all the loops and sub-loops to drop SCEV information.
8043   while (!LoopWorklist.empty()) {
8044     auto *CurrL = LoopWorklist.pop_back_val();
8045 
8046     // Drop any stored trip count value.
8047     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8048     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8049 
8050     // Drop information about predicated SCEV rewrites for this loop.
8051     for (auto I = PredicatedSCEVRewrites.begin();
8052          I != PredicatedSCEVRewrites.end();) {
8053       std::pair<const SCEV *, const Loop *> Entry = I->first;
8054       if (Entry.second == CurrL)
8055         PredicatedSCEVRewrites.erase(I++);
8056       else
8057         ++I;
8058     }
8059 
8060     auto LoopUsersItr = LoopUsers.find(CurrL);
8061     if (LoopUsersItr != LoopUsers.end()) {
8062       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8063                 LoopUsersItr->second.end());
8064     }
8065 
8066     // Drop information about expressions based on loop-header PHIs.
8067     PushLoopPHIs(CurrL, Worklist, Visited);
8068 
8069     while (!Worklist.empty()) {
8070       Instruction *I = Worklist.pop_back_val();
8071 
8072       ValueExprMapType::iterator It =
8073           ValueExprMap.find_as(static_cast<Value *>(I));
8074       if (It != ValueExprMap.end()) {
8075         eraseValueFromMap(It->first);
8076         ToForget.push_back(It->second);
8077         if (PHINode *PN = dyn_cast<PHINode>(I))
8078           ConstantEvolutionLoopExitValue.erase(PN);
8079       }
8080 
8081       PushDefUseChildren(I, Worklist, Visited);
8082     }
8083 
8084     LoopPropertiesCache.erase(CurrL);
8085     // Forget all contained loops too, to avoid dangling entries in the
8086     // ValuesAtScopes map.
8087     LoopWorklist.append(CurrL->begin(), CurrL->end());
8088   }
8089   forgetMemoizedResults(ToForget);
8090 }
8091 
8092 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8093   while (Loop *Parent = L->getParentLoop())
8094     L = Parent;
8095   forgetLoop(L);
8096 }
8097 
8098 void ScalarEvolution::forgetValue(Value *V) {
8099   Instruction *I = dyn_cast<Instruction>(V);
8100   if (!I) return;
8101 
8102   // Drop information about expressions based on loop-header PHIs.
8103   SmallVector<Instruction *, 16> Worklist;
8104   SmallPtrSet<Instruction *, 8> Visited;
8105   SmallVector<const SCEV *, 8> ToForget;
8106   Worklist.push_back(I);
8107   Visited.insert(I);
8108 
8109   while (!Worklist.empty()) {
8110     I = Worklist.pop_back_val();
8111     ValueExprMapType::iterator It =
8112       ValueExprMap.find_as(static_cast<Value *>(I));
8113     if (It != ValueExprMap.end()) {
8114       eraseValueFromMap(It->first);
8115       ToForget.push_back(It->second);
8116       if (PHINode *PN = dyn_cast<PHINode>(I))
8117         ConstantEvolutionLoopExitValue.erase(PN);
8118     }
8119 
8120     PushDefUseChildren(I, Worklist, Visited);
8121   }
8122   forgetMemoizedResults(ToForget);
8123 }
8124 
8125 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
8126   LoopDispositions.clear();
8127 }
8128 
8129 /// Get the exact loop backedge taken count considering all loop exits. A
8130 /// computable result can only be returned for loops with all exiting blocks
8131 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8132 /// is never skipped. This is a valid assumption as long as the loop exits via
8133 /// that test. For precise results, it is the caller's responsibility to specify
8134 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8135 const SCEV *
8136 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8137                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8138   // If any exits were not computable, the loop is not computable.
8139   if (!isComplete() || ExitNotTaken.empty())
8140     return SE->getCouldNotCompute();
8141 
8142   const BasicBlock *Latch = L->getLoopLatch();
8143   // All exiting blocks we have collected must dominate the only backedge.
8144   if (!Latch)
8145     return SE->getCouldNotCompute();
8146 
8147   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8148   // count is simply a minimum out of all these calculated exit counts.
8149   SmallVector<const SCEV *, 2> Ops;
8150   for (auto &ENT : ExitNotTaken) {
8151     const SCEV *BECount = ENT.ExactNotTaken;
8152     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8153     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8154            "We should only have known counts for exiting blocks that dominate "
8155            "latch!");
8156 
8157     Ops.push_back(BECount);
8158 
8159     if (Preds)
8160       for (auto *P : ENT.Predicates)
8161         Preds->push_back(P);
8162 
8163     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8164            "Predicate should be always true!");
8165   }
8166 
8167   // If an earlier exit exits on the first iteration (exit count zero), then
8168   // a later poison exit count should not propagate into the result. This are
8169   // exactly the semantics provided by umin_seq.
8170   return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8171 }
8172 
8173 /// Get the exact not taken count for this loop exit.
8174 const SCEV *
8175 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8176                                              ScalarEvolution *SE) const {
8177   for (auto &ENT : ExitNotTaken)
8178     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8179       return ENT.ExactNotTaken;
8180 
8181   return SE->getCouldNotCompute();
8182 }
8183 
8184 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8185     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8186   for (auto &ENT : ExitNotTaken)
8187     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8188       return ENT.MaxNotTaken;
8189 
8190   return SE->getCouldNotCompute();
8191 }
8192 
8193 /// getConstantMax - Get the constant max backedge taken count for the loop.
8194 const SCEV *
8195 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8196   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8197     return !ENT.hasAlwaysTruePredicate();
8198   };
8199 
8200   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8201     return SE->getCouldNotCompute();
8202 
8203   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8204           isa<SCEVConstant>(getConstantMax())) &&
8205          "No point in having a non-constant max backedge taken count!");
8206   return getConstantMax();
8207 }
8208 
8209 const SCEV *
8210 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8211                                                    ScalarEvolution *SE) {
8212   if (!SymbolicMax)
8213     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8214   return SymbolicMax;
8215 }
8216 
8217 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8218     ScalarEvolution *SE) const {
8219   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8220     return !ENT.hasAlwaysTruePredicate();
8221   };
8222   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8223 }
8224 
8225 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8226     : ExitLimit(E, E, false, None) {
8227 }
8228 
8229 ScalarEvolution::ExitLimit::ExitLimit(
8230     const SCEV *E, const SCEV *M, bool MaxOrZero,
8231     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8232     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
8233   // If we prove the max count is zero, so is the symbolic bound.  This happens
8234   // in practice due to differences in a) how context sensitive we've chosen
8235   // to be and b) how we reason about bounds impied by UB.
8236   if (MaxNotTaken->isZero())
8237     ExactNotTaken = MaxNotTaken;
8238 
8239   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8240           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
8241          "Exact is not allowed to be less precise than Max");
8242   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
8243           isa<SCEVConstant>(MaxNotTaken)) &&
8244          "No point in having a non-constant max backedge taken count!");
8245   for (auto *PredSet : PredSetList)
8246     for (auto *P : *PredSet)
8247       addPredicate(P);
8248   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8249          "Backedge count should be int");
8250   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
8251          "Max backedge count should be int");
8252 }
8253 
8254 ScalarEvolution::ExitLimit::ExitLimit(
8255     const SCEV *E, const SCEV *M, bool MaxOrZero,
8256     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8257     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
8258 }
8259 
8260 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
8261                                       bool MaxOrZero)
8262     : ExitLimit(E, M, MaxOrZero, None) {
8263 }
8264 
8265 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8266 /// computable exit into a persistent ExitNotTakenInfo array.
8267 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8268     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8269     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8270     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8271   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8272 
8273   ExitNotTaken.reserve(ExitCounts.size());
8274   std::transform(
8275       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
8276       [&](const EdgeExitInfo &EEI) {
8277         BasicBlock *ExitBB = EEI.first;
8278         const ExitLimit &EL = EEI.second;
8279         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
8280                                 EL.Predicates);
8281       });
8282   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8283           isa<SCEVConstant>(ConstantMax)) &&
8284          "No point in having a non-constant max backedge taken count!");
8285 }
8286 
8287 /// Compute the number of times the backedge of the specified loop will execute.
8288 ScalarEvolution::BackedgeTakenInfo
8289 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8290                                            bool AllowPredicates) {
8291   SmallVector<BasicBlock *, 8> ExitingBlocks;
8292   L->getExitingBlocks(ExitingBlocks);
8293 
8294   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8295 
8296   SmallVector<EdgeExitInfo, 4> ExitCounts;
8297   bool CouldComputeBECount = true;
8298   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8299   const SCEV *MustExitMaxBECount = nullptr;
8300   const SCEV *MayExitMaxBECount = nullptr;
8301   bool MustExitMaxOrZero = false;
8302 
8303   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8304   // and compute maxBECount.
8305   // Do a union of all the predicates here.
8306   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8307     BasicBlock *ExitBB = ExitingBlocks[i];
8308 
8309     // We canonicalize untaken exits to br (constant), ignore them so that
8310     // proving an exit untaken doesn't negatively impact our ability to reason
8311     // about the loop as whole.
8312     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8313       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8314         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8315         if (ExitIfTrue == CI->isZero())
8316           continue;
8317       }
8318 
8319     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8320 
8321     assert((AllowPredicates || EL.Predicates.empty()) &&
8322            "Predicated exit limit when predicates are not allowed!");
8323 
8324     // 1. For each exit that can be computed, add an entry to ExitCounts.
8325     // CouldComputeBECount is true only if all exits can be computed.
8326     if (EL.ExactNotTaken == getCouldNotCompute())
8327       // We couldn't compute an exact value for this exit, so
8328       // we won't be able to compute an exact value for the loop.
8329       CouldComputeBECount = false;
8330     else
8331       ExitCounts.emplace_back(ExitBB, EL);
8332 
8333     // 2. Derive the loop's MaxBECount from each exit's max number of
8334     // non-exiting iterations. Partition the loop exits into two kinds:
8335     // LoopMustExits and LoopMayExits.
8336     //
8337     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8338     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8339     // MaxBECount is the minimum EL.MaxNotTaken of computable
8340     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8341     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
8342     // computable EL.MaxNotTaken.
8343     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
8344         DT.dominates(ExitBB, Latch)) {
8345       if (!MustExitMaxBECount) {
8346         MustExitMaxBECount = EL.MaxNotTaken;
8347         MustExitMaxOrZero = EL.MaxOrZero;
8348       } else {
8349         MustExitMaxBECount =
8350             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
8351       }
8352     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8353       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
8354         MayExitMaxBECount = EL.MaxNotTaken;
8355       else {
8356         MayExitMaxBECount =
8357             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
8358       }
8359     }
8360   }
8361   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8362     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8363   // The loop backedge will be taken the maximum or zero times if there's
8364   // a single exit that must be taken the maximum or zero times.
8365   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8366 
8367   // Remember which SCEVs are used in exit limits for invalidation purposes.
8368   // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken
8369   // and MaxBECount, which must be SCEVConstant.
8370   for (const auto &Pair : ExitCounts)
8371     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8372       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8373   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8374                            MaxBECount, MaxOrZero);
8375 }
8376 
8377 ScalarEvolution::ExitLimit
8378 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8379                                       bool AllowPredicates) {
8380   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8381   // If our exiting block does not dominate the latch, then its connection with
8382   // loop's exit limit may be far from trivial.
8383   const BasicBlock *Latch = L->getLoopLatch();
8384   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8385     return getCouldNotCompute();
8386 
8387   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8388   Instruction *Term = ExitingBlock->getTerminator();
8389   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8390     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8391     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8392     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8393            "It should have one successor in loop and one exit block!");
8394     // Proceed to the next level to examine the exit condition expression.
8395     return computeExitLimitFromCond(
8396         L, BI->getCondition(), ExitIfTrue,
8397         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8398   }
8399 
8400   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8401     // For switch, make sure that there is a single exit from the loop.
8402     BasicBlock *Exit = nullptr;
8403     for (auto *SBB : successors(ExitingBlock))
8404       if (!L->contains(SBB)) {
8405         if (Exit) // Multiple exit successors.
8406           return getCouldNotCompute();
8407         Exit = SBB;
8408       }
8409     assert(Exit && "Exiting block must have at least one exit");
8410     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8411                                                 /*ControlsExit=*/IsOnlyExit);
8412   }
8413 
8414   return getCouldNotCompute();
8415 }
8416 
8417 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8418     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8419     bool ControlsExit, bool AllowPredicates) {
8420   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8421   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8422                                         ControlsExit, AllowPredicates);
8423 }
8424 
8425 Optional<ScalarEvolution::ExitLimit>
8426 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8427                                       bool ExitIfTrue, bool ControlsExit,
8428                                       bool AllowPredicates) {
8429   (void)this->L;
8430   (void)this->ExitIfTrue;
8431   (void)this->AllowPredicates;
8432 
8433   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8434          this->AllowPredicates == AllowPredicates &&
8435          "Variance in assumed invariant key components!");
8436   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8437   if (Itr == TripCountMap.end())
8438     return None;
8439   return Itr->second;
8440 }
8441 
8442 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8443                                              bool ExitIfTrue,
8444                                              bool ControlsExit,
8445                                              bool AllowPredicates,
8446                                              const ExitLimit &EL) {
8447   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8448          this->AllowPredicates == AllowPredicates &&
8449          "Variance in assumed invariant key components!");
8450 
8451   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8452   assert(InsertResult.second && "Expected successful insertion!");
8453   (void)InsertResult;
8454   (void)ExitIfTrue;
8455 }
8456 
8457 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8458     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8459     bool ControlsExit, bool AllowPredicates) {
8460 
8461   if (auto MaybeEL =
8462           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8463     return *MaybeEL;
8464 
8465   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8466                                               ControlsExit, AllowPredicates);
8467   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8468   return EL;
8469 }
8470 
8471 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8472     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8473     bool ControlsExit, bool AllowPredicates) {
8474   // Handle BinOp conditions (And, Or).
8475   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8476           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8477     return *LimitFromBinOp;
8478 
8479   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8480   // Proceed to the next level to examine the icmp.
8481   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8482     ExitLimit EL =
8483         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8484     if (EL.hasFullInfo() || !AllowPredicates)
8485       return EL;
8486 
8487     // Try again, but use SCEV predicates this time.
8488     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8489                                     /*AllowPredicates=*/true);
8490   }
8491 
8492   // Check for a constant condition. These are normally stripped out by
8493   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8494   // preserve the CFG and is temporarily leaving constant conditions
8495   // in place.
8496   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8497     if (ExitIfTrue == !CI->getZExtValue())
8498       // The backedge is always taken.
8499       return getCouldNotCompute();
8500     else
8501       // The backedge is never taken.
8502       return getZero(CI->getType());
8503   }
8504 
8505   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8506   // with a constant step, we can form an equivalent icmp predicate and figure
8507   // out how many iterations will be taken before we exit.
8508   const WithOverflowInst *WO;
8509   const APInt *C;
8510   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8511       match(WO->getRHS(), m_APInt(C))) {
8512     ConstantRange NWR =
8513       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8514                                            WO->getNoWrapKind());
8515     CmpInst::Predicate Pred;
8516     APInt NewRHSC, Offset;
8517     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8518     if (!ExitIfTrue)
8519       Pred = ICmpInst::getInversePredicate(Pred);
8520     auto *LHS = getSCEV(WO->getLHS());
8521     if (Offset != 0)
8522       LHS = getAddExpr(LHS, getConstant(Offset));
8523     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8524                                        ControlsExit, AllowPredicates);
8525     if (EL.hasAnyInfo()) return EL;
8526   }
8527 
8528   // If it's not an integer or pointer comparison then compute it the hard way.
8529   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8530 }
8531 
8532 Optional<ScalarEvolution::ExitLimit>
8533 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8534     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8535     bool ControlsExit, bool AllowPredicates) {
8536   // Check if the controlling expression for this loop is an And or Or.
8537   Value *Op0, *Op1;
8538   bool IsAnd = false;
8539   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8540     IsAnd = true;
8541   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8542     IsAnd = false;
8543   else
8544     return None;
8545 
8546   // EitherMayExit is true in these two cases:
8547   //   br (and Op0 Op1), loop, exit
8548   //   br (or  Op0 Op1), exit, loop
8549   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8550   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8551                                                  ControlsExit && !EitherMayExit,
8552                                                  AllowPredicates);
8553   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8554                                                  ControlsExit && !EitherMayExit,
8555                                                  AllowPredicates);
8556 
8557   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8558   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8559   if (isa<ConstantInt>(Op1))
8560     return Op1 == NeutralElement ? EL0 : EL1;
8561   if (isa<ConstantInt>(Op0))
8562     return Op0 == NeutralElement ? EL1 : EL0;
8563 
8564   const SCEV *BECount = getCouldNotCompute();
8565   const SCEV *MaxBECount = getCouldNotCompute();
8566   if (EitherMayExit) {
8567     // Both conditions must be same for the loop to continue executing.
8568     // Choose the less conservative count.
8569     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8570         EL1.ExactNotTaken != getCouldNotCompute()) {
8571       BECount = getUMinFromMismatchedTypes(
8572           EL0.ExactNotTaken, EL1.ExactNotTaken,
8573           /*Sequential=*/!isa<BinaryOperator>(ExitCond));
8574     }
8575     if (EL0.MaxNotTaken == getCouldNotCompute())
8576       MaxBECount = EL1.MaxNotTaken;
8577     else if (EL1.MaxNotTaken == getCouldNotCompute())
8578       MaxBECount = EL0.MaxNotTaken;
8579     else
8580       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8581   } else {
8582     // Both conditions must be same at the same time for the loop to exit.
8583     // For now, be conservative.
8584     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8585       BECount = EL0.ExactNotTaken;
8586   }
8587 
8588   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8589   // to be more aggressive when computing BECount than when computing
8590   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8591   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8592   // to not.
8593   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8594       !isa<SCEVCouldNotCompute>(BECount))
8595     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8596 
8597   return ExitLimit(BECount, MaxBECount, false,
8598                    { &EL0.Predicates, &EL1.Predicates });
8599 }
8600 
8601 ScalarEvolution::ExitLimit
8602 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8603                                           ICmpInst *ExitCond,
8604                                           bool ExitIfTrue,
8605                                           bool ControlsExit,
8606                                           bool AllowPredicates) {
8607   // If the condition was exit on true, convert the condition to exit on false
8608   ICmpInst::Predicate Pred;
8609   if (!ExitIfTrue)
8610     Pred = ExitCond->getPredicate();
8611   else
8612     Pred = ExitCond->getInversePredicate();
8613   const ICmpInst::Predicate OriginalPred = Pred;
8614 
8615   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8616   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8617 
8618   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
8619                                           AllowPredicates);
8620   if (EL.hasAnyInfo()) return EL;
8621 
8622   auto *ExhaustiveCount =
8623       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8624 
8625   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8626     return ExhaustiveCount;
8627 
8628   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8629                                       ExitCond->getOperand(1), L, OriginalPred);
8630 }
8631 ScalarEvolution::ExitLimit
8632 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8633                                           ICmpInst::Predicate Pred,
8634                                           const SCEV *LHS, const SCEV *RHS,
8635                                           bool ControlsExit,
8636                                           bool AllowPredicates) {
8637 
8638   // Try to evaluate any dependencies out of the loop.
8639   LHS = getSCEVAtScope(LHS, L);
8640   RHS = getSCEVAtScope(RHS, L);
8641 
8642   // At this point, we would like to compute how many iterations of the
8643   // loop the predicate will return true for these inputs.
8644   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8645     // If there is a loop-invariant, force it into the RHS.
8646     std::swap(LHS, RHS);
8647     Pred = ICmpInst::getSwappedPredicate(Pred);
8648   }
8649 
8650   bool ControllingFiniteLoop =
8651       ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
8652   // Simplify the operands before analyzing them.
8653   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
8654                              (EnableFiniteLoopControl ? ControllingFiniteLoop
8655                                                      : false));
8656 
8657   // If we have a comparison of a chrec against a constant, try to use value
8658   // ranges to answer this query.
8659   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8660     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8661       if (AddRec->getLoop() == L) {
8662         // Form the constant range.
8663         ConstantRange CompRange =
8664             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8665 
8666         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8667         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8668       }
8669 
8670   // If this loop must exit based on this condition (or execute undefined
8671   // behaviour), and we can prove the test sequence produced must repeat
8672   // the same values on self-wrap of the IV, then we can infer that IV
8673   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8674   // loop.
8675   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
8676     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8677     // invariant terms are effectively constants for our purposes here.
8678     auto *InnerLHS = LHS;
8679     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8680       InnerLHS = ZExt->getOperand();
8681     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8682       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8683       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8684           StrideC && StrideC->getAPInt().isPowerOf2()) {
8685         auto Flags = AR->getNoWrapFlags();
8686         Flags = setFlags(Flags, SCEV::FlagNW);
8687         SmallVector<const SCEV*> Operands{AR->operands()};
8688         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8689         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8690       }
8691     }
8692   }
8693 
8694   switch (Pred) {
8695   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8696     // Convert to: while (X-Y != 0)
8697     if (LHS->getType()->isPointerTy()) {
8698       LHS = getLosslessPtrToIntExpr(LHS);
8699       if (isa<SCEVCouldNotCompute>(LHS))
8700         return LHS;
8701     }
8702     if (RHS->getType()->isPointerTy()) {
8703       RHS = getLosslessPtrToIntExpr(RHS);
8704       if (isa<SCEVCouldNotCompute>(RHS))
8705         return RHS;
8706     }
8707     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8708                                 AllowPredicates);
8709     if (EL.hasAnyInfo()) return EL;
8710     break;
8711   }
8712   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8713     // Convert to: while (X-Y == 0)
8714     if (LHS->getType()->isPointerTy()) {
8715       LHS = getLosslessPtrToIntExpr(LHS);
8716       if (isa<SCEVCouldNotCompute>(LHS))
8717         return LHS;
8718     }
8719     if (RHS->getType()->isPointerTy()) {
8720       RHS = getLosslessPtrToIntExpr(RHS);
8721       if (isa<SCEVCouldNotCompute>(RHS))
8722         return RHS;
8723     }
8724     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8725     if (EL.hasAnyInfo()) return EL;
8726     break;
8727   }
8728   case ICmpInst::ICMP_SLT:
8729   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8730     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8731     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8732                                     AllowPredicates);
8733     if (EL.hasAnyInfo()) return EL;
8734     break;
8735   }
8736   case ICmpInst::ICMP_SGT:
8737   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8738     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8739     ExitLimit EL =
8740         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8741                             AllowPredicates);
8742     if (EL.hasAnyInfo()) return EL;
8743     break;
8744   }
8745   default:
8746     break;
8747   }
8748 
8749   return getCouldNotCompute();
8750 }
8751 
8752 ScalarEvolution::ExitLimit
8753 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8754                                                       SwitchInst *Switch,
8755                                                       BasicBlock *ExitingBlock,
8756                                                       bool ControlsExit) {
8757   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8758 
8759   // Give up if the exit is the default dest of a switch.
8760   if (Switch->getDefaultDest() == ExitingBlock)
8761     return getCouldNotCompute();
8762 
8763   assert(L->contains(Switch->getDefaultDest()) &&
8764          "Default case must not exit the loop!");
8765   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8766   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8767 
8768   // while (X != Y) --> while (X-Y != 0)
8769   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8770   if (EL.hasAnyInfo())
8771     return EL;
8772 
8773   return getCouldNotCompute();
8774 }
8775 
8776 static ConstantInt *
8777 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8778                                 ScalarEvolution &SE) {
8779   const SCEV *InVal = SE.getConstant(C);
8780   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8781   assert(isa<SCEVConstant>(Val) &&
8782          "Evaluation of SCEV at constant didn't fold correctly?");
8783   return cast<SCEVConstant>(Val)->getValue();
8784 }
8785 
8786 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8787     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8788   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8789   if (!RHS)
8790     return getCouldNotCompute();
8791 
8792   const BasicBlock *Latch = L->getLoopLatch();
8793   if (!Latch)
8794     return getCouldNotCompute();
8795 
8796   const BasicBlock *Predecessor = L->getLoopPredecessor();
8797   if (!Predecessor)
8798     return getCouldNotCompute();
8799 
8800   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8801   // Return LHS in OutLHS and shift_opt in OutOpCode.
8802   auto MatchPositiveShift =
8803       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8804 
8805     using namespace PatternMatch;
8806 
8807     ConstantInt *ShiftAmt;
8808     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8809       OutOpCode = Instruction::LShr;
8810     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8811       OutOpCode = Instruction::AShr;
8812     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8813       OutOpCode = Instruction::Shl;
8814     else
8815       return false;
8816 
8817     return ShiftAmt->getValue().isStrictlyPositive();
8818   };
8819 
8820   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8821   //
8822   // loop:
8823   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8824   //   %iv.shifted = lshr i32 %iv, <positive constant>
8825   //
8826   // Return true on a successful match.  Return the corresponding PHI node (%iv
8827   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8828   auto MatchShiftRecurrence =
8829       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8830     Optional<Instruction::BinaryOps> PostShiftOpCode;
8831 
8832     {
8833       Instruction::BinaryOps OpC;
8834       Value *V;
8835 
8836       // If we encounter a shift instruction, "peel off" the shift operation,
8837       // and remember that we did so.  Later when we inspect %iv's backedge
8838       // value, we will make sure that the backedge value uses the same
8839       // operation.
8840       //
8841       // Note: the peeled shift operation does not have to be the same
8842       // instruction as the one feeding into the PHI's backedge value.  We only
8843       // really care about it being the same *kind* of shift instruction --
8844       // that's all that is required for our later inferences to hold.
8845       if (MatchPositiveShift(LHS, V, OpC)) {
8846         PostShiftOpCode = OpC;
8847         LHS = V;
8848       }
8849     }
8850 
8851     PNOut = dyn_cast<PHINode>(LHS);
8852     if (!PNOut || PNOut->getParent() != L->getHeader())
8853       return false;
8854 
8855     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8856     Value *OpLHS;
8857 
8858     return
8859         // The backedge value for the PHI node must be a shift by a positive
8860         // amount
8861         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8862 
8863         // of the PHI node itself
8864         OpLHS == PNOut &&
8865 
8866         // and the kind of shift should be match the kind of shift we peeled
8867         // off, if any.
8868         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8869   };
8870 
8871   PHINode *PN;
8872   Instruction::BinaryOps OpCode;
8873   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8874     return getCouldNotCompute();
8875 
8876   const DataLayout &DL = getDataLayout();
8877 
8878   // The key rationale for this optimization is that for some kinds of shift
8879   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8880   // within a finite number of iterations.  If the condition guarding the
8881   // backedge (in the sense that the backedge is taken if the condition is true)
8882   // is false for the value the shift recurrence stabilizes to, then we know
8883   // that the backedge is taken only a finite number of times.
8884 
8885   ConstantInt *StableValue = nullptr;
8886   switch (OpCode) {
8887   default:
8888     llvm_unreachable("Impossible case!");
8889 
8890   case Instruction::AShr: {
8891     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8892     // bitwidth(K) iterations.
8893     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8894     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8895                                        Predecessor->getTerminator(), &DT);
8896     auto *Ty = cast<IntegerType>(RHS->getType());
8897     if (Known.isNonNegative())
8898       StableValue = ConstantInt::get(Ty, 0);
8899     else if (Known.isNegative())
8900       StableValue = ConstantInt::get(Ty, -1, true);
8901     else
8902       return getCouldNotCompute();
8903 
8904     break;
8905   }
8906   case Instruction::LShr:
8907   case Instruction::Shl:
8908     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8909     // stabilize to 0 in at most bitwidth(K) iterations.
8910     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8911     break;
8912   }
8913 
8914   auto *Result =
8915       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8916   assert(Result->getType()->isIntegerTy(1) &&
8917          "Otherwise cannot be an operand to a branch instruction");
8918 
8919   if (Result->isZeroValue()) {
8920     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8921     const SCEV *UpperBound =
8922         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8923     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8924   }
8925 
8926   return getCouldNotCompute();
8927 }
8928 
8929 /// Return true if we can constant fold an instruction of the specified type,
8930 /// assuming that all operands were constants.
8931 static bool CanConstantFold(const Instruction *I) {
8932   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8933       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8934       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8935     return true;
8936 
8937   if (const CallInst *CI = dyn_cast<CallInst>(I))
8938     if (const Function *F = CI->getCalledFunction())
8939       return canConstantFoldCallTo(CI, F);
8940   return false;
8941 }
8942 
8943 /// Determine whether this instruction can constant evolve within this loop
8944 /// assuming its operands can all constant evolve.
8945 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8946   // An instruction outside of the loop can't be derived from a loop PHI.
8947   if (!L->contains(I)) return false;
8948 
8949   if (isa<PHINode>(I)) {
8950     // We don't currently keep track of the control flow needed to evaluate
8951     // PHIs, so we cannot handle PHIs inside of loops.
8952     return L->getHeader() == I->getParent();
8953   }
8954 
8955   // If we won't be able to constant fold this expression even if the operands
8956   // are constants, bail early.
8957   return CanConstantFold(I);
8958 }
8959 
8960 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8961 /// recursing through each instruction operand until reaching a loop header phi.
8962 static PHINode *
8963 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8964                                DenseMap<Instruction *, PHINode *> &PHIMap,
8965                                unsigned Depth) {
8966   if (Depth > MaxConstantEvolvingDepth)
8967     return nullptr;
8968 
8969   // Otherwise, we can evaluate this instruction if all of its operands are
8970   // constant or derived from a PHI node themselves.
8971   PHINode *PHI = nullptr;
8972   for (Value *Op : UseInst->operands()) {
8973     if (isa<Constant>(Op)) continue;
8974 
8975     Instruction *OpInst = dyn_cast<Instruction>(Op);
8976     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8977 
8978     PHINode *P = dyn_cast<PHINode>(OpInst);
8979     if (!P)
8980       // If this operand is already visited, reuse the prior result.
8981       // We may have P != PHI if this is the deepest point at which the
8982       // inconsistent paths meet.
8983       P = PHIMap.lookup(OpInst);
8984     if (!P) {
8985       // Recurse and memoize the results, whether a phi is found or not.
8986       // This recursive call invalidates pointers into PHIMap.
8987       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8988       PHIMap[OpInst] = P;
8989     }
8990     if (!P)
8991       return nullptr;  // Not evolving from PHI
8992     if (PHI && PHI != P)
8993       return nullptr;  // Evolving from multiple different PHIs.
8994     PHI = P;
8995   }
8996   // This is a expression evolving from a constant PHI!
8997   return PHI;
8998 }
8999 
9000 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9001 /// in the loop that V is derived from.  We allow arbitrary operations along the
9002 /// way, but the operands of an operation must either be constants or a value
9003 /// derived from a constant PHI.  If this expression does not fit with these
9004 /// constraints, return null.
9005 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9006   Instruction *I = dyn_cast<Instruction>(V);
9007   if (!I || !canConstantEvolve(I, L)) return nullptr;
9008 
9009   if (PHINode *PN = dyn_cast<PHINode>(I))
9010     return PN;
9011 
9012   // Record non-constant instructions contained by the loop.
9013   DenseMap<Instruction *, PHINode *> PHIMap;
9014   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9015 }
9016 
9017 /// EvaluateExpression - Given an expression that passes the
9018 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9019 /// in the loop has the value PHIVal.  If we can't fold this expression for some
9020 /// reason, return null.
9021 static Constant *EvaluateExpression(Value *V, const Loop *L,
9022                                     DenseMap<Instruction *, Constant *> &Vals,
9023                                     const DataLayout &DL,
9024                                     const TargetLibraryInfo *TLI) {
9025   // Convenient constant check, but redundant for recursive calls.
9026   if (Constant *C = dyn_cast<Constant>(V)) return C;
9027   Instruction *I = dyn_cast<Instruction>(V);
9028   if (!I) return nullptr;
9029 
9030   if (Constant *C = Vals.lookup(I)) return C;
9031 
9032   // An instruction inside the loop depends on a value outside the loop that we
9033   // weren't given a mapping for, or a value such as a call inside the loop.
9034   if (!canConstantEvolve(I, L)) return nullptr;
9035 
9036   // An unmapped PHI can be due to a branch or another loop inside this loop,
9037   // or due to this not being the initial iteration through a loop where we
9038   // couldn't compute the evolution of this particular PHI last time.
9039   if (isa<PHINode>(I)) return nullptr;
9040 
9041   std::vector<Constant*> Operands(I->getNumOperands());
9042 
9043   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9044     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9045     if (!Operand) {
9046       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9047       if (!Operands[i]) return nullptr;
9048       continue;
9049     }
9050     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9051     Vals[Operand] = C;
9052     if (!C) return nullptr;
9053     Operands[i] = C;
9054   }
9055 
9056   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9057     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9058                                            Operands[1], DL, TLI);
9059   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9060     if (!LI->isVolatile())
9061       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
9062   }
9063   return ConstantFoldInstOperands(I, Operands, DL, TLI);
9064 }
9065 
9066 
9067 // If every incoming value to PN except the one for BB is a specific Constant,
9068 // return that, else return nullptr.
9069 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9070   Constant *IncomingVal = nullptr;
9071 
9072   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9073     if (PN->getIncomingBlock(i) == BB)
9074       continue;
9075 
9076     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9077     if (!CurrentVal)
9078       return nullptr;
9079 
9080     if (IncomingVal != CurrentVal) {
9081       if (IncomingVal)
9082         return nullptr;
9083       IncomingVal = CurrentVal;
9084     }
9085   }
9086 
9087   return IncomingVal;
9088 }
9089 
9090 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9091 /// in the header of its containing loop, we know the loop executes a
9092 /// constant number of times, and the PHI node is just a recurrence
9093 /// involving constants, fold it.
9094 Constant *
9095 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9096                                                    const APInt &BEs,
9097                                                    const Loop *L) {
9098   auto I = ConstantEvolutionLoopExitValue.find(PN);
9099   if (I != ConstantEvolutionLoopExitValue.end())
9100     return I->second;
9101 
9102   if (BEs.ugt(MaxBruteForceIterations))
9103     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
9104 
9105   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9106 
9107   DenseMap<Instruction *, Constant *> CurrentIterVals;
9108   BasicBlock *Header = L->getHeader();
9109   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9110 
9111   BasicBlock *Latch = L->getLoopLatch();
9112   if (!Latch)
9113     return nullptr;
9114 
9115   for (PHINode &PHI : Header->phis()) {
9116     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9117       CurrentIterVals[&PHI] = StartCST;
9118   }
9119   if (!CurrentIterVals.count(PN))
9120     return RetVal = nullptr;
9121 
9122   Value *BEValue = PN->getIncomingValueForBlock(Latch);
9123 
9124   // Execute the loop symbolically to determine the exit value.
9125   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9126          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9127 
9128   unsigned NumIterations = BEs.getZExtValue(); // must be in range
9129   unsigned IterationNum = 0;
9130   const DataLayout &DL = getDataLayout();
9131   for (; ; ++IterationNum) {
9132     if (IterationNum == NumIterations)
9133       return RetVal = CurrentIterVals[PN];  // Got exit value!
9134 
9135     // Compute the value of the PHIs for the next iteration.
9136     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9137     DenseMap<Instruction *, Constant *> NextIterVals;
9138     Constant *NextPHI =
9139         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9140     if (!NextPHI)
9141       return nullptr;        // Couldn't evaluate!
9142     NextIterVals[PN] = NextPHI;
9143 
9144     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9145 
9146     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9147     // cease to be able to evaluate one of them or if they stop evolving,
9148     // because that doesn't necessarily prevent us from computing PN.
9149     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9150     for (const auto &I : CurrentIterVals) {
9151       PHINode *PHI = dyn_cast<PHINode>(I.first);
9152       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9153       PHIsToCompute.emplace_back(PHI, I.second);
9154     }
9155     // We use two distinct loops because EvaluateExpression may invalidate any
9156     // iterators into CurrentIterVals.
9157     for (const auto &I : PHIsToCompute) {
9158       PHINode *PHI = I.first;
9159       Constant *&NextPHI = NextIterVals[PHI];
9160       if (!NextPHI) {   // Not already computed.
9161         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9162         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9163       }
9164       if (NextPHI != I.second)
9165         StoppedEvolving = false;
9166     }
9167 
9168     // If all entries in CurrentIterVals == NextIterVals then we can stop
9169     // iterating, the loop can't continue to change.
9170     if (StoppedEvolving)
9171       return RetVal = CurrentIterVals[PN];
9172 
9173     CurrentIterVals.swap(NextIterVals);
9174   }
9175 }
9176 
9177 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9178                                                           Value *Cond,
9179                                                           bool ExitWhen) {
9180   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9181   if (!PN) return getCouldNotCompute();
9182 
9183   // If the loop is canonicalized, the PHI will have exactly two entries.
9184   // That's the only form we support here.
9185   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9186 
9187   DenseMap<Instruction *, Constant *> CurrentIterVals;
9188   BasicBlock *Header = L->getHeader();
9189   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9190 
9191   BasicBlock *Latch = L->getLoopLatch();
9192   assert(Latch && "Should follow from NumIncomingValues == 2!");
9193 
9194   for (PHINode &PHI : Header->phis()) {
9195     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9196       CurrentIterVals[&PHI] = StartCST;
9197   }
9198   if (!CurrentIterVals.count(PN))
9199     return getCouldNotCompute();
9200 
9201   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9202   // the loop symbolically to determine when the condition gets a value of
9203   // "ExitWhen".
9204   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9205   const DataLayout &DL = getDataLayout();
9206   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9207     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9208         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9209 
9210     // Couldn't symbolically evaluate.
9211     if (!CondVal) return getCouldNotCompute();
9212 
9213     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9214       ++NumBruteForceTripCountsComputed;
9215       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9216     }
9217 
9218     // Update all the PHI nodes for the next iteration.
9219     DenseMap<Instruction *, Constant *> NextIterVals;
9220 
9221     // Create a list of which PHIs we need to compute. We want to do this before
9222     // calling EvaluateExpression on them because that may invalidate iterators
9223     // into CurrentIterVals.
9224     SmallVector<PHINode *, 8> PHIsToCompute;
9225     for (const auto &I : CurrentIterVals) {
9226       PHINode *PHI = dyn_cast<PHINode>(I.first);
9227       if (!PHI || PHI->getParent() != Header) continue;
9228       PHIsToCompute.push_back(PHI);
9229     }
9230     for (PHINode *PHI : PHIsToCompute) {
9231       Constant *&NextPHI = NextIterVals[PHI];
9232       if (NextPHI) continue;    // Already computed!
9233 
9234       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9235       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9236     }
9237     CurrentIterVals.swap(NextIterVals);
9238   }
9239 
9240   // Too many iterations were needed to evaluate.
9241   return getCouldNotCompute();
9242 }
9243 
9244 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9245   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9246       ValuesAtScopes[V];
9247   // Check to see if we've folded this expression at this loop before.
9248   for (auto &LS : Values)
9249     if (LS.first == L)
9250       return LS.second ? LS.second : V;
9251 
9252   Values.emplace_back(L, nullptr);
9253 
9254   // Otherwise compute it.
9255   const SCEV *C = computeSCEVAtScope(V, L);
9256   for (auto &LS : reverse(ValuesAtScopes[V]))
9257     if (LS.first == L) {
9258       LS.second = C;
9259       if (!isa<SCEVConstant>(C))
9260         ValuesAtScopesUsers[C].push_back({L, V});
9261       break;
9262     }
9263   return C;
9264 }
9265 
9266 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9267 /// will return Constants for objects which aren't represented by a
9268 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9269 /// Returns NULL if the SCEV isn't representable as a Constant.
9270 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9271   switch (V->getSCEVType()) {
9272   case scCouldNotCompute:
9273   case scAddRecExpr:
9274     return nullptr;
9275   case scConstant:
9276     return cast<SCEVConstant>(V)->getValue();
9277   case scUnknown:
9278     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9279   case scSignExtend: {
9280     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9281     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9282       return ConstantExpr::getSExt(CastOp, SS->getType());
9283     return nullptr;
9284   }
9285   case scZeroExtend: {
9286     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9287     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9288       return ConstantExpr::getZExt(CastOp, SZ->getType());
9289     return nullptr;
9290   }
9291   case scPtrToInt: {
9292     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9293     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9294       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9295 
9296     return nullptr;
9297   }
9298   case scTruncate: {
9299     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9300     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9301       return ConstantExpr::getTrunc(CastOp, ST->getType());
9302     return nullptr;
9303   }
9304   case scAddExpr: {
9305     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9306     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
9307       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
9308         unsigned AS = PTy->getAddressSpace();
9309         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9310         C = ConstantExpr::getBitCast(C, DestPtrTy);
9311       }
9312       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
9313         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
9314         if (!C2)
9315           return nullptr;
9316 
9317         // First pointer!
9318         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
9319           unsigned AS = C2->getType()->getPointerAddressSpace();
9320           std::swap(C, C2);
9321           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9322           // The offsets have been converted to bytes.  We can add bytes to an
9323           // i8* by GEP with the byte count in the first index.
9324           C = ConstantExpr::getBitCast(C, DestPtrTy);
9325         }
9326 
9327         // Don't bother trying to sum two pointers. We probably can't
9328         // statically compute a load that results from it anyway.
9329         if (C2->getType()->isPointerTy())
9330           return nullptr;
9331 
9332         if (C->getType()->isPointerTy()) {
9333           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9334                                              C, C2);
9335         } else {
9336           C = ConstantExpr::getAdd(C, C2);
9337         }
9338       }
9339       return C;
9340     }
9341     return nullptr;
9342   }
9343   case scMulExpr: {
9344     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9345     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
9346       // Don't bother with pointers at all.
9347       if (C->getType()->isPointerTy())
9348         return nullptr;
9349       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
9350         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
9351         if (!C2 || C2->getType()->isPointerTy())
9352           return nullptr;
9353         C = ConstantExpr::getMul(C, C2);
9354       }
9355       return C;
9356     }
9357     return nullptr;
9358   }
9359   case scUDivExpr: {
9360     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
9361     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
9362       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
9363         if (LHS->getType() == RHS->getType())
9364           return ConstantExpr::getUDiv(LHS, RHS);
9365     return nullptr;
9366   }
9367   case scSMaxExpr:
9368   case scUMaxExpr:
9369   case scSMinExpr:
9370   case scUMinExpr:
9371   case scSequentialUMinExpr:
9372     return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9373   }
9374   llvm_unreachable("Unknown SCEV kind!");
9375 }
9376 
9377 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9378   if (isa<SCEVConstant>(V)) return V;
9379 
9380   // If this instruction is evolved from a constant-evolving PHI, compute the
9381   // exit value from the loop without using SCEVs.
9382   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
9383     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
9384       if (PHINode *PN = dyn_cast<PHINode>(I)) {
9385         const Loop *CurrLoop = this->LI[I->getParent()];
9386         // Looking for loop exit value.
9387         if (CurrLoop && CurrLoop->getParentLoop() == L &&
9388             PN->getParent() == CurrLoop->getHeader()) {
9389           // Okay, there is no closed form solution for the PHI node.  Check
9390           // to see if the loop that contains it has a known backedge-taken
9391           // count.  If so, we may be able to force computation of the exit
9392           // value.
9393           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9394           // This trivial case can show up in some degenerate cases where
9395           // the incoming IR has not yet been fully simplified.
9396           if (BackedgeTakenCount->isZero()) {
9397             Value *InitValue = nullptr;
9398             bool MultipleInitValues = false;
9399             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9400               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9401                 if (!InitValue)
9402                   InitValue = PN->getIncomingValue(i);
9403                 else if (InitValue != PN->getIncomingValue(i)) {
9404                   MultipleInitValues = true;
9405                   break;
9406                 }
9407               }
9408             }
9409             if (!MultipleInitValues && InitValue)
9410               return getSCEV(InitValue);
9411           }
9412           // Do we have a loop invariant value flowing around the backedge
9413           // for a loop which must execute the backedge?
9414           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9415               isKnownPositive(BackedgeTakenCount) &&
9416               PN->getNumIncomingValues() == 2) {
9417 
9418             unsigned InLoopPred =
9419                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9420             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9421             if (CurrLoop->isLoopInvariant(BackedgeVal))
9422               return getSCEV(BackedgeVal);
9423           }
9424           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9425             // Okay, we know how many times the containing loop executes.  If
9426             // this is a constant evolving PHI node, get the final value at
9427             // the specified iteration number.
9428             Constant *RV = getConstantEvolutionLoopExitValue(
9429                 PN, BTCC->getAPInt(), CurrLoop);
9430             if (RV) return getSCEV(RV);
9431           }
9432         }
9433 
9434         // If there is a single-input Phi, evaluate it at our scope. If we can
9435         // prove that this replacement does not break LCSSA form, use new value.
9436         if (PN->getNumOperands() == 1) {
9437           const SCEV *Input = getSCEV(PN->getOperand(0));
9438           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9439           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9440           // for the simplest case just support constants.
9441           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9442         }
9443       }
9444 
9445       // Okay, this is an expression that we cannot symbolically evaluate
9446       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9447       // the arguments into constants, and if so, try to constant propagate the
9448       // result.  This is particularly useful for computing loop exit values.
9449       if (CanConstantFold(I)) {
9450         SmallVector<Constant *, 4> Operands;
9451         bool MadeImprovement = false;
9452         for (Value *Op : I->operands()) {
9453           if (Constant *C = dyn_cast<Constant>(Op)) {
9454             Operands.push_back(C);
9455             continue;
9456           }
9457 
9458           // If any of the operands is non-constant and if they are
9459           // non-integer and non-pointer, don't even try to analyze them
9460           // with scev techniques.
9461           if (!isSCEVable(Op->getType()))
9462             return V;
9463 
9464           const SCEV *OrigV = getSCEV(Op);
9465           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9466           MadeImprovement |= OrigV != OpV;
9467 
9468           Constant *C = BuildConstantFromSCEV(OpV);
9469           if (!C) return V;
9470           if (C->getType() != Op->getType())
9471             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9472                                                               Op->getType(),
9473                                                               false),
9474                                       C, Op->getType());
9475           Operands.push_back(C);
9476         }
9477 
9478         // Check to see if getSCEVAtScope actually made an improvement.
9479         if (MadeImprovement) {
9480           Constant *C = nullptr;
9481           const DataLayout &DL = getDataLayout();
9482           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9483             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9484                                                 Operands[1], DL, &TLI);
9485           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9486             if (!Load->isVolatile())
9487               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9488                                                DL);
9489           } else
9490             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9491           if (!C) return V;
9492           return getSCEV(C);
9493         }
9494       }
9495     }
9496 
9497     // This is some other type of SCEVUnknown, just return it.
9498     return V;
9499   }
9500 
9501   if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) {
9502     const auto *Comm = cast<SCEVNAryExpr>(V);
9503     // Avoid performing the look-up in the common case where the specified
9504     // expression has no loop-variant portions.
9505     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9506       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9507       if (OpAtScope != Comm->getOperand(i)) {
9508         // Okay, at least one of these operands is loop variant but might be
9509         // foldable.  Build a new instance of the folded commutative expression.
9510         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9511                                             Comm->op_begin()+i);
9512         NewOps.push_back(OpAtScope);
9513 
9514         for (++i; i != e; ++i) {
9515           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9516           NewOps.push_back(OpAtScope);
9517         }
9518         if (isa<SCEVAddExpr>(Comm))
9519           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9520         if (isa<SCEVMulExpr>(Comm))
9521           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9522         if (isa<SCEVMinMaxExpr>(Comm))
9523           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9524         if (isa<SCEVSequentialMinMaxExpr>(Comm))
9525           return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps);
9526         llvm_unreachable("Unknown commutative / sequential min/max SCEV type!");
9527       }
9528     }
9529     // If we got here, all operands are loop invariant.
9530     return Comm;
9531   }
9532 
9533   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9534     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9535     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9536     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9537       return Div;   // must be loop invariant
9538     return getUDivExpr(LHS, RHS);
9539   }
9540 
9541   // If this is a loop recurrence for a loop that does not contain L, then we
9542   // are dealing with the final value computed by the loop.
9543   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9544     // First, attempt to evaluate each operand.
9545     // Avoid performing the look-up in the common case where the specified
9546     // expression has no loop-variant portions.
9547     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9548       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9549       if (OpAtScope == AddRec->getOperand(i))
9550         continue;
9551 
9552       // Okay, at least one of these operands is loop variant but might be
9553       // foldable.  Build a new instance of the folded commutative expression.
9554       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9555                                           AddRec->op_begin()+i);
9556       NewOps.push_back(OpAtScope);
9557       for (++i; i != e; ++i)
9558         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9559 
9560       const SCEV *FoldedRec =
9561         getAddRecExpr(NewOps, AddRec->getLoop(),
9562                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9563       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9564       // The addrec may be folded to a nonrecurrence, for example, if the
9565       // induction variable is multiplied by zero after constant folding. Go
9566       // ahead and return the folded value.
9567       if (!AddRec)
9568         return FoldedRec;
9569       break;
9570     }
9571 
9572     // If the scope is outside the addrec's loop, evaluate it by using the
9573     // loop exit value of the addrec.
9574     if (!AddRec->getLoop()->contains(L)) {
9575       // To evaluate this recurrence, we need to know how many times the AddRec
9576       // loop iterates.  Compute this now.
9577       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9578       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9579 
9580       // Then, evaluate the AddRec.
9581       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9582     }
9583 
9584     return AddRec;
9585   }
9586 
9587   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
9588     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9589     if (Op == Cast->getOperand())
9590       return Cast;  // must be loop invariant
9591     return getCastExpr(Cast->getSCEVType(), Op, Cast->getType());
9592   }
9593 
9594   llvm_unreachable("Unknown SCEV type!");
9595 }
9596 
9597 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9598   return getSCEVAtScope(getSCEV(V), L);
9599 }
9600 
9601 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9602   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9603     return stripInjectiveFunctions(ZExt->getOperand());
9604   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9605     return stripInjectiveFunctions(SExt->getOperand());
9606   return S;
9607 }
9608 
9609 /// Finds the minimum unsigned root of the following equation:
9610 ///
9611 ///     A * X = B (mod N)
9612 ///
9613 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9614 /// A and B isn't important.
9615 ///
9616 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9617 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9618                                                ScalarEvolution &SE) {
9619   uint32_t BW = A.getBitWidth();
9620   assert(BW == SE.getTypeSizeInBits(B->getType()));
9621   assert(A != 0 && "A must be non-zero.");
9622 
9623   // 1. D = gcd(A, N)
9624   //
9625   // The gcd of A and N may have only one prime factor: 2. The number of
9626   // trailing zeros in A is its multiplicity
9627   uint32_t Mult2 = A.countTrailingZeros();
9628   // D = 2^Mult2
9629 
9630   // 2. Check if B is divisible by D.
9631   //
9632   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9633   // is not less than multiplicity of this prime factor for D.
9634   if (SE.GetMinTrailingZeros(B) < Mult2)
9635     return SE.getCouldNotCompute();
9636 
9637   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9638   // modulo (N / D).
9639   //
9640   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9641   // (N / D) in general. The inverse itself always fits into BW bits, though,
9642   // so we immediately truncate it.
9643   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9644   APInt Mod(BW + 1, 0);
9645   Mod.setBit(BW - Mult2);  // Mod = N / D
9646   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9647 
9648   // 4. Compute the minimum unsigned root of the equation:
9649   // I * (B / D) mod (N / D)
9650   // To simplify the computation, we factor out the divide by D:
9651   // (I * B mod N) / D
9652   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9653   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9654 }
9655 
9656 /// For a given quadratic addrec, generate coefficients of the corresponding
9657 /// quadratic equation, multiplied by a common value to ensure that they are
9658 /// integers.
9659 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9660 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9661 /// were multiplied by, and BitWidth is the bit width of the original addrec
9662 /// coefficients.
9663 /// This function returns None if the addrec coefficients are not compile-
9664 /// time constants.
9665 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9666 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9667   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9668   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9669   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9670   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9671   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9672                     << *AddRec << '\n');
9673 
9674   // We currently can only solve this if the coefficients are constants.
9675   if (!LC || !MC || !NC) {
9676     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9677     return None;
9678   }
9679 
9680   APInt L = LC->getAPInt();
9681   APInt M = MC->getAPInt();
9682   APInt N = NC->getAPInt();
9683   assert(!N.isZero() && "This is not a quadratic addrec");
9684 
9685   unsigned BitWidth = LC->getAPInt().getBitWidth();
9686   unsigned NewWidth = BitWidth + 1;
9687   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9688                     << BitWidth << '\n');
9689   // The sign-extension (as opposed to a zero-extension) here matches the
9690   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9691   N = N.sext(NewWidth);
9692   M = M.sext(NewWidth);
9693   L = L.sext(NewWidth);
9694 
9695   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9696   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9697   //   L+M, L+2M+N, L+3M+3N, ...
9698   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9699   //
9700   // The equation Acc = 0 is then
9701   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9702   // In a quadratic form it becomes:
9703   //   N n^2 + (2M-N) n + 2L = 0.
9704 
9705   APInt A = N;
9706   APInt B = 2 * M - A;
9707   APInt C = 2 * L;
9708   APInt T = APInt(NewWidth, 2);
9709   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9710                     << "x + " << C << ", coeff bw: " << NewWidth
9711                     << ", multiplied by " << T << '\n');
9712   return std::make_tuple(A, B, C, T, BitWidth);
9713 }
9714 
9715 /// Helper function to compare optional APInts:
9716 /// (a) if X and Y both exist, return min(X, Y),
9717 /// (b) if neither X nor Y exist, return None,
9718 /// (c) if exactly one of X and Y exists, return that value.
9719 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9720   if (X.hasValue() && Y.hasValue()) {
9721     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9722     APInt XW = X->sext(W);
9723     APInt YW = Y->sext(W);
9724     return XW.slt(YW) ? *X : *Y;
9725   }
9726   if (!X.hasValue() && !Y.hasValue())
9727     return None;
9728   return X.hasValue() ? *X : *Y;
9729 }
9730 
9731 /// Helper function to truncate an optional APInt to a given BitWidth.
9732 /// When solving addrec-related equations, it is preferable to return a value
9733 /// that has the same bit width as the original addrec's coefficients. If the
9734 /// solution fits in the original bit width, truncate it (except for i1).
9735 /// Returning a value of a different bit width may inhibit some optimizations.
9736 ///
9737 /// In general, a solution to a quadratic equation generated from an addrec
9738 /// may require BW+1 bits, where BW is the bit width of the addrec's
9739 /// coefficients. The reason is that the coefficients of the quadratic
9740 /// equation are BW+1 bits wide (to avoid truncation when converting from
9741 /// the addrec to the equation).
9742 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9743   if (!X.hasValue())
9744     return None;
9745   unsigned W = X->getBitWidth();
9746   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9747     return X->trunc(BitWidth);
9748   return X;
9749 }
9750 
9751 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9752 /// iterations. The values L, M, N are assumed to be signed, and they
9753 /// should all have the same bit widths.
9754 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9755 /// where BW is the bit width of the addrec's coefficients.
9756 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9757 /// returned as such, otherwise the bit width of the returned value may
9758 /// be greater than BW.
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 cases
9763 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9764 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9765 static Optional<APInt>
9766 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9767   APInt A, B, C, M;
9768   unsigned BitWidth;
9769   auto T = GetQuadraticEquation(AddRec);
9770   if (!T.hasValue())
9771     return None;
9772 
9773   std::tie(A, B, C, M, BitWidth) = *T;
9774   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9775   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9776   if (!X.hasValue())
9777     return None;
9778 
9779   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9780   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9781   if (!V->isZero())
9782     return None;
9783 
9784   return TruncIfPossible(X, BitWidth);
9785 }
9786 
9787 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9788 /// iterations. The values M, N are assumed to be signed, and they
9789 /// should all have the same bit widths.
9790 /// Find the least n such that c(n) does not belong to the given range,
9791 /// while c(n-1) does.
9792 ///
9793 /// This function returns None if
9794 /// (a) the addrec coefficients are not constant, or
9795 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9796 ///     bounds of the range.
9797 static Optional<APInt>
9798 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9799                           const ConstantRange &Range, ScalarEvolution &SE) {
9800   assert(AddRec->getOperand(0)->isZero() &&
9801          "Starting value of addrec should be 0");
9802   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9803                     << Range << ", addrec " << *AddRec << '\n');
9804   // This case is handled in getNumIterationsInRange. Here we can assume that
9805   // we start in the range.
9806   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9807          "Addrec's initial value should be in range");
9808 
9809   APInt A, B, C, M;
9810   unsigned BitWidth;
9811   auto T = GetQuadraticEquation(AddRec);
9812   if (!T.hasValue())
9813     return None;
9814 
9815   // Be careful about the return value: there can be two reasons for not
9816   // returning an actual number. First, if no solutions to the equations
9817   // were found, and second, if the solutions don't leave the given range.
9818   // The first case means that the actual solution is "unknown", the second
9819   // means that it's known, but not valid. If the solution is unknown, we
9820   // cannot make any conclusions.
9821   // Return a pair: the optional solution and a flag indicating if the
9822   // solution was found.
9823   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9824     // Solve for signed overflow and unsigned overflow, pick the lower
9825     // solution.
9826     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9827                       << Bound << " (before multiplying by " << M << ")\n");
9828     Bound *= M; // The quadratic equation multiplier.
9829 
9830     Optional<APInt> SO = None;
9831     if (BitWidth > 1) {
9832       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9833                            "signed overflow\n");
9834       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9835     }
9836     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9837                          "unsigned overflow\n");
9838     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9839                                                               BitWidth+1);
9840 
9841     auto LeavesRange = [&] (const APInt &X) {
9842       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9843       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9844       if (Range.contains(V0->getValue()))
9845         return false;
9846       // X should be at least 1, so X-1 is non-negative.
9847       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9848       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9849       if (Range.contains(V1->getValue()))
9850         return true;
9851       return false;
9852     };
9853 
9854     // If SolveQuadraticEquationWrap returns None, it means that there can
9855     // be a solution, but the function failed to find it. We cannot treat it
9856     // as "no solution".
9857     if (!SO.hasValue() || !UO.hasValue())
9858       return { None, false };
9859 
9860     // Check the smaller value first to see if it leaves the range.
9861     // At this point, both SO and UO must have values.
9862     Optional<APInt> Min = MinOptional(SO, UO);
9863     if (LeavesRange(*Min))
9864       return { Min, true };
9865     Optional<APInt> Max = Min == SO ? UO : SO;
9866     if (LeavesRange(*Max))
9867       return { Max, true };
9868 
9869     // Solutions were found, but were eliminated, hence the "true".
9870     return { None, true };
9871   };
9872 
9873   std::tie(A, B, C, M, BitWidth) = *T;
9874   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9875   APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
9876   APInt Upper = Range.getUpper().sext(A.getBitWidth());
9877   auto SL = SolveForBoundary(Lower);
9878   auto SU = SolveForBoundary(Upper);
9879   // If any of the solutions was unknown, no meaninigful conclusions can
9880   // be made.
9881   if (!SL.second || !SU.second)
9882     return None;
9883 
9884   // Claim: The correct solution is not some value between Min and Max.
9885   //
9886   // Justification: Assuming that Min and Max are different values, one of
9887   // them is when the first signed overflow happens, the other is when the
9888   // first unsigned overflow happens. Crossing the range boundary is only
9889   // possible via an overflow (treating 0 as a special case of it, modeling
9890   // an overflow as crossing k*2^W for some k).
9891   //
9892   // The interesting case here is when Min was eliminated as an invalid
9893   // solution, but Max was not. The argument is that if there was another
9894   // overflow between Min and Max, it would also have been eliminated if
9895   // it was considered.
9896   //
9897   // For a given boundary, it is possible to have two overflows of the same
9898   // type (signed/unsigned) without having the other type in between: this
9899   // can happen when the vertex of the parabola is between the iterations
9900   // corresponding to the overflows. This is only possible when the two
9901   // overflows cross k*2^W for the same k. In such case, if the second one
9902   // left the range (and was the first one to do so), the first overflow
9903   // would have to enter the range, which would mean that either we had left
9904   // the range before or that we started outside of it. Both of these cases
9905   // are contradictions.
9906   //
9907   // Claim: In the case where SolveForBoundary returns None, the correct
9908   // solution is not some value between the Max for this boundary and the
9909   // Min of the other boundary.
9910   //
9911   // Justification: Assume that we had such Max_A and Min_B corresponding
9912   // to range boundaries A and B and such that Max_A < Min_B. If there was
9913   // a solution between Max_A and Min_B, it would have to be caused by an
9914   // overflow corresponding to either A or B. It cannot correspond to B,
9915   // since Min_B is the first occurrence of such an overflow. If it
9916   // corresponded to A, it would have to be either a signed or an unsigned
9917   // overflow that is larger than both eliminated overflows for A. But
9918   // between the eliminated overflows and this overflow, the values would
9919   // cover the entire value space, thus crossing the other boundary, which
9920   // is a contradiction.
9921 
9922   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9923 }
9924 
9925 ScalarEvolution::ExitLimit
9926 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9927                               bool AllowPredicates) {
9928 
9929   // This is only used for loops with a "x != y" exit test. The exit condition
9930   // is now expressed as a single expression, V = x-y. So the exit test is
9931   // effectively V != 0.  We know and take advantage of the fact that this
9932   // expression only being used in a comparison by zero context.
9933 
9934   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9935   // If the value is a constant
9936   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9937     // If the value is already zero, the branch will execute zero times.
9938     if (C->getValue()->isZero()) return C;
9939     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9940   }
9941 
9942   const SCEVAddRecExpr *AddRec =
9943       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9944 
9945   if (!AddRec && AllowPredicates)
9946     // Try to make this an AddRec using runtime tests, in the first X
9947     // iterations of this loop, where X is the SCEV expression found by the
9948     // algorithm below.
9949     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9950 
9951   if (!AddRec || AddRec->getLoop() != L)
9952     return getCouldNotCompute();
9953 
9954   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9955   // the quadratic equation to solve it.
9956   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9957     // We can only use this value if the chrec ends up with an exact zero
9958     // value at this index.  When solving for "X*X != 5", for example, we
9959     // should not accept a root of 2.
9960     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9961       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9962       return ExitLimit(R, R, false, Predicates);
9963     }
9964     return getCouldNotCompute();
9965   }
9966 
9967   // Otherwise we can only handle this if it is affine.
9968   if (!AddRec->isAffine())
9969     return getCouldNotCompute();
9970 
9971   // If this is an affine expression, the execution count of this branch is
9972   // the minimum unsigned root of the following equation:
9973   //
9974   //     Start + Step*N = 0 (mod 2^BW)
9975   //
9976   // equivalent to:
9977   //
9978   //             Step*N = -Start (mod 2^BW)
9979   //
9980   // where BW is the common bit width of Start and Step.
9981 
9982   // Get the initial value for the loop.
9983   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9984   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9985 
9986   // For now we handle only constant steps.
9987   //
9988   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9989   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9990   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9991   // We have not yet seen any such cases.
9992   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9993   if (!StepC || StepC->getValue()->isZero())
9994     return getCouldNotCompute();
9995 
9996   // For positive steps (counting up until unsigned overflow):
9997   //   N = -Start/Step (as unsigned)
9998   // For negative steps (counting down to zero):
9999   //   N = Start/-Step
10000   // First compute the unsigned distance from zero in the direction of Step.
10001   bool CountDown = StepC->getAPInt().isNegative();
10002   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10003 
10004   // Handle unitary steps, which cannot wraparound.
10005   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10006   //   N = Distance (as unsigned)
10007   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
10008     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
10009     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10010 
10011     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10012     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
10013     // case, and see if we can improve the bound.
10014     //
10015     // Explicitly handling this here is necessary because getUnsignedRange
10016     // isn't context-sensitive; it doesn't know that we only care about the
10017     // range inside the loop.
10018     const SCEV *Zero = getZero(Distance->getType());
10019     const SCEV *One = getOne(Distance->getType());
10020     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10021     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10022       // If Distance + 1 doesn't overflow, we can compute the maximum distance
10023       // as "unsigned_max(Distance + 1) - 1".
10024       ConstantRange CR = getUnsignedRange(DistancePlusOne);
10025       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10026     }
10027     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
10028   }
10029 
10030   // If the condition controls loop exit (the loop exits only if the expression
10031   // is true) and the addition is no-wrap we can use unsigned divide to
10032   // compute the backedge count.  In this case, the step may not divide the
10033   // distance, but we don't care because if the condition is "missed" the loop
10034   // will have undefined behavior due to wrapping.
10035   if (ControlsExit && AddRec->hasNoSelfWrap() &&
10036       loopHasNoAbnormalExits(AddRec->getLoop())) {
10037     const SCEV *Exact =
10038         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10039     const SCEV *Max = getCouldNotCompute();
10040     if (Exact != getCouldNotCompute()) {
10041       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10042       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10043     }
10044     return ExitLimit(Exact, Max, false, Predicates);
10045   }
10046 
10047   // Solve the general equation.
10048   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10049                                                getNegativeSCEV(Start), *this);
10050 
10051   const SCEV *M = E;
10052   if (E != getCouldNotCompute()) {
10053     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10054     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10055   }
10056   return ExitLimit(E, M, false, Predicates);
10057 }
10058 
10059 ScalarEvolution::ExitLimit
10060 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10061   // Loops that look like: while (X == 0) are very strange indeed.  We don't
10062   // handle them yet except for the trivial case.  This could be expanded in the
10063   // future as needed.
10064 
10065   // If the value is a constant, check to see if it is known to be non-zero
10066   // already.  If so, the backedge will execute zero times.
10067   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10068     if (!C->getValue()->isZero())
10069       return getZero(C->getType());
10070     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10071   }
10072 
10073   // We could implement others, but I really doubt anyone writes loops like
10074   // this, and if they did, they would already be constant folded.
10075   return getCouldNotCompute();
10076 }
10077 
10078 std::pair<const BasicBlock *, const BasicBlock *>
10079 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10080     const {
10081   // If the block has a unique predecessor, then there is no path from the
10082   // predecessor to the block that does not go through the direct edge
10083   // from the predecessor to the block.
10084   if (const BasicBlock *Pred = BB->getSinglePredecessor())
10085     return {Pred, BB};
10086 
10087   // A loop's header is defined to be a block that dominates the loop.
10088   // If the header has a unique predecessor outside the loop, it must be
10089   // a block that has exactly one successor that can reach the loop.
10090   if (const Loop *L = LI.getLoopFor(BB))
10091     return {L->getLoopPredecessor(), L->getHeader()};
10092 
10093   return {nullptr, nullptr};
10094 }
10095 
10096 /// SCEV structural equivalence is usually sufficient for testing whether two
10097 /// expressions are equal, however for the purposes of looking for a condition
10098 /// guarding a loop, it can be useful to be a little more general, since a
10099 /// front-end may have replicated the controlling expression.
10100 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10101   // Quick check to see if they are the same SCEV.
10102   if (A == B) return true;
10103 
10104   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10105     // Not all instructions that are "identical" compute the same value.  For
10106     // instance, two distinct alloca instructions allocating the same type are
10107     // identical and do not read memory; but compute distinct values.
10108     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10109   };
10110 
10111   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10112   // two different instructions with the same value. Check for this case.
10113   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10114     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10115       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10116         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10117           if (ComputesEqualValues(AI, BI))
10118             return true;
10119 
10120   // Otherwise assume they may have a different value.
10121   return false;
10122 }
10123 
10124 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10125                                            const SCEV *&LHS, const SCEV *&RHS,
10126                                            unsigned Depth,
10127                                            bool ControllingFiniteLoop) {
10128   bool Changed = false;
10129   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10130   // '0 != 0'.
10131   auto TrivialCase = [&](bool TriviallyTrue) {
10132     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10133     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10134     return true;
10135   };
10136   // If we hit the max recursion limit bail out.
10137   if (Depth >= 3)
10138     return false;
10139 
10140   // Canonicalize a constant to the right side.
10141   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10142     // Check for both operands constant.
10143     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10144       if (ConstantExpr::getICmp(Pred,
10145                                 LHSC->getValue(),
10146                                 RHSC->getValue())->isNullValue())
10147         return TrivialCase(false);
10148       else
10149         return TrivialCase(true);
10150     }
10151     // Otherwise swap the operands to put the constant on the right.
10152     std::swap(LHS, RHS);
10153     Pred = ICmpInst::getSwappedPredicate(Pred);
10154     Changed = true;
10155   }
10156 
10157   // If we're comparing an addrec with a value which is loop-invariant in the
10158   // addrec's loop, put the addrec on the left. Also make a dominance check,
10159   // as both operands could be addrecs loop-invariant in each other's loop.
10160   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10161     const Loop *L = AR->getLoop();
10162     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10163       std::swap(LHS, RHS);
10164       Pred = ICmpInst::getSwappedPredicate(Pred);
10165       Changed = true;
10166     }
10167   }
10168 
10169   // If there's a constant operand, canonicalize comparisons with boundary
10170   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10171   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10172     const APInt &RA = RC->getAPInt();
10173 
10174     bool SimplifiedByConstantRange = false;
10175 
10176     if (!ICmpInst::isEquality(Pred)) {
10177       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10178       if (ExactCR.isFullSet())
10179         return TrivialCase(true);
10180       else if (ExactCR.isEmptySet())
10181         return TrivialCase(false);
10182 
10183       APInt NewRHS;
10184       CmpInst::Predicate NewPred;
10185       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10186           ICmpInst::isEquality(NewPred)) {
10187         // We were able to convert an inequality to an equality.
10188         Pred = NewPred;
10189         RHS = getConstant(NewRHS);
10190         Changed = SimplifiedByConstantRange = true;
10191       }
10192     }
10193 
10194     if (!SimplifiedByConstantRange) {
10195       switch (Pred) {
10196       default:
10197         break;
10198       case ICmpInst::ICMP_EQ:
10199       case ICmpInst::ICMP_NE:
10200         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10201         if (!RA)
10202           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10203             if (const SCEVMulExpr *ME =
10204                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10205               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10206                   ME->getOperand(0)->isAllOnesValue()) {
10207                 RHS = AE->getOperand(1);
10208                 LHS = ME->getOperand(1);
10209                 Changed = true;
10210               }
10211         break;
10212 
10213 
10214         // The "Should have been caught earlier!" messages refer to the fact
10215         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10216         // should have fired on the corresponding cases, and canonicalized the
10217         // check to trivial case.
10218 
10219       case ICmpInst::ICMP_UGE:
10220         assert(!RA.isMinValue() && "Should have been caught earlier!");
10221         Pred = ICmpInst::ICMP_UGT;
10222         RHS = getConstant(RA - 1);
10223         Changed = true;
10224         break;
10225       case ICmpInst::ICMP_ULE:
10226         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10227         Pred = ICmpInst::ICMP_ULT;
10228         RHS = getConstant(RA + 1);
10229         Changed = true;
10230         break;
10231       case ICmpInst::ICMP_SGE:
10232         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10233         Pred = ICmpInst::ICMP_SGT;
10234         RHS = getConstant(RA - 1);
10235         Changed = true;
10236         break;
10237       case ICmpInst::ICMP_SLE:
10238         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10239         Pred = ICmpInst::ICMP_SLT;
10240         RHS = getConstant(RA + 1);
10241         Changed = true;
10242         break;
10243       }
10244     }
10245   }
10246 
10247   // Check for obvious equality.
10248   if (HasSameValue(LHS, RHS)) {
10249     if (ICmpInst::isTrueWhenEqual(Pred))
10250       return TrivialCase(true);
10251     if (ICmpInst::isFalseWhenEqual(Pred))
10252       return TrivialCase(false);
10253   }
10254 
10255   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10256   // adding or subtracting 1 from one of the operands. This can be done for
10257   // one of two reasons:
10258   // 1) The range of the RHS does not include the (signed/unsigned) boundaries
10259   // 2) The loop is finite, with this comparison controlling the exit. Since the
10260   // loop is finite, the bound cannot include the corresponding boundary
10261   // (otherwise it would loop forever).
10262   switch (Pred) {
10263   case ICmpInst::ICMP_SLE:
10264     if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
10265       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10266                        SCEV::FlagNSW);
10267       Pred = ICmpInst::ICMP_SLT;
10268       Changed = true;
10269     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10270       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10271                        SCEV::FlagNSW);
10272       Pred = ICmpInst::ICMP_SLT;
10273       Changed = true;
10274     }
10275     break;
10276   case ICmpInst::ICMP_SGE:
10277     if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
10278       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10279                        SCEV::FlagNSW);
10280       Pred = ICmpInst::ICMP_SGT;
10281       Changed = true;
10282     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10283       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10284                        SCEV::FlagNSW);
10285       Pred = ICmpInst::ICMP_SGT;
10286       Changed = true;
10287     }
10288     break;
10289   case ICmpInst::ICMP_ULE:
10290     if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
10291       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10292                        SCEV::FlagNUW);
10293       Pred = ICmpInst::ICMP_ULT;
10294       Changed = true;
10295     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10296       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10297       Pred = ICmpInst::ICMP_ULT;
10298       Changed = true;
10299     }
10300     break;
10301   case ICmpInst::ICMP_UGE:
10302     if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
10303       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10304       Pred = ICmpInst::ICMP_UGT;
10305       Changed = true;
10306     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10307       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10308                        SCEV::FlagNUW);
10309       Pred = ICmpInst::ICMP_UGT;
10310       Changed = true;
10311     }
10312     break;
10313   default:
10314     break;
10315   }
10316 
10317   // TODO: More simplifications are possible here.
10318 
10319   // Recursively simplify until we either hit a recursion limit or nothing
10320   // changes.
10321   if (Changed)
10322     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
10323                                 ControllingFiniteLoop);
10324 
10325   return Changed;
10326 }
10327 
10328 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10329   return getSignedRangeMax(S).isNegative();
10330 }
10331 
10332 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10333   return getSignedRangeMin(S).isStrictlyPositive();
10334 }
10335 
10336 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10337   return !getSignedRangeMin(S).isNegative();
10338 }
10339 
10340 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10341   return !getSignedRangeMax(S).isStrictlyPositive();
10342 }
10343 
10344 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10345   return getUnsignedRangeMin(S) != 0;
10346 }
10347 
10348 std::pair<const SCEV *, const SCEV *>
10349 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10350   // Compute SCEV on entry of loop L.
10351   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10352   if (Start == getCouldNotCompute())
10353     return { Start, Start };
10354   // Compute post increment SCEV for loop L.
10355   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10356   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10357   return { Start, PostInc };
10358 }
10359 
10360 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10361                                           const SCEV *LHS, const SCEV *RHS) {
10362   // First collect all loops.
10363   SmallPtrSet<const Loop *, 8> LoopsUsed;
10364   getUsedLoops(LHS, LoopsUsed);
10365   getUsedLoops(RHS, LoopsUsed);
10366 
10367   if (LoopsUsed.empty())
10368     return false;
10369 
10370   // Domination relationship must be a linear order on collected loops.
10371 #ifndef NDEBUG
10372   for (auto *L1 : LoopsUsed)
10373     for (auto *L2 : LoopsUsed)
10374       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10375               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10376              "Domination relationship is not a linear order");
10377 #endif
10378 
10379   const Loop *MDL =
10380       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10381                         [&](const Loop *L1, const Loop *L2) {
10382          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10383        });
10384 
10385   // Get init and post increment value for LHS.
10386   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10387   // if LHS contains unknown non-invariant SCEV then bail out.
10388   if (SplitLHS.first == getCouldNotCompute())
10389     return false;
10390   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10391   // Get init and post increment value for RHS.
10392   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10393   // if RHS contains unknown non-invariant SCEV then bail out.
10394   if (SplitRHS.first == getCouldNotCompute())
10395     return false;
10396   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10397   // It is possible that init SCEV contains an invariant load but it does
10398   // not dominate MDL and is not available at MDL loop entry, so we should
10399   // check it here.
10400   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10401       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10402     return false;
10403 
10404   // It seems backedge guard check is faster than entry one so in some cases
10405   // it can speed up whole estimation by short circuit
10406   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10407                                      SplitRHS.second) &&
10408          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10409 }
10410 
10411 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10412                                        const SCEV *LHS, const SCEV *RHS) {
10413   // Canonicalize the inputs first.
10414   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10415 
10416   if (isKnownViaInduction(Pred, LHS, RHS))
10417     return true;
10418 
10419   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10420     return true;
10421 
10422   // Otherwise see what can be done with some simple reasoning.
10423   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10424 }
10425 
10426 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10427                                                   const SCEV *LHS,
10428                                                   const SCEV *RHS) {
10429   if (isKnownPredicate(Pred, LHS, RHS))
10430     return true;
10431   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10432     return false;
10433   return None;
10434 }
10435 
10436 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10437                                          const SCEV *LHS, const SCEV *RHS,
10438                                          const Instruction *CtxI) {
10439   // TODO: Analyze guards and assumes from Context's block.
10440   return isKnownPredicate(Pred, LHS, RHS) ||
10441          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10442 }
10443 
10444 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10445                                                     const SCEV *LHS,
10446                                                     const SCEV *RHS,
10447                                                     const Instruction *CtxI) {
10448   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10449   if (KnownWithoutContext)
10450     return KnownWithoutContext;
10451 
10452   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10453     return true;
10454   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10455                                           ICmpInst::getInversePredicate(Pred),
10456                                           LHS, RHS))
10457     return false;
10458   return None;
10459 }
10460 
10461 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10462                                               const SCEVAddRecExpr *LHS,
10463                                               const SCEV *RHS) {
10464   const Loop *L = LHS->getLoop();
10465   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10466          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10467 }
10468 
10469 Optional<ScalarEvolution::MonotonicPredicateType>
10470 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10471                                            ICmpInst::Predicate Pred) {
10472   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10473 
10474 #ifndef NDEBUG
10475   // Verify an invariant: inverting the predicate should turn a monotonically
10476   // increasing change to a monotonically decreasing one, and vice versa.
10477   if (Result) {
10478     auto ResultSwapped =
10479         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10480 
10481     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10482     assert(ResultSwapped.getValue() != Result.getValue() &&
10483            "monotonicity should flip as we flip the predicate");
10484   }
10485 #endif
10486 
10487   return Result;
10488 }
10489 
10490 Optional<ScalarEvolution::MonotonicPredicateType>
10491 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10492                                                ICmpInst::Predicate Pred) {
10493   // A zero step value for LHS means the induction variable is essentially a
10494   // loop invariant value. We don't really depend on the predicate actually
10495   // flipping from false to true (for increasing predicates, and the other way
10496   // around for decreasing predicates), all we care about is that *if* the
10497   // predicate changes then it only changes from false to true.
10498   //
10499   // A zero step value in itself is not very useful, but there may be places
10500   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10501   // as general as possible.
10502 
10503   // Only handle LE/LT/GE/GT predicates.
10504   if (!ICmpInst::isRelational(Pred))
10505     return None;
10506 
10507   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10508   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10509          "Should be greater or less!");
10510 
10511   // Check that AR does not wrap.
10512   if (ICmpInst::isUnsigned(Pred)) {
10513     if (!LHS->hasNoUnsignedWrap())
10514       return None;
10515     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10516   } else {
10517     assert(ICmpInst::isSigned(Pred) &&
10518            "Relational predicate is either signed or unsigned!");
10519     if (!LHS->hasNoSignedWrap())
10520       return None;
10521 
10522     const SCEV *Step = LHS->getStepRecurrence(*this);
10523 
10524     if (isKnownNonNegative(Step))
10525       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10526 
10527     if (isKnownNonPositive(Step))
10528       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10529 
10530     return None;
10531   }
10532 }
10533 
10534 Optional<ScalarEvolution::LoopInvariantPredicate>
10535 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10536                                            const SCEV *LHS, const SCEV *RHS,
10537                                            const Loop *L) {
10538 
10539   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10540   if (!isLoopInvariant(RHS, L)) {
10541     if (!isLoopInvariant(LHS, L))
10542       return None;
10543 
10544     std::swap(LHS, RHS);
10545     Pred = ICmpInst::getSwappedPredicate(Pred);
10546   }
10547 
10548   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10549   if (!ArLHS || ArLHS->getLoop() != L)
10550     return None;
10551 
10552   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10553   if (!MonotonicType)
10554     return None;
10555   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10556   // true as the loop iterates, and the backedge is control dependent on
10557   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10558   //
10559   //   * if the predicate was false in the first iteration then the predicate
10560   //     is never evaluated again, since the loop exits without taking the
10561   //     backedge.
10562   //   * if the predicate was true in the first iteration then it will
10563   //     continue to be true for all future iterations since it is
10564   //     monotonically increasing.
10565   //
10566   // For both the above possibilities, we can replace the loop varying
10567   // predicate with its value on the first iteration of the loop (which is
10568   // loop invariant).
10569   //
10570   // A similar reasoning applies for a monotonically decreasing predicate, by
10571   // replacing true with false and false with true in the above two bullets.
10572   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10573   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10574 
10575   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10576     return None;
10577 
10578   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10579 }
10580 
10581 Optional<ScalarEvolution::LoopInvariantPredicate>
10582 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10583     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10584     const Instruction *CtxI, const SCEV *MaxIter) {
10585   // Try to prove the following set of facts:
10586   // - The predicate is monotonic in the iteration space.
10587   // - If the check does not fail on the 1st iteration:
10588   //   - No overflow will happen during first MaxIter iterations;
10589   //   - It will not fail on the MaxIter'th iteration.
10590   // If the check does fail on the 1st iteration, we leave the loop and no
10591   // other checks matter.
10592 
10593   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10594   if (!isLoopInvariant(RHS, L)) {
10595     if (!isLoopInvariant(LHS, L))
10596       return None;
10597 
10598     std::swap(LHS, RHS);
10599     Pred = ICmpInst::getSwappedPredicate(Pred);
10600   }
10601 
10602   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10603   if (!AR || AR->getLoop() != L)
10604     return None;
10605 
10606   // The predicate must be relational (i.e. <, <=, >=, >).
10607   if (!ICmpInst::isRelational(Pred))
10608     return None;
10609 
10610   // TODO: Support steps other than +/- 1.
10611   const SCEV *Step = AR->getStepRecurrence(*this);
10612   auto *One = getOne(Step->getType());
10613   auto *MinusOne = getNegativeSCEV(One);
10614   if (Step != One && Step != MinusOne)
10615     return None;
10616 
10617   // Type mismatch here means that MaxIter is potentially larger than max
10618   // unsigned value in start type, which mean we cannot prove no wrap for the
10619   // indvar.
10620   if (AR->getType() != MaxIter->getType())
10621     return None;
10622 
10623   // Value of IV on suggested last iteration.
10624   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10625   // Does it still meet the requirement?
10626   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10627     return None;
10628   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10629   // not exceed max unsigned value of this type), this effectively proves
10630   // that there is no wrap during the iteration. To prove that there is no
10631   // signed/unsigned wrap, we need to check that
10632   // Start <= Last for step = 1 or Start >= Last for step = -1.
10633   ICmpInst::Predicate NoOverflowPred =
10634       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10635   if (Step == MinusOne)
10636     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10637   const SCEV *Start = AR->getStart();
10638   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10639     return None;
10640 
10641   // Everything is fine.
10642   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10643 }
10644 
10645 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10646     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10647   if (HasSameValue(LHS, RHS))
10648     return ICmpInst::isTrueWhenEqual(Pred);
10649 
10650   // This code is split out from isKnownPredicate because it is called from
10651   // within isLoopEntryGuardedByCond.
10652 
10653   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10654                          const ConstantRange &RangeRHS) {
10655     return RangeLHS.icmp(Pred, RangeRHS);
10656   };
10657 
10658   // The check at the top of the function catches the case where the values are
10659   // known to be equal.
10660   if (Pred == CmpInst::ICMP_EQ)
10661     return false;
10662 
10663   if (Pred == CmpInst::ICMP_NE) {
10664     auto SL = getSignedRange(LHS);
10665     auto SR = getSignedRange(RHS);
10666     if (CheckRanges(SL, SR))
10667       return true;
10668     auto UL = getUnsignedRange(LHS);
10669     auto UR = getUnsignedRange(RHS);
10670     if (CheckRanges(UL, UR))
10671       return true;
10672     auto *Diff = getMinusSCEV(LHS, RHS);
10673     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10674   }
10675 
10676   if (CmpInst::isSigned(Pred)) {
10677     auto SL = getSignedRange(LHS);
10678     auto SR = getSignedRange(RHS);
10679     return CheckRanges(SL, SR);
10680   }
10681 
10682   auto UL = getUnsignedRange(LHS);
10683   auto UR = getUnsignedRange(RHS);
10684   return CheckRanges(UL, UR);
10685 }
10686 
10687 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10688                                                     const SCEV *LHS,
10689                                                     const SCEV *RHS) {
10690   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10691   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10692   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10693   // OutC1 and OutC2.
10694   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10695                                       APInt &OutC1, APInt &OutC2,
10696                                       SCEV::NoWrapFlags ExpectedFlags) {
10697     const SCEV *XNonConstOp, *XConstOp;
10698     const SCEV *YNonConstOp, *YConstOp;
10699     SCEV::NoWrapFlags XFlagsPresent;
10700     SCEV::NoWrapFlags YFlagsPresent;
10701 
10702     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10703       XConstOp = getZero(X->getType());
10704       XNonConstOp = X;
10705       XFlagsPresent = ExpectedFlags;
10706     }
10707     if (!isa<SCEVConstant>(XConstOp) ||
10708         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10709       return false;
10710 
10711     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10712       YConstOp = getZero(Y->getType());
10713       YNonConstOp = Y;
10714       YFlagsPresent = ExpectedFlags;
10715     }
10716 
10717     if (!isa<SCEVConstant>(YConstOp) ||
10718         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10719       return false;
10720 
10721     if (YNonConstOp != XNonConstOp)
10722       return false;
10723 
10724     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10725     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10726 
10727     return true;
10728   };
10729 
10730   APInt C1;
10731   APInt C2;
10732 
10733   switch (Pred) {
10734   default:
10735     break;
10736 
10737   case ICmpInst::ICMP_SGE:
10738     std::swap(LHS, RHS);
10739     LLVM_FALLTHROUGH;
10740   case ICmpInst::ICMP_SLE:
10741     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10742     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10743       return true;
10744 
10745     break;
10746 
10747   case ICmpInst::ICMP_SGT:
10748     std::swap(LHS, RHS);
10749     LLVM_FALLTHROUGH;
10750   case ICmpInst::ICMP_SLT:
10751     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10752     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10753       return true;
10754 
10755     break;
10756 
10757   case ICmpInst::ICMP_UGE:
10758     std::swap(LHS, RHS);
10759     LLVM_FALLTHROUGH;
10760   case ICmpInst::ICMP_ULE:
10761     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10762     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10763       return true;
10764 
10765     break;
10766 
10767   case ICmpInst::ICMP_UGT:
10768     std::swap(LHS, RHS);
10769     LLVM_FALLTHROUGH;
10770   case ICmpInst::ICMP_ULT:
10771     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10772     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10773       return true;
10774     break;
10775   }
10776 
10777   return false;
10778 }
10779 
10780 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10781                                                    const SCEV *LHS,
10782                                                    const SCEV *RHS) {
10783   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10784     return false;
10785 
10786   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10787   // the stack can result in exponential time complexity.
10788   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10789 
10790   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10791   //
10792   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10793   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10794   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10795   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10796   // use isKnownPredicate later if needed.
10797   return isKnownNonNegative(RHS) &&
10798          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10799          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10800 }
10801 
10802 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10803                                         ICmpInst::Predicate Pred,
10804                                         const SCEV *LHS, const SCEV *RHS) {
10805   // No need to even try if we know the module has no guards.
10806   if (!HasGuards)
10807     return false;
10808 
10809   return any_of(*BB, [&](const Instruction &I) {
10810     using namespace llvm::PatternMatch;
10811 
10812     Value *Condition;
10813     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10814                          m_Value(Condition))) &&
10815            isImpliedCond(Pred, LHS, RHS, Condition, false);
10816   });
10817 }
10818 
10819 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10820 /// protected by a conditional between LHS and RHS.  This is used to
10821 /// to eliminate casts.
10822 bool
10823 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10824                                              ICmpInst::Predicate Pred,
10825                                              const SCEV *LHS, const SCEV *RHS) {
10826   // Interpret a null as meaning no loop, where there is obviously no guard
10827   // (interprocedural conditions notwithstanding).
10828   if (!L) return true;
10829 
10830   if (VerifyIR)
10831     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10832            "This cannot be done on broken IR!");
10833 
10834 
10835   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10836     return true;
10837 
10838   BasicBlock *Latch = L->getLoopLatch();
10839   if (!Latch)
10840     return false;
10841 
10842   BranchInst *LoopContinuePredicate =
10843     dyn_cast<BranchInst>(Latch->getTerminator());
10844   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10845       isImpliedCond(Pred, LHS, RHS,
10846                     LoopContinuePredicate->getCondition(),
10847                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10848     return true;
10849 
10850   // We don't want more than one activation of the following loops on the stack
10851   // -- that can lead to O(n!) time complexity.
10852   if (WalkingBEDominatingConds)
10853     return false;
10854 
10855   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10856 
10857   // See if we can exploit a trip count to prove the predicate.
10858   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10859   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10860   if (LatchBECount != getCouldNotCompute()) {
10861     // We know that Latch branches back to the loop header exactly
10862     // LatchBECount times.  This means the backdege condition at Latch is
10863     // equivalent to  "{0,+,1} u< LatchBECount".
10864     Type *Ty = LatchBECount->getType();
10865     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10866     const SCEV *LoopCounter =
10867       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10868     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10869                       LatchBECount))
10870       return true;
10871   }
10872 
10873   // Check conditions due to any @llvm.assume intrinsics.
10874   for (auto &AssumeVH : AC.assumptions()) {
10875     if (!AssumeVH)
10876       continue;
10877     auto *CI = cast<CallInst>(AssumeVH);
10878     if (!DT.dominates(CI, Latch->getTerminator()))
10879       continue;
10880 
10881     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10882       return true;
10883   }
10884 
10885   // If the loop is not reachable from the entry block, we risk running into an
10886   // infinite loop as we walk up into the dom tree.  These loops do not matter
10887   // anyway, so we just return a conservative answer when we see them.
10888   if (!DT.isReachableFromEntry(L->getHeader()))
10889     return false;
10890 
10891   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10892     return true;
10893 
10894   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10895        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10896     assert(DTN && "should reach the loop header before reaching the root!");
10897 
10898     BasicBlock *BB = DTN->getBlock();
10899     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10900       return true;
10901 
10902     BasicBlock *PBB = BB->getSinglePredecessor();
10903     if (!PBB)
10904       continue;
10905 
10906     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10907     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10908       continue;
10909 
10910     Value *Condition = ContinuePredicate->getCondition();
10911 
10912     // If we have an edge `E` within the loop body that dominates the only
10913     // latch, the condition guarding `E` also guards the backedge.  This
10914     // reasoning works only for loops with a single latch.
10915 
10916     BasicBlockEdge DominatingEdge(PBB, BB);
10917     if (DominatingEdge.isSingleEdge()) {
10918       // We're constructively (and conservatively) enumerating edges within the
10919       // loop body that dominate the latch.  The dominator tree better agree
10920       // with us on this:
10921       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10922 
10923       if (isImpliedCond(Pred, LHS, RHS, Condition,
10924                         BB != ContinuePredicate->getSuccessor(0)))
10925         return true;
10926     }
10927   }
10928 
10929   return false;
10930 }
10931 
10932 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10933                                                      ICmpInst::Predicate Pred,
10934                                                      const SCEV *LHS,
10935                                                      const SCEV *RHS) {
10936   if (VerifyIR)
10937     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10938            "This cannot be done on broken IR!");
10939 
10940   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10941   // the facts (a >= b && a != b) separately. A typical situation is when the
10942   // non-strict comparison is known from ranges and non-equality is known from
10943   // dominating predicates. If we are proving strict comparison, we always try
10944   // to prove non-equality and non-strict comparison separately.
10945   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10946   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10947   bool ProvedNonStrictComparison = false;
10948   bool ProvedNonEquality = false;
10949 
10950   auto SplitAndProve =
10951     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10952     if (!ProvedNonStrictComparison)
10953       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10954     if (!ProvedNonEquality)
10955       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10956     if (ProvedNonStrictComparison && ProvedNonEquality)
10957       return true;
10958     return false;
10959   };
10960 
10961   if (ProvingStrictComparison) {
10962     auto ProofFn = [&](ICmpInst::Predicate P) {
10963       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10964     };
10965     if (SplitAndProve(ProofFn))
10966       return true;
10967   }
10968 
10969   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10970   auto ProveViaGuard = [&](const BasicBlock *Block) {
10971     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10972       return true;
10973     if (ProvingStrictComparison) {
10974       auto ProofFn = [&](ICmpInst::Predicate P) {
10975         return isImpliedViaGuard(Block, P, LHS, RHS);
10976       };
10977       if (SplitAndProve(ProofFn))
10978         return true;
10979     }
10980     return false;
10981   };
10982 
10983   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10984   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10985     const Instruction *CtxI = &BB->front();
10986     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10987       return true;
10988     if (ProvingStrictComparison) {
10989       auto ProofFn = [&](ICmpInst::Predicate P) {
10990         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10991       };
10992       if (SplitAndProve(ProofFn))
10993         return true;
10994     }
10995     return false;
10996   };
10997 
10998   // Starting at the block's predecessor, climb up the predecessor chain, as long
10999   // as there are predecessors that can be found that have unique successors
11000   // leading to the original block.
11001   const Loop *ContainingLoop = LI.getLoopFor(BB);
11002   const BasicBlock *PredBB;
11003   if (ContainingLoop && ContainingLoop->getHeader() == BB)
11004     PredBB = ContainingLoop->getLoopPredecessor();
11005   else
11006     PredBB = BB->getSinglePredecessor();
11007   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11008        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11009     if (ProveViaGuard(Pair.first))
11010       return true;
11011 
11012     const BranchInst *LoopEntryPredicate =
11013         dyn_cast<BranchInst>(Pair.first->getTerminator());
11014     if (!LoopEntryPredicate ||
11015         LoopEntryPredicate->isUnconditional())
11016       continue;
11017 
11018     if (ProveViaCond(LoopEntryPredicate->getCondition(),
11019                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
11020       return true;
11021   }
11022 
11023   // Check conditions due to any @llvm.assume intrinsics.
11024   for (auto &AssumeVH : AC.assumptions()) {
11025     if (!AssumeVH)
11026       continue;
11027     auto *CI = cast<CallInst>(AssumeVH);
11028     if (!DT.dominates(CI, BB))
11029       continue;
11030 
11031     if (ProveViaCond(CI->getArgOperand(0), false))
11032       return true;
11033   }
11034 
11035   return false;
11036 }
11037 
11038 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11039                                                ICmpInst::Predicate Pred,
11040                                                const SCEV *LHS,
11041                                                const SCEV *RHS) {
11042   // Interpret a null as meaning no loop, where there is obviously no guard
11043   // (interprocedural conditions notwithstanding).
11044   if (!L)
11045     return false;
11046 
11047   // Both LHS and RHS must be available at loop entry.
11048   assert(isAvailableAtLoopEntry(LHS, L) &&
11049          "LHS is not available at Loop Entry");
11050   assert(isAvailableAtLoopEntry(RHS, L) &&
11051          "RHS is not available at Loop Entry");
11052 
11053   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11054     return true;
11055 
11056   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11057 }
11058 
11059 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11060                                     const SCEV *RHS,
11061                                     const Value *FoundCondValue, bool Inverse,
11062                                     const Instruction *CtxI) {
11063   // False conditions implies anything. Do not bother analyzing it further.
11064   if (FoundCondValue ==
11065       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11066     return true;
11067 
11068   if (!PendingLoopPredicates.insert(FoundCondValue).second)
11069     return false;
11070 
11071   auto ClearOnExit =
11072       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11073 
11074   // Recursively handle And and Or conditions.
11075   const Value *Op0, *Op1;
11076   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11077     if (!Inverse)
11078       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11079              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11080   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11081     if (Inverse)
11082       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11083              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11084   }
11085 
11086   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11087   if (!ICI) return false;
11088 
11089   // Now that we found a conditional branch that dominates the loop or controls
11090   // the loop latch. Check to see if it is the comparison we are looking for.
11091   ICmpInst::Predicate FoundPred;
11092   if (Inverse)
11093     FoundPred = ICI->getInversePredicate();
11094   else
11095     FoundPred = ICI->getPredicate();
11096 
11097   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11098   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11099 
11100   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11101 }
11102 
11103 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11104                                     const SCEV *RHS,
11105                                     ICmpInst::Predicate FoundPred,
11106                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
11107                                     const Instruction *CtxI) {
11108   // Balance the types.
11109   if (getTypeSizeInBits(LHS->getType()) <
11110       getTypeSizeInBits(FoundLHS->getType())) {
11111     // For unsigned and equality predicates, try to prove that both found
11112     // operands fit into narrow unsigned range. If so, try to prove facts in
11113     // narrow types.
11114     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11115         !FoundRHS->getType()->isPointerTy()) {
11116       auto *NarrowType = LHS->getType();
11117       auto *WideType = FoundLHS->getType();
11118       auto BitWidth = getTypeSizeInBits(NarrowType);
11119       const SCEV *MaxValue = getZeroExtendExpr(
11120           getConstant(APInt::getMaxValue(BitWidth)), WideType);
11121       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11122                                           MaxValue) &&
11123           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11124                                           MaxValue)) {
11125         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11126         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11127         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11128                                        TruncFoundRHS, CtxI))
11129           return true;
11130       }
11131     }
11132 
11133     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11134       return false;
11135     if (CmpInst::isSigned(Pred)) {
11136       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11137       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11138     } else {
11139       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11140       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11141     }
11142   } else if (getTypeSizeInBits(LHS->getType()) >
11143       getTypeSizeInBits(FoundLHS->getType())) {
11144     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11145       return false;
11146     if (CmpInst::isSigned(FoundPred)) {
11147       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11148       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11149     } else {
11150       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11151       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11152     }
11153   }
11154   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11155                                     FoundRHS, CtxI);
11156 }
11157 
11158 bool ScalarEvolution::isImpliedCondBalancedTypes(
11159     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11160     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11161     const Instruction *CtxI) {
11162   assert(getTypeSizeInBits(LHS->getType()) ==
11163              getTypeSizeInBits(FoundLHS->getType()) &&
11164          "Types should be balanced!");
11165   // Canonicalize the query to match the way instcombine will have
11166   // canonicalized the comparison.
11167   if (SimplifyICmpOperands(Pred, LHS, RHS))
11168     if (LHS == RHS)
11169       return CmpInst::isTrueWhenEqual(Pred);
11170   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11171     if (FoundLHS == FoundRHS)
11172       return CmpInst::isFalseWhenEqual(FoundPred);
11173 
11174   // Check to see if we can make the LHS or RHS match.
11175   if (LHS == FoundRHS || RHS == FoundLHS) {
11176     if (isa<SCEVConstant>(RHS)) {
11177       std::swap(FoundLHS, FoundRHS);
11178       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11179     } else {
11180       std::swap(LHS, RHS);
11181       Pred = ICmpInst::getSwappedPredicate(Pred);
11182     }
11183   }
11184 
11185   // Check whether the found predicate is the same as the desired predicate.
11186   if (FoundPred == Pred)
11187     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11188 
11189   // Check whether swapping the found predicate makes it the same as the
11190   // desired predicate.
11191   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11192     // We can write the implication
11193     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11194     // using one of the following ways:
11195     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11196     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11197     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11198     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11199     // Forms 1. and 2. require swapping the operands of one condition. Don't
11200     // do this if it would break canonical constant/addrec ordering.
11201     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11202       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11203                                    CtxI);
11204     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11205       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11206 
11207     // There's no clear preference between forms 3. and 4., try both.  Avoid
11208     // forming getNotSCEV of pointer values as the resulting subtract is
11209     // not legal.
11210     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11211         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11212                               FoundLHS, FoundRHS, CtxI))
11213       return true;
11214 
11215     if (!FoundLHS->getType()->isPointerTy() &&
11216         !FoundRHS->getType()->isPointerTy() &&
11217         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11218                               getNotSCEV(FoundRHS), CtxI))
11219       return true;
11220 
11221     return false;
11222   }
11223 
11224   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11225                                    CmpInst::Predicate P2) {
11226     assert(P1 != P2 && "Handled earlier!");
11227     return CmpInst::isRelational(P2) &&
11228            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11229   };
11230   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11231     // Unsigned comparison is the same as signed comparison when both the
11232     // operands are non-negative or negative.
11233     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11234         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11235       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11236     // Create local copies that we can freely swap and canonicalize our
11237     // conditions to "le/lt".
11238     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11239     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11240                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11241     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11242       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11243       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11244       std::swap(CanonicalLHS, CanonicalRHS);
11245       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11246     }
11247     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11248            "Must be!");
11249     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11250             ICmpInst::isLE(CanonicalFoundPred)) &&
11251            "Must be!");
11252     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11253       // Use implication:
11254       // x <u y && y >=s 0 --> x <s y.
11255       // If we can prove the left part, the right part is also proven.
11256       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11257                                    CanonicalRHS, CanonicalFoundLHS,
11258                                    CanonicalFoundRHS);
11259     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11260       // Use implication:
11261       // x <s y && y <s 0 --> x <u y.
11262       // If we can prove the left part, the right part is also proven.
11263       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11264                                    CanonicalRHS, CanonicalFoundLHS,
11265                                    CanonicalFoundRHS);
11266   }
11267 
11268   // Check if we can make progress by sharpening ranges.
11269   if (FoundPred == ICmpInst::ICMP_NE &&
11270       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11271 
11272     const SCEVConstant *C = nullptr;
11273     const SCEV *V = nullptr;
11274 
11275     if (isa<SCEVConstant>(FoundLHS)) {
11276       C = cast<SCEVConstant>(FoundLHS);
11277       V = FoundRHS;
11278     } else {
11279       C = cast<SCEVConstant>(FoundRHS);
11280       V = FoundLHS;
11281     }
11282 
11283     // The guarding predicate tells us that C != V. If the known range
11284     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11285     // range we consider has to correspond to same signedness as the
11286     // predicate we're interested in folding.
11287 
11288     APInt Min = ICmpInst::isSigned(Pred) ?
11289         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11290 
11291     if (Min == C->getAPInt()) {
11292       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11293       // This is true even if (Min + 1) wraps around -- in case of
11294       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11295 
11296       APInt SharperMin = Min + 1;
11297 
11298       switch (Pred) {
11299         case ICmpInst::ICMP_SGE:
11300         case ICmpInst::ICMP_UGE:
11301           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11302           // RHS, we're done.
11303           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11304                                     CtxI))
11305             return true;
11306           LLVM_FALLTHROUGH;
11307 
11308         case ICmpInst::ICMP_SGT:
11309         case ICmpInst::ICMP_UGT:
11310           // We know from the range information that (V `Pred` Min ||
11311           // V == Min).  We know from the guarding condition that !(V
11312           // == Min).  This gives us
11313           //
11314           //       V `Pred` Min || V == Min && !(V == Min)
11315           //   =>  V `Pred` Min
11316           //
11317           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11318 
11319           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11320             return true;
11321           break;
11322 
11323         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11324         case ICmpInst::ICMP_SLE:
11325         case ICmpInst::ICMP_ULE:
11326           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11327                                     LHS, V, getConstant(SharperMin), CtxI))
11328             return true;
11329           LLVM_FALLTHROUGH;
11330 
11331         case ICmpInst::ICMP_SLT:
11332         case ICmpInst::ICMP_ULT:
11333           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11334                                     LHS, V, getConstant(Min), CtxI))
11335             return true;
11336           break;
11337 
11338         default:
11339           // No change
11340           break;
11341       }
11342     }
11343   }
11344 
11345   // Check whether the actual condition is beyond sufficient.
11346   if (FoundPred == ICmpInst::ICMP_EQ)
11347     if (ICmpInst::isTrueWhenEqual(Pred))
11348       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11349         return true;
11350   if (Pred == ICmpInst::ICMP_NE)
11351     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11352       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11353         return true;
11354 
11355   // Otherwise assume the worst.
11356   return false;
11357 }
11358 
11359 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11360                                      const SCEV *&L, const SCEV *&R,
11361                                      SCEV::NoWrapFlags &Flags) {
11362   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11363   if (!AE || AE->getNumOperands() != 2)
11364     return false;
11365 
11366   L = AE->getOperand(0);
11367   R = AE->getOperand(1);
11368   Flags = AE->getNoWrapFlags();
11369   return true;
11370 }
11371 
11372 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
11373                                                            const SCEV *Less) {
11374   // We avoid subtracting expressions here because this function is usually
11375   // fairly deep in the call stack (i.e. is called many times).
11376 
11377   // X - X = 0.
11378   if (More == Less)
11379     return APInt(getTypeSizeInBits(More->getType()), 0);
11380 
11381   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11382     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11383     const auto *MAR = cast<SCEVAddRecExpr>(More);
11384 
11385     if (LAR->getLoop() != MAR->getLoop())
11386       return None;
11387 
11388     // We look at affine expressions only; not for correctness but to keep
11389     // getStepRecurrence cheap.
11390     if (!LAR->isAffine() || !MAR->isAffine())
11391       return None;
11392 
11393     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11394       return None;
11395 
11396     Less = LAR->getStart();
11397     More = MAR->getStart();
11398 
11399     // fall through
11400   }
11401 
11402   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11403     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11404     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11405     return M - L;
11406   }
11407 
11408   SCEV::NoWrapFlags Flags;
11409   const SCEV *LLess = nullptr, *RLess = nullptr;
11410   const SCEV *LMore = nullptr, *RMore = nullptr;
11411   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11412   // Compare (X + C1) vs X.
11413   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11414     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11415       if (RLess == More)
11416         return -(C1->getAPInt());
11417 
11418   // Compare X vs (X + C2).
11419   if (splitBinaryAdd(More, LMore, RMore, Flags))
11420     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11421       if (RMore == Less)
11422         return C2->getAPInt();
11423 
11424   // Compare (X + C1) vs (X + C2).
11425   if (C1 && C2 && RLess == RMore)
11426     return C2->getAPInt() - C1->getAPInt();
11427 
11428   return None;
11429 }
11430 
11431 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11432     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11433     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11434   // Try to recognize the following pattern:
11435   //
11436   //   FoundRHS = ...
11437   // ...
11438   // loop:
11439   //   FoundLHS = {Start,+,W}
11440   // context_bb: // Basic block from the same loop
11441   //   known(Pred, FoundLHS, FoundRHS)
11442   //
11443   // If some predicate is known in the context of a loop, it is also known on
11444   // each iteration of this loop, including the first iteration. Therefore, in
11445   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11446   // prove the original pred using this fact.
11447   if (!CtxI)
11448     return false;
11449   const BasicBlock *ContextBB = CtxI->getParent();
11450   // Make sure AR varies in the context block.
11451   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11452     const Loop *L = AR->getLoop();
11453     // Make sure that context belongs to the loop and executes on 1st iteration
11454     // (if it ever executes at all).
11455     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11456       return false;
11457     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11458       return false;
11459     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11460   }
11461 
11462   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11463     const Loop *L = AR->getLoop();
11464     // Make sure that context belongs to the loop and executes on 1st iteration
11465     // (if it ever executes at all).
11466     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11467       return false;
11468     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11469       return false;
11470     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11471   }
11472 
11473   return false;
11474 }
11475 
11476 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11477     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11478     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11479   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11480     return false;
11481 
11482   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11483   if (!AddRecLHS)
11484     return false;
11485 
11486   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11487   if (!AddRecFoundLHS)
11488     return false;
11489 
11490   // We'd like to let SCEV reason about control dependencies, so we constrain
11491   // both the inequalities to be about add recurrences on the same loop.  This
11492   // way we can use isLoopEntryGuardedByCond later.
11493 
11494   const Loop *L = AddRecFoundLHS->getLoop();
11495   if (L != AddRecLHS->getLoop())
11496     return false;
11497 
11498   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11499   //
11500   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11501   //                                                                  ... (2)
11502   //
11503   // Informal proof for (2), assuming (1) [*]:
11504   //
11505   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11506   //
11507   // Then
11508   //
11509   //       FoundLHS s< FoundRHS s< INT_MIN - C
11510   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11511   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11512   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11513   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11514   // <=>  FoundLHS + C s< FoundRHS + C
11515   //
11516   // [*]: (1) can be proved by ruling out overflow.
11517   //
11518   // [**]: This can be proved by analyzing all the four possibilities:
11519   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11520   //    (A s>= 0, B s>= 0).
11521   //
11522   // Note:
11523   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11524   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11525   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11526   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11527   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11528   // C)".
11529 
11530   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11531   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11532   if (!LDiff || !RDiff || *LDiff != *RDiff)
11533     return false;
11534 
11535   if (LDiff->isMinValue())
11536     return true;
11537 
11538   APInt FoundRHSLimit;
11539 
11540   if (Pred == CmpInst::ICMP_ULT) {
11541     FoundRHSLimit = -(*RDiff);
11542   } else {
11543     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11544     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11545   }
11546 
11547   // Try to prove (1) or (2), as needed.
11548   return isAvailableAtLoopEntry(FoundRHS, L) &&
11549          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11550                                   getConstant(FoundRHSLimit));
11551 }
11552 
11553 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11554                                         const SCEV *LHS, const SCEV *RHS,
11555                                         const SCEV *FoundLHS,
11556                                         const SCEV *FoundRHS, unsigned Depth) {
11557   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11558 
11559   auto ClearOnExit = make_scope_exit([&]() {
11560     if (LPhi) {
11561       bool Erased = PendingMerges.erase(LPhi);
11562       assert(Erased && "Failed to erase LPhi!");
11563       (void)Erased;
11564     }
11565     if (RPhi) {
11566       bool Erased = PendingMerges.erase(RPhi);
11567       assert(Erased && "Failed to erase RPhi!");
11568       (void)Erased;
11569     }
11570   });
11571 
11572   // Find respective Phis and check that they are not being pending.
11573   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11574     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11575       if (!PendingMerges.insert(Phi).second)
11576         return false;
11577       LPhi = Phi;
11578     }
11579   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11580     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11581       // If we detect a loop of Phi nodes being processed by this method, for
11582       // example:
11583       //
11584       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11585       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11586       //
11587       // we don't want to deal with a case that complex, so return conservative
11588       // answer false.
11589       if (!PendingMerges.insert(Phi).second)
11590         return false;
11591       RPhi = Phi;
11592     }
11593 
11594   // If none of LHS, RHS is a Phi, nothing to do here.
11595   if (!LPhi && !RPhi)
11596     return false;
11597 
11598   // If there is a SCEVUnknown Phi we are interested in, make it left.
11599   if (!LPhi) {
11600     std::swap(LHS, RHS);
11601     std::swap(FoundLHS, FoundRHS);
11602     std::swap(LPhi, RPhi);
11603     Pred = ICmpInst::getSwappedPredicate(Pred);
11604   }
11605 
11606   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11607   const BasicBlock *LBB = LPhi->getParent();
11608   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11609 
11610   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11611     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11612            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11613            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11614   };
11615 
11616   if (RPhi && RPhi->getParent() == LBB) {
11617     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11618     // If we compare two Phis from the same block, and for each entry block
11619     // the predicate is true for incoming values from this block, then the
11620     // predicate is also true for the Phis.
11621     for (const BasicBlock *IncBB : predecessors(LBB)) {
11622       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11623       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11624       if (!ProvedEasily(L, R))
11625         return false;
11626     }
11627   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11628     // Case two: RHS is also a Phi from the same basic block, and it is an
11629     // AddRec. It means that there is a loop which has both AddRec and Unknown
11630     // PHIs, for it we can compare incoming values of AddRec from above the loop
11631     // and latch with their respective incoming values of LPhi.
11632     // TODO: Generalize to handle loops with many inputs in a header.
11633     if (LPhi->getNumIncomingValues() != 2) return false;
11634 
11635     auto *RLoop = RAR->getLoop();
11636     auto *Predecessor = RLoop->getLoopPredecessor();
11637     assert(Predecessor && "Loop with AddRec with no predecessor?");
11638     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11639     if (!ProvedEasily(L1, RAR->getStart()))
11640       return false;
11641     auto *Latch = RLoop->getLoopLatch();
11642     assert(Latch && "Loop with AddRec with no latch?");
11643     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11644     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11645       return false;
11646   } else {
11647     // In all other cases go over inputs of LHS and compare each of them to RHS,
11648     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11649     // At this point RHS is either a non-Phi, or it is a Phi from some block
11650     // different from LBB.
11651     for (const BasicBlock *IncBB : predecessors(LBB)) {
11652       // Check that RHS is available in this block.
11653       if (!dominates(RHS, IncBB))
11654         return false;
11655       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11656       // Make sure L does not refer to a value from a potentially previous
11657       // iteration of a loop.
11658       if (!properlyDominates(L, IncBB))
11659         return false;
11660       if (!ProvedEasily(L, RHS))
11661         return false;
11662     }
11663   }
11664   return true;
11665 }
11666 
11667 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
11668                                                     const SCEV *LHS,
11669                                                     const SCEV *RHS,
11670                                                     const SCEV *FoundLHS,
11671                                                     const SCEV *FoundRHS) {
11672   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
11673   // sure that we are dealing with same LHS.
11674   if (RHS == FoundRHS) {
11675     std::swap(LHS, RHS);
11676     std::swap(FoundLHS, FoundRHS);
11677     Pred = ICmpInst::getSwappedPredicate(Pred);
11678   }
11679   if (LHS != FoundLHS)
11680     return false;
11681 
11682   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
11683   if (!SUFoundRHS)
11684     return false;
11685 
11686   Value *Shiftee, *ShiftValue;
11687 
11688   using namespace PatternMatch;
11689   if (match(SUFoundRHS->getValue(),
11690             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
11691     auto *ShifteeS = getSCEV(Shiftee);
11692     // Prove one of the following:
11693     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
11694     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
11695     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11696     //   ---> LHS <s RHS
11697     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11698     //   ---> LHS <=s RHS
11699     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
11700       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
11701     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
11702       if (isKnownNonNegative(ShifteeS))
11703         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
11704   }
11705 
11706   return false;
11707 }
11708 
11709 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11710                                             const SCEV *LHS, const SCEV *RHS,
11711                                             const SCEV *FoundLHS,
11712                                             const SCEV *FoundRHS,
11713                                             const Instruction *CtxI) {
11714   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11715     return true;
11716 
11717   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11718     return true;
11719 
11720   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
11721     return true;
11722 
11723   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11724                                           CtxI))
11725     return true;
11726 
11727   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11728                                      FoundLHS, FoundRHS);
11729 }
11730 
11731 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11732 template <typename MinMaxExprType>
11733 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11734                                  const SCEV *Candidate) {
11735   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11736   if (!MinMaxExpr)
11737     return false;
11738 
11739   return is_contained(MinMaxExpr->operands(), Candidate);
11740 }
11741 
11742 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11743                                            ICmpInst::Predicate Pred,
11744                                            const SCEV *LHS, const SCEV *RHS) {
11745   // If both sides are affine addrecs for the same loop, with equal
11746   // steps, and we know the recurrences don't wrap, then we only
11747   // need to check the predicate on the starting values.
11748 
11749   if (!ICmpInst::isRelational(Pred))
11750     return false;
11751 
11752   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11753   if (!LAR)
11754     return false;
11755   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11756   if (!RAR)
11757     return false;
11758   if (LAR->getLoop() != RAR->getLoop())
11759     return false;
11760   if (!LAR->isAffine() || !RAR->isAffine())
11761     return false;
11762 
11763   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11764     return false;
11765 
11766   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11767                          SCEV::FlagNSW : SCEV::FlagNUW;
11768   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11769     return false;
11770 
11771   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11772 }
11773 
11774 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11775 /// expression?
11776 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11777                                         ICmpInst::Predicate Pred,
11778                                         const SCEV *LHS, const SCEV *RHS) {
11779   switch (Pred) {
11780   default:
11781     return false;
11782 
11783   case ICmpInst::ICMP_SGE:
11784     std::swap(LHS, RHS);
11785     LLVM_FALLTHROUGH;
11786   case ICmpInst::ICMP_SLE:
11787     return
11788         // min(A, ...) <= A
11789         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11790         // A <= max(A, ...)
11791         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11792 
11793   case ICmpInst::ICMP_UGE:
11794     std::swap(LHS, RHS);
11795     LLVM_FALLTHROUGH;
11796   case ICmpInst::ICMP_ULE:
11797     return
11798         // min(A, ...) <= A
11799         // FIXME: what about umin_seq?
11800         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11801         // A <= max(A, ...)
11802         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11803   }
11804 
11805   llvm_unreachable("covered switch fell through?!");
11806 }
11807 
11808 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11809                                              const SCEV *LHS, const SCEV *RHS,
11810                                              const SCEV *FoundLHS,
11811                                              const SCEV *FoundRHS,
11812                                              unsigned Depth) {
11813   assert(getTypeSizeInBits(LHS->getType()) ==
11814              getTypeSizeInBits(RHS->getType()) &&
11815          "LHS and RHS have different sizes?");
11816   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11817              getTypeSizeInBits(FoundRHS->getType()) &&
11818          "FoundLHS and FoundRHS have different sizes?");
11819   // We want to avoid hurting the compile time with analysis of too big trees.
11820   if (Depth > MaxSCEVOperationsImplicationDepth)
11821     return false;
11822 
11823   // We only want to work with GT comparison so far.
11824   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11825     Pred = CmpInst::getSwappedPredicate(Pred);
11826     std::swap(LHS, RHS);
11827     std::swap(FoundLHS, FoundRHS);
11828   }
11829 
11830   // For unsigned, try to reduce it to corresponding signed comparison.
11831   if (Pred == ICmpInst::ICMP_UGT)
11832     // We can replace unsigned predicate with its signed counterpart if all
11833     // involved values are non-negative.
11834     // TODO: We could have better support for unsigned.
11835     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11836       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11837       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11838       // use this fact to prove that LHS and RHS are non-negative.
11839       const SCEV *MinusOne = getMinusOne(LHS->getType());
11840       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11841                                 FoundRHS) &&
11842           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11843                                 FoundRHS))
11844         Pred = ICmpInst::ICMP_SGT;
11845     }
11846 
11847   if (Pred != ICmpInst::ICMP_SGT)
11848     return false;
11849 
11850   auto GetOpFromSExt = [&](const SCEV *S) {
11851     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11852       return Ext->getOperand();
11853     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11854     // the constant in some cases.
11855     return S;
11856   };
11857 
11858   // Acquire values from extensions.
11859   auto *OrigLHS = LHS;
11860   auto *OrigFoundLHS = FoundLHS;
11861   LHS = GetOpFromSExt(LHS);
11862   FoundLHS = GetOpFromSExt(FoundLHS);
11863 
11864   // Is the SGT predicate can be proved trivially or using the found context.
11865   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11866     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11867            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11868                                   FoundRHS, Depth + 1);
11869   };
11870 
11871   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11872     // We want to avoid creation of any new non-constant SCEV. Since we are
11873     // going to compare the operands to RHS, we should be certain that we don't
11874     // need any size extensions for this. So let's decline all cases when the
11875     // sizes of types of LHS and RHS do not match.
11876     // TODO: Maybe try to get RHS from sext to catch more cases?
11877     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11878       return false;
11879 
11880     // Should not overflow.
11881     if (!LHSAddExpr->hasNoSignedWrap())
11882       return false;
11883 
11884     auto *LL = LHSAddExpr->getOperand(0);
11885     auto *LR = LHSAddExpr->getOperand(1);
11886     auto *MinusOne = getMinusOne(RHS->getType());
11887 
11888     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11889     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11890       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11891     };
11892     // Try to prove the following rule:
11893     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11894     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11895     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11896       return true;
11897   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11898     Value *LL, *LR;
11899     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11900 
11901     using namespace llvm::PatternMatch;
11902 
11903     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11904       // Rules for division.
11905       // We are going to perform some comparisons with Denominator and its
11906       // derivative expressions. In general case, creating a SCEV for it may
11907       // lead to a complex analysis of the entire graph, and in particular it
11908       // can request trip count recalculation for the same loop. This would
11909       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11910       // this, we only want to create SCEVs that are constants in this section.
11911       // So we bail if Denominator is not a constant.
11912       if (!isa<ConstantInt>(LR))
11913         return false;
11914 
11915       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11916 
11917       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11918       // then a SCEV for the numerator already exists and matches with FoundLHS.
11919       auto *Numerator = getExistingSCEV(LL);
11920       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11921         return false;
11922 
11923       // Make sure that the numerator matches with FoundLHS and the denominator
11924       // is positive.
11925       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11926         return false;
11927 
11928       auto *DTy = Denominator->getType();
11929       auto *FRHSTy = FoundRHS->getType();
11930       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11931         // One of types is a pointer and another one is not. We cannot extend
11932         // them properly to a wider type, so let us just reject this case.
11933         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11934         // to avoid this check.
11935         return false;
11936 
11937       // Given that:
11938       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11939       auto *WTy = getWiderType(DTy, FRHSTy);
11940       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11941       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11942 
11943       // Try to prove the following rule:
11944       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11945       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11946       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11947       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11948       if (isKnownNonPositive(RHS) &&
11949           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11950         return true;
11951 
11952       // Try to prove the following rule:
11953       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11954       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11955       // If we divide it by Denominator > 2, then:
11956       // 1. If FoundLHS is negative, then the result is 0.
11957       // 2. If FoundLHS is non-negative, then the result is non-negative.
11958       // Anyways, the result is non-negative.
11959       auto *MinusOne = getMinusOne(WTy);
11960       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11961       if (isKnownNegative(RHS) &&
11962           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11963         return true;
11964     }
11965   }
11966 
11967   // If our expression contained SCEVUnknown Phis, and we split it down and now
11968   // need to prove something for them, try to prove the predicate for every
11969   // possible incoming values of those Phis.
11970   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11971     return true;
11972 
11973   return false;
11974 }
11975 
11976 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11977                                         const SCEV *LHS, const SCEV *RHS) {
11978   // zext x u<= sext x, sext x s<= zext x
11979   switch (Pred) {
11980   case ICmpInst::ICMP_SGE:
11981     std::swap(LHS, RHS);
11982     LLVM_FALLTHROUGH;
11983   case ICmpInst::ICMP_SLE: {
11984     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11985     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11986     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11987     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11988       return true;
11989     break;
11990   }
11991   case ICmpInst::ICMP_UGE:
11992     std::swap(LHS, RHS);
11993     LLVM_FALLTHROUGH;
11994   case ICmpInst::ICMP_ULE: {
11995     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11996     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11997     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11998     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11999       return true;
12000     break;
12001   }
12002   default:
12003     break;
12004   };
12005   return false;
12006 }
12007 
12008 bool
12009 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12010                                            const SCEV *LHS, const SCEV *RHS) {
12011   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12012          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12013          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12014          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12015          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12016 }
12017 
12018 bool
12019 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12020                                              const SCEV *LHS, const SCEV *RHS,
12021                                              const SCEV *FoundLHS,
12022                                              const SCEV *FoundRHS) {
12023   switch (Pred) {
12024   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
12025   case ICmpInst::ICMP_EQ:
12026   case ICmpInst::ICMP_NE:
12027     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12028       return true;
12029     break;
12030   case ICmpInst::ICMP_SLT:
12031   case ICmpInst::ICMP_SLE:
12032     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12033         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12034       return true;
12035     break;
12036   case ICmpInst::ICMP_SGT:
12037   case ICmpInst::ICMP_SGE:
12038     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12039         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12040       return true;
12041     break;
12042   case ICmpInst::ICMP_ULT:
12043   case ICmpInst::ICMP_ULE:
12044     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12045         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12046       return true;
12047     break;
12048   case ICmpInst::ICMP_UGT:
12049   case ICmpInst::ICMP_UGE:
12050     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12051         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12052       return true;
12053     break;
12054   }
12055 
12056   // Maybe it can be proved via operations?
12057   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12058     return true;
12059 
12060   return false;
12061 }
12062 
12063 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12064                                                      const SCEV *LHS,
12065                                                      const SCEV *RHS,
12066                                                      const SCEV *FoundLHS,
12067                                                      const SCEV *FoundRHS) {
12068   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12069     // The restriction on `FoundRHS` be lifted easily -- it exists only to
12070     // reduce the compile time impact of this optimization.
12071     return false;
12072 
12073   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12074   if (!Addend)
12075     return false;
12076 
12077   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12078 
12079   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12080   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12081   ConstantRange FoundLHSRange =
12082       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12083 
12084   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12085   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12086 
12087   // We can also compute the range of values for `LHS` that satisfy the
12088   // consequent, "`LHS` `Pred` `RHS`":
12089   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12090   // The antecedent implies the consequent if every value of `LHS` that
12091   // satisfies the antecedent also satisfies the consequent.
12092   return LHSRange.icmp(Pred, ConstRHS);
12093 }
12094 
12095 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12096                                         bool IsSigned) {
12097   assert(isKnownPositive(Stride) && "Positive stride expected!");
12098 
12099   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12100   const SCEV *One = getOne(Stride->getType());
12101 
12102   if (IsSigned) {
12103     APInt MaxRHS = getSignedRangeMax(RHS);
12104     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12105     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12106 
12107     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12108     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12109   }
12110 
12111   APInt MaxRHS = getUnsignedRangeMax(RHS);
12112   APInt MaxValue = APInt::getMaxValue(BitWidth);
12113   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12114 
12115   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12116   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12117 }
12118 
12119 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12120                                         bool IsSigned) {
12121 
12122   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12123   const SCEV *One = getOne(Stride->getType());
12124 
12125   if (IsSigned) {
12126     APInt MinRHS = getSignedRangeMin(RHS);
12127     APInt MinValue = APInt::getSignedMinValue(BitWidth);
12128     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12129 
12130     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12131     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12132   }
12133 
12134   APInt MinRHS = getUnsignedRangeMin(RHS);
12135   APInt MinValue = APInt::getMinValue(BitWidth);
12136   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12137 
12138   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12139   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12140 }
12141 
12142 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12143   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12144   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12145   // expression fixes the case of N=0.
12146   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12147   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12148   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12149 }
12150 
12151 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12152                                                     const SCEV *Stride,
12153                                                     const SCEV *End,
12154                                                     unsigned BitWidth,
12155                                                     bool IsSigned) {
12156   // The logic in this function assumes we can represent a positive stride.
12157   // If we can't, the backedge-taken count must be zero.
12158   if (IsSigned && BitWidth == 1)
12159     return getZero(Stride->getType());
12160 
12161   // This code has only been closely audited for negative strides in the
12162   // unsigned comparison case, it may be correct for signed comparison, but
12163   // that needs to be established.
12164   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
12165          "Stride is expected strictly positive for signed case!");
12166 
12167   // Calculate the maximum backedge count based on the range of values
12168   // permitted by Start, End, and Stride.
12169   APInt MinStart =
12170       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12171 
12172   APInt MinStride =
12173       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12174 
12175   // We assume either the stride is positive, or the backedge-taken count
12176   // is zero. So force StrideForMaxBECount to be at least one.
12177   APInt One(BitWidth, 1);
12178   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12179                                        : APIntOps::umax(One, MinStride);
12180 
12181   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12182                             : APInt::getMaxValue(BitWidth);
12183   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12184 
12185   // Although End can be a MAX expression we estimate MaxEnd considering only
12186   // the case End = RHS of the loop termination condition. This is safe because
12187   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12188   // taken count.
12189   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12190                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12191 
12192   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12193   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12194                     : APIntOps::umax(MaxEnd, MinStart);
12195 
12196   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12197                          getConstant(StrideForMaxBECount) /* Step */);
12198 }
12199 
12200 ScalarEvolution::ExitLimit
12201 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12202                                   const Loop *L, bool IsSigned,
12203                                   bool ControlsExit, bool AllowPredicates) {
12204   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12205 
12206   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12207   bool PredicatedIV = false;
12208 
12209   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12210     // Can we prove this loop *must* be UB if overflow of IV occurs?
12211     // Reasoning goes as follows:
12212     // * Suppose the IV did self wrap.
12213     // * If Stride evenly divides the iteration space, then once wrap
12214     //   occurs, the loop must revisit the same values.
12215     // * We know that RHS is invariant, and that none of those values
12216     //   caused this exit to be taken previously.  Thus, this exit is
12217     //   dynamically dead.
12218     // * If this is the sole exit, then a dead exit implies the loop
12219     //   must be infinite if there are no abnormal exits.
12220     // * If the loop were infinite, then it must either not be mustprogress
12221     //   or have side effects. Otherwise, it must be UB.
12222     // * It can't (by assumption), be UB so we have contradicted our
12223     //   premise and can conclude the IV did not in fact self-wrap.
12224     if (!isLoopInvariant(RHS, L))
12225       return false;
12226 
12227     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12228     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12229       return false;
12230 
12231     if (!ControlsExit || !loopHasNoAbnormalExits(L))
12232       return false;
12233 
12234     return loopIsFiniteByAssumption(L);
12235   };
12236 
12237   if (!IV) {
12238     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12239       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12240       if (AR && AR->getLoop() == L && AR->isAffine()) {
12241         auto canProveNUW = [&]() {
12242           if (!isLoopInvariant(RHS, L))
12243             return false;
12244 
12245           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12246             // We need the sequence defined by AR to strictly increase in the
12247             // unsigned integer domain for the logic below to hold.
12248             return false;
12249 
12250           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12251           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12252           // If RHS <=u Limit, then there must exist a value V in the sequence
12253           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12254           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12255           // overflow occurs.  This limit also implies that a signed comparison
12256           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12257           // the high bits on both sides must be zero.
12258           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12259           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12260           Limit = Limit.zext(OuterBitWidth);
12261           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12262         };
12263         auto Flags = AR->getNoWrapFlags();
12264         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12265           Flags = setFlags(Flags, SCEV::FlagNUW);
12266 
12267         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12268         if (AR->hasNoUnsignedWrap()) {
12269           // Emulate what getZeroExtendExpr would have done during construction
12270           // if we'd been able to infer the fact just above at that time.
12271           const SCEV *Step = AR->getStepRecurrence(*this);
12272           Type *Ty = ZExt->getType();
12273           auto *S = getAddRecExpr(
12274             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12275             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12276           IV = dyn_cast<SCEVAddRecExpr>(S);
12277         }
12278       }
12279     }
12280   }
12281 
12282 
12283   if (!IV && AllowPredicates) {
12284     // Try to make this an AddRec using runtime tests, in the first X
12285     // iterations of this loop, where X is the SCEV expression found by the
12286     // algorithm below.
12287     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12288     PredicatedIV = true;
12289   }
12290 
12291   // Avoid weird loops
12292   if (!IV || IV->getLoop() != L || !IV->isAffine())
12293     return getCouldNotCompute();
12294 
12295   // A precondition of this method is that the condition being analyzed
12296   // reaches an exiting branch which dominates the latch.  Given that, we can
12297   // assume that an increment which violates the nowrap specification and
12298   // produces poison must cause undefined behavior when the resulting poison
12299   // value is branched upon and thus we can conclude that the backedge is
12300   // taken no more often than would be required to produce that poison value.
12301   // Note that a well defined loop can exit on the iteration which violates
12302   // the nowrap specification if there is another exit (either explicit or
12303   // implicit/exceptional) which causes the loop to execute before the
12304   // exiting instruction we're analyzing would trigger UB.
12305   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12306   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12307   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12308 
12309   const SCEV *Stride = IV->getStepRecurrence(*this);
12310 
12311   bool PositiveStride = isKnownPositive(Stride);
12312 
12313   // Avoid negative or zero stride values.
12314   if (!PositiveStride) {
12315     // We can compute the correct backedge taken count for loops with unknown
12316     // strides if we can prove that the loop is not an infinite loop with side
12317     // effects. Here's the loop structure we are trying to handle -
12318     //
12319     // i = start
12320     // do {
12321     //   A[i] = i;
12322     //   i += s;
12323     // } while (i < end);
12324     //
12325     // The backedge taken count for such loops is evaluated as -
12326     // (max(end, start + stride) - start - 1) /u stride
12327     //
12328     // The additional preconditions that we need to check to prove correctness
12329     // of the above formula is as follows -
12330     //
12331     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12332     //    NoWrap flag).
12333     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12334     //    no side effects within the loop)
12335     // c) loop has a single static exit (with no abnormal exits)
12336     //
12337     // Precondition a) implies that if the stride is negative, this is a single
12338     // trip loop. The backedge taken count formula reduces to zero in this case.
12339     //
12340     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12341     // then a zero stride means the backedge can't be taken without executing
12342     // undefined behavior.
12343     //
12344     // The positive stride case is the same as isKnownPositive(Stride) returning
12345     // true (original behavior of the function).
12346     //
12347     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12348         !loopHasNoAbnormalExits(L))
12349       return getCouldNotCompute();
12350 
12351     // This bailout is protecting the logic in computeMaxBECountForLT which
12352     // has not yet been sufficiently auditted or tested with negative strides.
12353     // We used to filter out all known-non-positive cases here, we're in the
12354     // process of being less restrictive bit by bit.
12355     if (IsSigned && isKnownNonPositive(Stride))
12356       return getCouldNotCompute();
12357 
12358     if (!isKnownNonZero(Stride)) {
12359       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12360       // if it might eventually be greater than start and if so, on which
12361       // iteration.  We can't even produce a useful upper bound.
12362       if (!isLoopInvariant(RHS, L))
12363         return getCouldNotCompute();
12364 
12365       // We allow a potentially zero stride, but we need to divide by stride
12366       // below.  Since the loop can't be infinite and this check must control
12367       // the sole exit, we can infer the exit must be taken on the first
12368       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12369       // we know the numerator in the divides below must be zero, so we can
12370       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12371       // and produce the right result.
12372       // FIXME: Handle the case where Stride is poison?
12373       auto wouldZeroStrideBeUB = [&]() {
12374         // Proof by contradiction.  Suppose the stride were zero.  If we can
12375         // prove that the backedge *is* taken on the first iteration, then since
12376         // we know this condition controls the sole exit, we must have an
12377         // infinite loop.  We can't have a (well defined) infinite loop per
12378         // check just above.
12379         // Note: The (Start - Stride) term is used to get the start' term from
12380         // (start' + stride,+,stride). Remember that we only care about the
12381         // result of this expression when stride == 0 at runtime.
12382         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12383         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12384       };
12385       if (!wouldZeroStrideBeUB()) {
12386         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12387       }
12388     }
12389   } else if (!Stride->isOne() && !NoWrap) {
12390     auto isUBOnWrap = [&]() {
12391       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12392       // follows trivially from the fact that every (un)signed-wrapped, but
12393       // not self-wrapped value must be LT than the last value before
12394       // (un)signed wrap.  Since we know that last value didn't exit, nor
12395       // will any smaller one.
12396       return canAssumeNoSelfWrap(IV);
12397     };
12398 
12399     // Avoid proven overflow cases: this will ensure that the backedge taken
12400     // count will not generate any unsigned overflow. Relaxed no-overflow
12401     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12402     // undefined behaviors like the case of C language.
12403     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12404       return getCouldNotCompute();
12405   }
12406 
12407   // On all paths just preceeding, we established the following invariant:
12408   //   IV can be assumed not to overflow up to and including the exiting
12409   //   iteration.  We proved this in one of two ways:
12410   //   1) We can show overflow doesn't occur before the exiting iteration
12411   //      1a) canIVOverflowOnLT, and b) step of one
12412   //   2) We can show that if overflow occurs, the loop must execute UB
12413   //      before any possible exit.
12414   // Note that we have not yet proved RHS invariant (in general).
12415 
12416   const SCEV *Start = IV->getStart();
12417 
12418   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12419   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12420   // Use integer-typed versions for actual computation; we can't subtract
12421   // pointers in general.
12422   const SCEV *OrigStart = Start;
12423   const SCEV *OrigRHS = RHS;
12424   if (Start->getType()->isPointerTy()) {
12425     Start = getLosslessPtrToIntExpr(Start);
12426     if (isa<SCEVCouldNotCompute>(Start))
12427       return Start;
12428   }
12429   if (RHS->getType()->isPointerTy()) {
12430     RHS = getLosslessPtrToIntExpr(RHS);
12431     if (isa<SCEVCouldNotCompute>(RHS))
12432       return RHS;
12433   }
12434 
12435   // When the RHS is not invariant, we do not know the end bound of the loop and
12436   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12437   // calculate the MaxBECount, given the start, stride and max value for the end
12438   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12439   // checked above).
12440   if (!isLoopInvariant(RHS, L)) {
12441     const SCEV *MaxBECount = computeMaxBECountForLT(
12442         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12443     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12444                      false /*MaxOrZero*/, Predicates);
12445   }
12446 
12447   // We use the expression (max(End,Start)-Start)/Stride to describe the
12448   // backedge count, as if the backedge is taken at least once max(End,Start)
12449   // is End and so the result is as above, and if not max(End,Start) is Start
12450   // so we get a backedge count of zero.
12451   const SCEV *BECount = nullptr;
12452   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12453   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12454   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12455   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12456   // Can we prove (max(RHS,Start) > Start - Stride?
12457   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12458       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12459     // In this case, we can use a refined formula for computing backedge taken
12460     // count.  The general formula remains:
12461     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12462     // We want to use the alternate formula:
12463     //   "((End - 1) - (Start - Stride)) /u Stride"
12464     // Let's do a quick case analysis to show these are equivalent under
12465     // our precondition that max(RHS,Start) > Start - Stride.
12466     // * For RHS <= Start, the backedge-taken count must be zero.
12467     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12468     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12469     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12470     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12471     //     this to the stride of 1 case.
12472     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12473     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12474     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12475     //   "((RHS - (Start - Stride) - 1) /u Stride".
12476     //   Our preconditions trivially imply no overflow in that form.
12477     const SCEV *MinusOne = getMinusOne(Stride->getType());
12478     const SCEV *Numerator =
12479         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12480     BECount = getUDivExpr(Numerator, Stride);
12481   }
12482 
12483   const SCEV *BECountIfBackedgeTaken = nullptr;
12484   if (!BECount) {
12485     auto canProveRHSGreaterThanEqualStart = [&]() {
12486       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12487       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12488         return true;
12489 
12490       // (RHS > Start - 1) implies RHS >= Start.
12491       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12492       //   "Start - 1" doesn't overflow.
12493       // * For signed comparison, if Start - 1 does overflow, it's equal
12494       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12495       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12496       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12497       //
12498       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12499       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12500       auto *StartMinusOne = getAddExpr(OrigStart,
12501                                        getMinusOne(OrigStart->getType()));
12502       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12503     };
12504 
12505     // If we know that RHS >= Start in the context of loop, then we know that
12506     // max(RHS, Start) = RHS at this point.
12507     const SCEV *End;
12508     if (canProveRHSGreaterThanEqualStart()) {
12509       End = RHS;
12510     } else {
12511       // If RHS < Start, the backedge will be taken zero times.  So in
12512       // general, we can write the backedge-taken count as:
12513       //
12514       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12515       //
12516       // We convert it to the following to make it more convenient for SCEV:
12517       //
12518       //     ceil(max(RHS, Start) - Start) / Stride
12519       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12520 
12521       // See what would happen if we assume the backedge is taken. This is
12522       // used to compute MaxBECount.
12523       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12524     }
12525 
12526     // At this point, we know:
12527     //
12528     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12529     // 2. The index variable doesn't overflow.
12530     //
12531     // Therefore, we know N exists such that
12532     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12533     // doesn't overflow.
12534     //
12535     // Using this information, try to prove whether the addition in
12536     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12537     const SCEV *One = getOne(Stride->getType());
12538     bool MayAddOverflow = [&] {
12539       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12540         if (StrideC->getAPInt().isPowerOf2()) {
12541           // Suppose Stride is a power of two, and Start/End are unsigned
12542           // integers.  Let UMAX be the largest representable unsigned
12543           // integer.
12544           //
12545           // By the preconditions of this function, we know
12546           // "(Start + Stride * N) >= End", and this doesn't overflow.
12547           // As a formula:
12548           //
12549           //   End <= (Start + Stride * N) <= UMAX
12550           //
12551           // Subtracting Start from all the terms:
12552           //
12553           //   End - Start <= Stride * N <= UMAX - Start
12554           //
12555           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12556           //
12557           //   End - Start <= Stride * N <= UMAX
12558           //
12559           // Stride * N is a multiple of Stride. Therefore,
12560           //
12561           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12562           //
12563           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12564           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12565           //
12566           //   End - Start <= Stride * N <= UMAX - Stride - 1
12567           //
12568           // Dropping the middle term:
12569           //
12570           //   End - Start <= UMAX - Stride - 1
12571           //
12572           // Adding Stride - 1 to both sides:
12573           //
12574           //   (End - Start) + (Stride - 1) <= UMAX
12575           //
12576           // In other words, the addition doesn't have unsigned overflow.
12577           //
12578           // A similar proof works if we treat Start/End as signed values.
12579           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12580           // use signed max instead of unsigned max. Note that we're trying
12581           // to prove a lack of unsigned overflow in either case.
12582           return false;
12583         }
12584       }
12585       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12586         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12587         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12588         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12589         //
12590         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12591         return false;
12592       }
12593       return true;
12594     }();
12595 
12596     const SCEV *Delta = getMinusSCEV(End, Start);
12597     if (!MayAddOverflow) {
12598       // floor((D + (S - 1)) / S)
12599       // We prefer this formulation if it's legal because it's fewer operations.
12600       BECount =
12601           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12602     } else {
12603       BECount = getUDivCeilSCEV(Delta, Stride);
12604     }
12605   }
12606 
12607   const SCEV *MaxBECount;
12608   bool MaxOrZero = false;
12609   if (isa<SCEVConstant>(BECount)) {
12610     MaxBECount = BECount;
12611   } else if (BECountIfBackedgeTaken &&
12612              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12613     // If we know exactly how many times the backedge will be taken if it's
12614     // taken at least once, then the backedge count will either be that or
12615     // zero.
12616     MaxBECount = BECountIfBackedgeTaken;
12617     MaxOrZero = true;
12618   } else {
12619     MaxBECount = computeMaxBECountForLT(
12620         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12621   }
12622 
12623   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12624       !isa<SCEVCouldNotCompute>(BECount))
12625     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12626 
12627   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12628 }
12629 
12630 ScalarEvolution::ExitLimit
12631 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12632                                      const Loop *L, bool IsSigned,
12633                                      bool ControlsExit, bool AllowPredicates) {
12634   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12635   // We handle only IV > Invariant
12636   if (!isLoopInvariant(RHS, L))
12637     return getCouldNotCompute();
12638 
12639   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12640   if (!IV && AllowPredicates)
12641     // Try to make this an AddRec using runtime tests, in the first X
12642     // iterations of this loop, where X is the SCEV expression found by the
12643     // algorithm below.
12644     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12645 
12646   // Avoid weird loops
12647   if (!IV || IV->getLoop() != L || !IV->isAffine())
12648     return getCouldNotCompute();
12649 
12650   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12651   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12652   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12653 
12654   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12655 
12656   // Avoid negative or zero stride values
12657   if (!isKnownPositive(Stride))
12658     return getCouldNotCompute();
12659 
12660   // Avoid proven overflow cases: this will ensure that the backedge taken count
12661   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12662   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12663   // behaviors like the case of C language.
12664   if (!Stride->isOne() && !NoWrap)
12665     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12666       return getCouldNotCompute();
12667 
12668   const SCEV *Start = IV->getStart();
12669   const SCEV *End = RHS;
12670   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12671     // If we know that Start >= RHS in the context of loop, then we know that
12672     // min(RHS, Start) = RHS at this point.
12673     if (isLoopEntryGuardedByCond(
12674             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12675       End = RHS;
12676     else
12677       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12678   }
12679 
12680   if (Start->getType()->isPointerTy()) {
12681     Start = getLosslessPtrToIntExpr(Start);
12682     if (isa<SCEVCouldNotCompute>(Start))
12683       return Start;
12684   }
12685   if (End->getType()->isPointerTy()) {
12686     End = getLosslessPtrToIntExpr(End);
12687     if (isa<SCEVCouldNotCompute>(End))
12688       return End;
12689   }
12690 
12691   // Compute ((Start - End) + (Stride - 1)) / Stride.
12692   // FIXME: This can overflow. Holding off on fixing this for now;
12693   // howManyGreaterThans will hopefully be gone soon.
12694   const SCEV *One = getOne(Stride->getType());
12695   const SCEV *BECount = getUDivExpr(
12696       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12697 
12698   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12699                             : getUnsignedRangeMax(Start);
12700 
12701   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12702                              : getUnsignedRangeMin(Stride);
12703 
12704   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12705   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12706                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12707 
12708   // Although End can be a MIN expression we estimate MinEnd considering only
12709   // the case End = RHS. This is safe because in the other case (Start - End)
12710   // is zero, leading to a zero maximum backedge taken count.
12711   APInt MinEnd =
12712     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12713              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12714 
12715   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12716                                ? BECount
12717                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12718                                                  getConstant(MinStride));
12719 
12720   if (isa<SCEVCouldNotCompute>(MaxBECount))
12721     MaxBECount = BECount;
12722 
12723   return ExitLimit(BECount, MaxBECount, false, Predicates);
12724 }
12725 
12726 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12727                                                     ScalarEvolution &SE) const {
12728   if (Range.isFullSet())  // Infinite loop.
12729     return SE.getCouldNotCompute();
12730 
12731   // If the start is a non-zero constant, shift the range to simplify things.
12732   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12733     if (!SC->getValue()->isZero()) {
12734       SmallVector<const SCEV *, 4> Operands(operands());
12735       Operands[0] = SE.getZero(SC->getType());
12736       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12737                                              getNoWrapFlags(FlagNW));
12738       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12739         return ShiftedAddRec->getNumIterationsInRange(
12740             Range.subtract(SC->getAPInt()), SE);
12741       // This is strange and shouldn't happen.
12742       return SE.getCouldNotCompute();
12743     }
12744 
12745   // The only time we can solve this is when we have all constant indices.
12746   // Otherwise, we cannot determine the overflow conditions.
12747   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12748     return SE.getCouldNotCompute();
12749 
12750   // Okay at this point we know that all elements of the chrec are constants and
12751   // that the start element is zero.
12752 
12753   // First check to see if the range contains zero.  If not, the first
12754   // iteration exits.
12755   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12756   if (!Range.contains(APInt(BitWidth, 0)))
12757     return SE.getZero(getType());
12758 
12759   if (isAffine()) {
12760     // If this is an affine expression then we have this situation:
12761     //   Solve {0,+,A} in Range  ===  Ax in Range
12762 
12763     // We know that zero is in the range.  If A is positive then we know that
12764     // the upper value of the range must be the first possible exit value.
12765     // If A is negative then the lower of the range is the last possible loop
12766     // value.  Also note that we already checked for a full range.
12767     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12768     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12769 
12770     // The exit value should be (End+A)/A.
12771     APInt ExitVal = (End + A).udiv(A);
12772     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12773 
12774     // Evaluate at the exit value.  If we really did fall out of the valid
12775     // range, then we computed our trip count, otherwise wrap around or other
12776     // things must have happened.
12777     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12778     if (Range.contains(Val->getValue()))
12779       return SE.getCouldNotCompute();  // Something strange happened
12780 
12781     // Ensure that the previous value is in the range.
12782     assert(Range.contains(
12783            EvaluateConstantChrecAtConstant(this,
12784            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12785            "Linear scev computation is off in a bad way!");
12786     return SE.getConstant(ExitValue);
12787   }
12788 
12789   if (isQuadratic()) {
12790     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12791       return SE.getConstant(S.getValue());
12792   }
12793 
12794   return SE.getCouldNotCompute();
12795 }
12796 
12797 const SCEVAddRecExpr *
12798 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12799   assert(getNumOperands() > 1 && "AddRec with zero step?");
12800   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12801   // but in this case we cannot guarantee that the value returned will be an
12802   // AddRec because SCEV does not have a fixed point where it stops
12803   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12804   // may happen if we reach arithmetic depth limit while simplifying. So we
12805   // construct the returned value explicitly.
12806   SmallVector<const SCEV *, 3> Ops;
12807   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12808   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12809   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12810     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12811   // We know that the last operand is not a constant zero (otherwise it would
12812   // have been popped out earlier). This guarantees us that if the result has
12813   // the same last operand, then it will also not be popped out, meaning that
12814   // the returned value will be an AddRec.
12815   const SCEV *Last = getOperand(getNumOperands() - 1);
12816   assert(!Last->isZero() && "Recurrency with zero step?");
12817   Ops.push_back(Last);
12818   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12819                                                SCEV::FlagAnyWrap));
12820 }
12821 
12822 // Return true when S contains at least an undef value.
12823 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12824   return SCEVExprContains(S, [](const SCEV *S) {
12825     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12826       return isa<UndefValue>(SU->getValue());
12827     return false;
12828   });
12829 }
12830 
12831 // Return true when S contains a value that is a nullptr.
12832 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
12833   return SCEVExprContains(S, [](const SCEV *S) {
12834     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12835       return SU->getValue() == nullptr;
12836     return false;
12837   });
12838 }
12839 
12840 /// Return the size of an element read or written by Inst.
12841 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12842   Type *Ty;
12843   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12844     Ty = Store->getValueOperand()->getType();
12845   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12846     Ty = Load->getType();
12847   else
12848     return nullptr;
12849 
12850   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12851   return getSizeOfExpr(ETy, Ty);
12852 }
12853 
12854 //===----------------------------------------------------------------------===//
12855 //                   SCEVCallbackVH Class Implementation
12856 //===----------------------------------------------------------------------===//
12857 
12858 void ScalarEvolution::SCEVCallbackVH::deleted() {
12859   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12860   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12861     SE->ConstantEvolutionLoopExitValue.erase(PN);
12862   SE->eraseValueFromMap(getValPtr());
12863   // this now dangles!
12864 }
12865 
12866 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12867   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12868 
12869   // Forget all the expressions associated with users of the old value,
12870   // so that future queries will recompute the expressions using the new
12871   // value.
12872   Value *Old = getValPtr();
12873   SmallVector<User *, 16> Worklist(Old->users());
12874   SmallPtrSet<User *, 8> Visited;
12875   while (!Worklist.empty()) {
12876     User *U = Worklist.pop_back_val();
12877     // Deleting the Old value will cause this to dangle. Postpone
12878     // that until everything else is done.
12879     if (U == Old)
12880       continue;
12881     if (!Visited.insert(U).second)
12882       continue;
12883     if (PHINode *PN = dyn_cast<PHINode>(U))
12884       SE->ConstantEvolutionLoopExitValue.erase(PN);
12885     SE->eraseValueFromMap(U);
12886     llvm::append_range(Worklist, U->users());
12887   }
12888   // Delete the Old value.
12889   if (PHINode *PN = dyn_cast<PHINode>(Old))
12890     SE->ConstantEvolutionLoopExitValue.erase(PN);
12891   SE->eraseValueFromMap(Old);
12892   // this now dangles!
12893 }
12894 
12895 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12896   : CallbackVH(V), SE(se) {}
12897 
12898 //===----------------------------------------------------------------------===//
12899 //                   ScalarEvolution Class Implementation
12900 //===----------------------------------------------------------------------===//
12901 
12902 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12903                                  AssumptionCache &AC, DominatorTree &DT,
12904                                  LoopInfo &LI)
12905     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12906       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12907       LoopDispositions(64), BlockDispositions(64) {
12908   // To use guards for proving predicates, we need to scan every instruction in
12909   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12910   // time if the IR does not actually contain any calls to
12911   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12912   //
12913   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12914   // to _add_ guards to the module when there weren't any before, and wants
12915   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12916   // efficient in lieu of being smart in that rather obscure case.
12917 
12918   auto *GuardDecl = F.getParent()->getFunction(
12919       Intrinsic::getName(Intrinsic::experimental_guard));
12920   HasGuards = GuardDecl && !GuardDecl->use_empty();
12921 }
12922 
12923 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12924     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12925       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12926       ValueExprMap(std::move(Arg.ValueExprMap)),
12927       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12928       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12929       PendingMerges(std::move(Arg.PendingMerges)),
12930       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12931       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12932       PredicatedBackedgeTakenCounts(
12933           std::move(Arg.PredicatedBackedgeTakenCounts)),
12934       BECountUsers(std::move(Arg.BECountUsers)),
12935       ConstantEvolutionLoopExitValue(
12936           std::move(Arg.ConstantEvolutionLoopExitValue)),
12937       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12938       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
12939       LoopDispositions(std::move(Arg.LoopDispositions)),
12940       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12941       BlockDispositions(std::move(Arg.BlockDispositions)),
12942       SCEVUsers(std::move(Arg.SCEVUsers)),
12943       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12944       SignedRanges(std::move(Arg.SignedRanges)),
12945       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12946       UniquePreds(std::move(Arg.UniquePreds)),
12947       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12948       LoopUsers(std::move(Arg.LoopUsers)),
12949       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12950       FirstUnknown(Arg.FirstUnknown) {
12951   Arg.FirstUnknown = nullptr;
12952 }
12953 
12954 ScalarEvolution::~ScalarEvolution() {
12955   // Iterate through all the SCEVUnknown instances and call their
12956   // destructors, so that they release their references to their values.
12957   for (SCEVUnknown *U = FirstUnknown; U;) {
12958     SCEVUnknown *Tmp = U;
12959     U = U->Next;
12960     Tmp->~SCEVUnknown();
12961   }
12962   FirstUnknown = nullptr;
12963 
12964   ExprValueMap.clear();
12965   ValueExprMap.clear();
12966   HasRecMap.clear();
12967   BackedgeTakenCounts.clear();
12968   PredicatedBackedgeTakenCounts.clear();
12969 
12970   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12971   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12972   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12973   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12974   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12975 }
12976 
12977 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12978   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12979 }
12980 
12981 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12982                           const Loop *L) {
12983   // Print all inner loops first
12984   for (Loop *I : *L)
12985     PrintLoopInfo(OS, SE, I);
12986 
12987   OS << "Loop ";
12988   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12989   OS << ": ";
12990 
12991   SmallVector<BasicBlock *, 8> ExitingBlocks;
12992   L->getExitingBlocks(ExitingBlocks);
12993   if (ExitingBlocks.size() != 1)
12994     OS << "<multiple exits> ";
12995 
12996   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12997     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12998   else
12999     OS << "Unpredictable backedge-taken count.\n";
13000 
13001   if (ExitingBlocks.size() > 1)
13002     for (BasicBlock *ExitingBlock : ExitingBlocks) {
13003       OS << "  exit count for " << ExitingBlock->getName() << ": "
13004          << *SE->getExitCount(L, ExitingBlock) << "\n";
13005     }
13006 
13007   OS << "Loop ";
13008   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13009   OS << ": ";
13010 
13011   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
13012     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
13013     if (SE->isBackedgeTakenCountMaxOrZero(L))
13014       OS << ", actual taken count either this or zero.";
13015   } else {
13016     OS << "Unpredictable max backedge-taken count. ";
13017   }
13018 
13019   OS << "\n"
13020         "Loop ";
13021   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13022   OS << ": ";
13023 
13024   SmallVector<const SCEVPredicate *, 4> Preds;
13025   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13026   if (!isa<SCEVCouldNotCompute>(PBT)) {
13027     OS << "Predicated backedge-taken count is " << *PBT << "\n";
13028     OS << " Predicates:\n";
13029     for (auto *P : Preds)
13030       P->print(OS, 4);
13031   } else {
13032     OS << "Unpredictable predicated backedge-taken count. ";
13033   }
13034   OS << "\n";
13035 
13036   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13037     OS << "Loop ";
13038     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13039     OS << ": ";
13040     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13041   }
13042 }
13043 
13044 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
13045   switch (LD) {
13046   case ScalarEvolution::LoopVariant:
13047     return "Variant";
13048   case ScalarEvolution::LoopInvariant:
13049     return "Invariant";
13050   case ScalarEvolution::LoopComputable:
13051     return "Computable";
13052   }
13053   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
13054 }
13055 
13056 void ScalarEvolution::print(raw_ostream &OS) const {
13057   // ScalarEvolution's implementation of the print method is to print
13058   // out SCEV values of all instructions that are interesting. Doing
13059   // this potentially causes it to create new SCEV objects though,
13060   // which technically conflicts with the const qualifier. This isn't
13061   // observable from outside the class though, so casting away the
13062   // const isn't dangerous.
13063   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13064 
13065   if (ClassifyExpressions) {
13066     OS << "Classifying expressions for: ";
13067     F.printAsOperand(OS, /*PrintType=*/false);
13068     OS << "\n";
13069     for (Instruction &I : instructions(F))
13070       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13071         OS << I << '\n';
13072         OS << "  -->  ";
13073         const SCEV *SV = SE.getSCEV(&I);
13074         SV->print(OS);
13075         if (!isa<SCEVCouldNotCompute>(SV)) {
13076           OS << " U: ";
13077           SE.getUnsignedRange(SV).print(OS);
13078           OS << " S: ";
13079           SE.getSignedRange(SV).print(OS);
13080         }
13081 
13082         const Loop *L = LI.getLoopFor(I.getParent());
13083 
13084         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13085         if (AtUse != SV) {
13086           OS << "  -->  ";
13087           AtUse->print(OS);
13088           if (!isa<SCEVCouldNotCompute>(AtUse)) {
13089             OS << " U: ";
13090             SE.getUnsignedRange(AtUse).print(OS);
13091             OS << " S: ";
13092             SE.getSignedRange(AtUse).print(OS);
13093           }
13094         }
13095 
13096         if (L) {
13097           OS << "\t\t" "Exits: ";
13098           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13099           if (!SE.isLoopInvariant(ExitValue, L)) {
13100             OS << "<<Unknown>>";
13101           } else {
13102             OS << *ExitValue;
13103           }
13104 
13105           bool First = true;
13106           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13107             if (First) {
13108               OS << "\t\t" "LoopDispositions: { ";
13109               First = false;
13110             } else {
13111               OS << ", ";
13112             }
13113 
13114             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13115             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
13116           }
13117 
13118           for (auto *InnerL : depth_first(L)) {
13119             if (InnerL == L)
13120               continue;
13121             if (First) {
13122               OS << "\t\t" "LoopDispositions: { ";
13123               First = false;
13124             } else {
13125               OS << ", ";
13126             }
13127 
13128             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13129             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
13130           }
13131 
13132           OS << " }";
13133         }
13134 
13135         OS << "\n";
13136       }
13137   }
13138 
13139   OS << "Determining loop execution counts for: ";
13140   F.printAsOperand(OS, /*PrintType=*/false);
13141   OS << "\n";
13142   for (Loop *I : LI)
13143     PrintLoopInfo(OS, &SE, I);
13144 }
13145 
13146 ScalarEvolution::LoopDisposition
13147 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13148   auto &Values = LoopDispositions[S];
13149   for (auto &V : Values) {
13150     if (V.getPointer() == L)
13151       return V.getInt();
13152   }
13153   Values.emplace_back(L, LoopVariant);
13154   LoopDisposition D = computeLoopDisposition(S, L);
13155   auto &Values2 = LoopDispositions[S];
13156   for (auto &V : llvm::reverse(Values2)) {
13157     if (V.getPointer() == L) {
13158       V.setInt(D);
13159       break;
13160     }
13161   }
13162   return D;
13163 }
13164 
13165 ScalarEvolution::LoopDisposition
13166 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13167   switch (S->getSCEVType()) {
13168   case scConstant:
13169     return LoopInvariant;
13170   case scPtrToInt:
13171   case scTruncate:
13172   case scZeroExtend:
13173   case scSignExtend:
13174     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
13175   case scAddRecExpr: {
13176     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13177 
13178     // If L is the addrec's loop, it's computable.
13179     if (AR->getLoop() == L)
13180       return LoopComputable;
13181 
13182     // Add recurrences are never invariant in the function-body (null loop).
13183     if (!L)
13184       return LoopVariant;
13185 
13186     // Everything that is not defined at loop entry is variant.
13187     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13188       return LoopVariant;
13189     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13190            " dominate the contained loop's header?");
13191 
13192     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13193     if (AR->getLoop()->contains(L))
13194       return LoopInvariant;
13195 
13196     // This recurrence is variant w.r.t. L if any of its operands
13197     // are variant.
13198     for (auto *Op : AR->operands())
13199       if (!isLoopInvariant(Op, L))
13200         return LoopVariant;
13201 
13202     // Otherwise it's loop-invariant.
13203     return LoopInvariant;
13204   }
13205   case scAddExpr:
13206   case scMulExpr:
13207   case scUMaxExpr:
13208   case scSMaxExpr:
13209   case scUMinExpr:
13210   case scSMinExpr:
13211   case scSequentialUMinExpr: {
13212     bool HasVarying = false;
13213     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
13214       LoopDisposition D = getLoopDisposition(Op, L);
13215       if (D == LoopVariant)
13216         return LoopVariant;
13217       if (D == LoopComputable)
13218         HasVarying = true;
13219     }
13220     return HasVarying ? LoopComputable : LoopInvariant;
13221   }
13222   case scUDivExpr: {
13223     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13224     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
13225     if (LD == LoopVariant)
13226       return LoopVariant;
13227     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
13228     if (RD == LoopVariant)
13229       return LoopVariant;
13230     return (LD == LoopInvariant && RD == LoopInvariant) ?
13231            LoopInvariant : LoopComputable;
13232   }
13233   case scUnknown:
13234     // All non-instruction values are loop invariant.  All instructions are loop
13235     // invariant if they are not contained in the specified loop.
13236     // Instructions are never considered invariant in the function body
13237     // (null loop) because they are defined within the "loop".
13238     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13239       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13240     return LoopInvariant;
13241   case scCouldNotCompute:
13242     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13243   }
13244   llvm_unreachable("Unknown SCEV kind!");
13245 }
13246 
13247 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13248   return getLoopDisposition(S, L) == LoopInvariant;
13249 }
13250 
13251 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13252   return getLoopDisposition(S, L) == LoopComputable;
13253 }
13254 
13255 ScalarEvolution::BlockDisposition
13256 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13257   auto &Values = BlockDispositions[S];
13258   for (auto &V : Values) {
13259     if (V.getPointer() == BB)
13260       return V.getInt();
13261   }
13262   Values.emplace_back(BB, DoesNotDominateBlock);
13263   BlockDisposition D = computeBlockDisposition(S, BB);
13264   auto &Values2 = BlockDispositions[S];
13265   for (auto &V : llvm::reverse(Values2)) {
13266     if (V.getPointer() == BB) {
13267       V.setInt(D);
13268       break;
13269     }
13270   }
13271   return D;
13272 }
13273 
13274 ScalarEvolution::BlockDisposition
13275 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13276   switch (S->getSCEVType()) {
13277   case scConstant:
13278     return ProperlyDominatesBlock;
13279   case scPtrToInt:
13280   case scTruncate:
13281   case scZeroExtend:
13282   case scSignExtend:
13283     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
13284   case scAddRecExpr: {
13285     // This uses a "dominates" query instead of "properly dominates" query
13286     // to test for proper dominance too, because the instruction which
13287     // produces the addrec's value is a PHI, and a PHI effectively properly
13288     // dominates its entire containing block.
13289     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13290     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13291       return DoesNotDominateBlock;
13292 
13293     // Fall through into SCEVNAryExpr handling.
13294     LLVM_FALLTHROUGH;
13295   }
13296   case scAddExpr:
13297   case scMulExpr:
13298   case scUMaxExpr:
13299   case scSMaxExpr:
13300   case scUMinExpr:
13301   case scSMinExpr:
13302   case scSequentialUMinExpr: {
13303     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
13304     bool Proper = true;
13305     for (const SCEV *NAryOp : NAry->operands()) {
13306       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13307       if (D == DoesNotDominateBlock)
13308         return DoesNotDominateBlock;
13309       if (D == DominatesBlock)
13310         Proper = false;
13311     }
13312     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13313   }
13314   case scUDivExpr: {
13315     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13316     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
13317     BlockDisposition LD = getBlockDisposition(LHS, BB);
13318     if (LD == DoesNotDominateBlock)
13319       return DoesNotDominateBlock;
13320     BlockDisposition RD = getBlockDisposition(RHS, BB);
13321     if (RD == DoesNotDominateBlock)
13322       return DoesNotDominateBlock;
13323     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
13324       ProperlyDominatesBlock : DominatesBlock;
13325   }
13326   case scUnknown:
13327     if (Instruction *I =
13328           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13329       if (I->getParent() == BB)
13330         return DominatesBlock;
13331       if (DT.properlyDominates(I->getParent(), BB))
13332         return ProperlyDominatesBlock;
13333       return DoesNotDominateBlock;
13334     }
13335     return ProperlyDominatesBlock;
13336   case scCouldNotCompute:
13337     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13338   }
13339   llvm_unreachable("Unknown SCEV kind!");
13340 }
13341 
13342 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13343   return getBlockDisposition(S, BB) >= DominatesBlock;
13344 }
13345 
13346 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13347   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13348 }
13349 
13350 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13351   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13352 }
13353 
13354 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13355                                                 bool Predicated) {
13356   auto &BECounts =
13357       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13358   auto It = BECounts.find(L);
13359   if (It != BECounts.end()) {
13360     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13361       if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13362         auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13363         assert(UserIt != BECountUsers.end());
13364         UserIt->second.erase({L, Predicated});
13365       }
13366     }
13367     BECounts.erase(It);
13368   }
13369 }
13370 
13371 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13372   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13373   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13374 
13375   while (!Worklist.empty()) {
13376     const SCEV *Curr = Worklist.pop_back_val();
13377     auto Users = SCEVUsers.find(Curr);
13378     if (Users != SCEVUsers.end())
13379       for (auto *User : Users->second)
13380         if (ToForget.insert(User).second)
13381           Worklist.push_back(User);
13382   }
13383 
13384   for (auto *S : ToForget)
13385     forgetMemoizedResultsImpl(S);
13386 
13387   for (auto I = PredicatedSCEVRewrites.begin();
13388        I != PredicatedSCEVRewrites.end();) {
13389     std::pair<const SCEV *, const Loop *> Entry = I->first;
13390     if (ToForget.count(Entry.first))
13391       PredicatedSCEVRewrites.erase(I++);
13392     else
13393       ++I;
13394   }
13395 }
13396 
13397 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13398   LoopDispositions.erase(S);
13399   BlockDispositions.erase(S);
13400   UnsignedRanges.erase(S);
13401   SignedRanges.erase(S);
13402   HasRecMap.erase(S);
13403   MinTrailingZerosCache.erase(S);
13404 
13405   auto ExprIt = ExprValueMap.find(S);
13406   if (ExprIt != ExprValueMap.end()) {
13407     for (Value *V : ExprIt->second) {
13408       auto ValueIt = ValueExprMap.find_as(V);
13409       if (ValueIt != ValueExprMap.end())
13410         ValueExprMap.erase(ValueIt);
13411     }
13412     ExprValueMap.erase(ExprIt);
13413   }
13414 
13415   auto ScopeIt = ValuesAtScopes.find(S);
13416   if (ScopeIt != ValuesAtScopes.end()) {
13417     for (const auto &Pair : ScopeIt->second)
13418       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13419         erase_value(ValuesAtScopesUsers[Pair.second],
13420                     std::make_pair(Pair.first, S));
13421     ValuesAtScopes.erase(ScopeIt);
13422   }
13423 
13424   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13425   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13426     for (const auto &Pair : ScopeUserIt->second)
13427       erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13428     ValuesAtScopesUsers.erase(ScopeUserIt);
13429   }
13430 
13431   auto BEUsersIt = BECountUsers.find(S);
13432   if (BEUsersIt != BECountUsers.end()) {
13433     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13434     auto Copy = BEUsersIt->second;
13435     for (const auto &Pair : Copy)
13436       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13437     BECountUsers.erase(BEUsersIt);
13438   }
13439 }
13440 
13441 void
13442 ScalarEvolution::getUsedLoops(const SCEV *S,
13443                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13444   struct FindUsedLoops {
13445     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13446         : LoopsUsed(LoopsUsed) {}
13447     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13448     bool follow(const SCEV *S) {
13449       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13450         LoopsUsed.insert(AR->getLoop());
13451       return true;
13452     }
13453 
13454     bool isDone() const { return false; }
13455   };
13456 
13457   FindUsedLoops F(LoopsUsed);
13458   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13459 }
13460 
13461 void ScalarEvolution::getReachableBlocks(
13462     SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13463   SmallVector<BasicBlock *> Worklist;
13464   Worklist.push_back(&F.getEntryBlock());
13465   while (!Worklist.empty()) {
13466     BasicBlock *BB = Worklist.pop_back_val();
13467     if (!Reachable.insert(BB).second)
13468       continue;
13469 
13470     Value *Cond;
13471     BasicBlock *TrueBB, *FalseBB;
13472     if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13473                                         m_BasicBlock(FalseBB)))) {
13474       if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13475         Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13476         continue;
13477       }
13478 
13479       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13480         const SCEV *L = getSCEV(Cmp->getOperand(0));
13481         const SCEV *R = getSCEV(Cmp->getOperand(1));
13482         if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13483           Worklist.push_back(TrueBB);
13484           continue;
13485         }
13486         if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13487                                               R)) {
13488           Worklist.push_back(FalseBB);
13489           continue;
13490         }
13491       }
13492     }
13493 
13494     append_range(Worklist, successors(BB));
13495   }
13496 }
13497 
13498 void ScalarEvolution::verify() const {
13499   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13500   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13501 
13502   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13503 
13504   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13505   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13506     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13507 
13508     const SCEV *visitConstant(const SCEVConstant *Constant) {
13509       return SE.getConstant(Constant->getAPInt());
13510     }
13511 
13512     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13513       return SE.getUnknown(Expr->getValue());
13514     }
13515 
13516     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13517       return SE.getCouldNotCompute();
13518     }
13519   };
13520 
13521   SCEVMapper SCM(SE2);
13522   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13523   SE2.getReachableBlocks(ReachableBlocks, F);
13524 
13525   auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13526     if (containsUndefs(Old) || containsUndefs(New)) {
13527       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13528       // not propagate undef aggressively).  This means we can (and do) fail
13529       // verification in cases where a transform makes a value go from "undef"
13530       // to "undef+1" (say).  The transform is fine, since in both cases the
13531       // result is "undef", but SCEV thinks the value increased by 1.
13532       return nullptr;
13533     }
13534 
13535     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13536     const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13537     if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13538       return nullptr;
13539 
13540     return Delta;
13541   };
13542 
13543   while (!LoopStack.empty()) {
13544     auto *L = LoopStack.pop_back_val();
13545     llvm::append_range(LoopStack, *L);
13546 
13547     // Only verify BECounts in reachable loops. For an unreachable loop,
13548     // any BECount is legal.
13549     if (!ReachableBlocks.contains(L->getHeader()))
13550       continue;
13551 
13552     // Only verify cached BECounts. Computing new BECounts may change the
13553     // results of subsequent SCEV uses.
13554     auto It = BackedgeTakenCounts.find(L);
13555     if (It == BackedgeTakenCounts.end())
13556       continue;
13557 
13558     auto *CurBECount =
13559         SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
13560     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13561 
13562     if (CurBECount == SE2.getCouldNotCompute() ||
13563         NewBECount == SE2.getCouldNotCompute()) {
13564       // NB! This situation is legal, but is very suspicious -- whatever pass
13565       // change the loop to make a trip count go from could not compute to
13566       // computable or vice-versa *should have* invalidated SCEV.  However, we
13567       // choose not to assert here (for now) since we don't want false
13568       // positives.
13569       continue;
13570     }
13571 
13572     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13573         SE.getTypeSizeInBits(NewBECount->getType()))
13574       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13575     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13576              SE.getTypeSizeInBits(NewBECount->getType()))
13577       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13578 
13579     const SCEV *Delta = GetDelta(CurBECount, NewBECount);
13580     if (Delta && !Delta->isZero()) {
13581       dbgs() << "Trip Count for " << *L << " Changed!\n";
13582       dbgs() << "Old: " << *CurBECount << "\n";
13583       dbgs() << "New: " << *NewBECount << "\n";
13584       dbgs() << "Delta: " << *Delta << "\n";
13585       std::abort();
13586     }
13587   }
13588 
13589   // Collect all valid loops currently in LoopInfo.
13590   SmallPtrSet<Loop *, 32> ValidLoops;
13591   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13592   while (!Worklist.empty()) {
13593     Loop *L = Worklist.pop_back_val();
13594     if (ValidLoops.insert(L).second)
13595       Worklist.append(L->begin(), L->end());
13596   }
13597   for (auto &KV : ValueExprMap) {
13598 #ifndef NDEBUG
13599     // Check for SCEV expressions referencing invalid/deleted loops.
13600     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
13601       assert(ValidLoops.contains(AR->getLoop()) &&
13602              "AddRec references invalid loop");
13603     }
13604 #endif
13605 
13606     // Check that the value is also part of the reverse map.
13607     auto It = ExprValueMap.find(KV.second);
13608     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
13609       dbgs() << "Value " << *KV.first
13610              << " is in ValueExprMap but not in ExprValueMap\n";
13611       std::abort();
13612     }
13613 
13614     if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
13615       if (!ReachableBlocks.contains(I->getParent()))
13616         continue;
13617       const SCEV *OldSCEV = SCM.visit(KV.second);
13618       const SCEV *NewSCEV = SE2.getSCEV(I);
13619       const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
13620       if (Delta && !Delta->isZero()) {
13621         dbgs() << "SCEV for value " << *I << " changed!\n"
13622                << "Old: " << *OldSCEV << "\n"
13623                << "New: " << *NewSCEV << "\n"
13624                << "Delta: " << *Delta << "\n";
13625         std::abort();
13626       }
13627     }
13628   }
13629 
13630   for (const auto &KV : ExprValueMap) {
13631     for (Value *V : KV.second) {
13632       auto It = ValueExprMap.find_as(V);
13633       if (It == ValueExprMap.end()) {
13634         dbgs() << "Value " << *V
13635                << " is in ExprValueMap but not in ValueExprMap\n";
13636         std::abort();
13637       }
13638       if (It->second != KV.first) {
13639         dbgs() << "Value " << *V << " mapped to " << *It->second
13640                << " rather than " << *KV.first << "\n";
13641         std::abort();
13642       }
13643     }
13644   }
13645 
13646   // Verify integrity of SCEV users.
13647   for (const auto &S : UniqueSCEVs) {
13648     SmallVector<const SCEV *, 4> Ops;
13649     collectUniqueOps(&S, Ops);
13650     for (const auto *Op : Ops) {
13651       // We do not store dependencies of constants.
13652       if (isa<SCEVConstant>(Op))
13653         continue;
13654       auto It = SCEVUsers.find(Op);
13655       if (It != SCEVUsers.end() && It->second.count(&S))
13656         continue;
13657       dbgs() << "Use of operand  " << *Op << " by user " << S
13658              << " is not being tracked!\n";
13659       std::abort();
13660     }
13661   }
13662 
13663   // Verify integrity of ValuesAtScopes users.
13664   for (const auto &ValueAndVec : ValuesAtScopes) {
13665     const SCEV *Value = ValueAndVec.first;
13666     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
13667       const Loop *L = LoopAndValueAtScope.first;
13668       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
13669       if (!isa<SCEVConstant>(ValueAtScope)) {
13670         auto It = ValuesAtScopesUsers.find(ValueAtScope);
13671         if (It != ValuesAtScopesUsers.end() &&
13672             is_contained(It->second, std::make_pair(L, Value)))
13673           continue;
13674         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13675                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
13676         std::abort();
13677       }
13678     }
13679   }
13680 
13681   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
13682     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
13683     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
13684       const Loop *L = LoopAndValue.first;
13685       const SCEV *Value = LoopAndValue.second;
13686       assert(!isa<SCEVConstant>(Value));
13687       auto It = ValuesAtScopes.find(Value);
13688       if (It != ValuesAtScopes.end() &&
13689           is_contained(It->second, std::make_pair(L, ValueAtScope)))
13690         continue;
13691       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13692              << *ValueAtScope << " missing in ValuesAtScopes\n";
13693       std::abort();
13694     }
13695   }
13696 
13697   // Verify integrity of BECountUsers.
13698   auto VerifyBECountUsers = [&](bool Predicated) {
13699     auto &BECounts =
13700         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13701     for (const auto &LoopAndBEInfo : BECounts) {
13702       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
13703         if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13704           auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13705           if (UserIt != BECountUsers.end() &&
13706               UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
13707             continue;
13708           dbgs() << "Value " << *ENT.ExactNotTaken << " for loop "
13709                  << *LoopAndBEInfo.first << " missing from BECountUsers\n";
13710           std::abort();
13711         }
13712       }
13713     }
13714   };
13715   VerifyBECountUsers(/* Predicated */ false);
13716   VerifyBECountUsers(/* Predicated */ true);
13717 }
13718 
13719 bool ScalarEvolution::invalidate(
13720     Function &F, const PreservedAnalyses &PA,
13721     FunctionAnalysisManager::Invalidator &Inv) {
13722   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13723   // of its dependencies is invalidated.
13724   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13725   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13726          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13727          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13728          Inv.invalidate<LoopAnalysis>(F, PA);
13729 }
13730 
13731 AnalysisKey ScalarEvolutionAnalysis::Key;
13732 
13733 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13734                                              FunctionAnalysisManager &AM) {
13735   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13736                          AM.getResult<AssumptionAnalysis>(F),
13737                          AM.getResult<DominatorTreeAnalysis>(F),
13738                          AM.getResult<LoopAnalysis>(F));
13739 }
13740 
13741 PreservedAnalyses
13742 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13743   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13744   return PreservedAnalyses::all();
13745 }
13746 
13747 PreservedAnalyses
13748 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13749   // For compatibility with opt's -analyze feature under legacy pass manager
13750   // which was not ported to NPM. This keeps tests using
13751   // update_analyze_test_checks.py working.
13752   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13753      << F.getName() << "':\n";
13754   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13755   return PreservedAnalyses::all();
13756 }
13757 
13758 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13759                       "Scalar Evolution Analysis", false, true)
13760 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13761 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13762 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13763 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13764 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13765                     "Scalar Evolution Analysis", false, true)
13766 
13767 char ScalarEvolutionWrapperPass::ID = 0;
13768 
13769 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13770   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13771 }
13772 
13773 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13774   SE.reset(new ScalarEvolution(
13775       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13776       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13777       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13778       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13779   return false;
13780 }
13781 
13782 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13783 
13784 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13785   SE->print(OS);
13786 }
13787 
13788 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13789   if (!VerifySCEV)
13790     return;
13791 
13792   SE->verify();
13793 }
13794 
13795 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13796   AU.setPreservesAll();
13797   AU.addRequiredTransitive<AssumptionCacheTracker>();
13798   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13799   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13800   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13801 }
13802 
13803 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13804                                                         const SCEV *RHS) {
13805   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
13806 }
13807 
13808 const SCEVPredicate *
13809 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
13810                                      const SCEV *LHS, const SCEV *RHS) {
13811   FoldingSetNodeID ID;
13812   assert(LHS->getType() == RHS->getType() &&
13813          "Type mismatch between LHS and RHS");
13814   // Unique this node based on the arguments
13815   ID.AddInteger(SCEVPredicate::P_Compare);
13816   ID.AddInteger(Pred);
13817   ID.AddPointer(LHS);
13818   ID.AddPointer(RHS);
13819   void *IP = nullptr;
13820   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13821     return S;
13822   SCEVComparePredicate *Eq = new (SCEVAllocator)
13823     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
13824   UniquePreds.InsertNode(Eq, IP);
13825   return Eq;
13826 }
13827 
13828 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13829     const SCEVAddRecExpr *AR,
13830     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13831   FoldingSetNodeID ID;
13832   // Unique this node based on the arguments
13833   ID.AddInteger(SCEVPredicate::P_Wrap);
13834   ID.AddPointer(AR);
13835   ID.AddInteger(AddedFlags);
13836   void *IP = nullptr;
13837   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13838     return S;
13839   auto *OF = new (SCEVAllocator)
13840       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13841   UniquePreds.InsertNode(OF, IP);
13842   return OF;
13843 }
13844 
13845 namespace {
13846 
13847 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13848 public:
13849 
13850   /// Rewrites \p S in the context of a loop L and the SCEV predication
13851   /// infrastructure.
13852   ///
13853   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13854   /// equivalences present in \p Pred.
13855   ///
13856   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13857   /// \p NewPreds such that the result will be an AddRecExpr.
13858   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13859                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13860                              const SCEVPredicate *Pred) {
13861     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13862     return Rewriter.visit(S);
13863   }
13864 
13865   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13866     if (Pred) {
13867       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
13868         for (auto *Pred : U->getPredicates())
13869           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
13870             if (IPred->getLHS() == Expr &&
13871                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
13872               return IPred->getRHS();
13873       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
13874         if (IPred->getLHS() == Expr &&
13875             IPred->getPredicate() == ICmpInst::ICMP_EQ)
13876           return IPred->getRHS();
13877       }
13878     }
13879     return convertToAddRecWithPreds(Expr);
13880   }
13881 
13882   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13883     const SCEV *Operand = visit(Expr->getOperand());
13884     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13885     if (AR && AR->getLoop() == L && AR->isAffine()) {
13886       // This couldn't be folded because the operand didn't have the nuw
13887       // flag. Add the nusw flag as an assumption that we could make.
13888       const SCEV *Step = AR->getStepRecurrence(SE);
13889       Type *Ty = Expr->getType();
13890       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13891         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13892                                 SE.getSignExtendExpr(Step, Ty), L,
13893                                 AR->getNoWrapFlags());
13894     }
13895     return SE.getZeroExtendExpr(Operand, Expr->getType());
13896   }
13897 
13898   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13899     const SCEV *Operand = visit(Expr->getOperand());
13900     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13901     if (AR && AR->getLoop() == L && AR->isAffine()) {
13902       // This couldn't be folded because the operand didn't have the nsw
13903       // flag. Add the nssw flag as an assumption that we could make.
13904       const SCEV *Step = AR->getStepRecurrence(SE);
13905       Type *Ty = Expr->getType();
13906       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13907         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13908                                 SE.getSignExtendExpr(Step, Ty), L,
13909                                 AR->getNoWrapFlags());
13910     }
13911     return SE.getSignExtendExpr(Operand, Expr->getType());
13912   }
13913 
13914 private:
13915   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13916                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13917                         const SCEVPredicate *Pred)
13918       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13919 
13920   bool addOverflowAssumption(const SCEVPredicate *P) {
13921     if (!NewPreds) {
13922       // Check if we've already made this assumption.
13923       return Pred && Pred->implies(P);
13924     }
13925     NewPreds->insert(P);
13926     return true;
13927   }
13928 
13929   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13930                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13931     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13932     return addOverflowAssumption(A);
13933   }
13934 
13935   // If \p Expr represents a PHINode, we try to see if it can be represented
13936   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13937   // to add this predicate as a runtime overflow check, we return the AddRec.
13938   // If \p Expr does not meet these conditions (is not a PHI node, or we
13939   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13940   // return \p Expr.
13941   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13942     if (!isa<PHINode>(Expr->getValue()))
13943       return Expr;
13944     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13945     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13946     if (!PredicatedRewrite)
13947       return Expr;
13948     for (auto *P : PredicatedRewrite->second){
13949       // Wrap predicates from outer loops are not supported.
13950       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13951         if (L != WP->getExpr()->getLoop())
13952           return Expr;
13953       }
13954       if (!addOverflowAssumption(P))
13955         return Expr;
13956     }
13957     return PredicatedRewrite->first;
13958   }
13959 
13960   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13961   const SCEVPredicate *Pred;
13962   const Loop *L;
13963 };
13964 
13965 } // end anonymous namespace
13966 
13967 const SCEV *
13968 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13969                                        const SCEVPredicate &Preds) {
13970   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13971 }
13972 
13973 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13974     const SCEV *S, const Loop *L,
13975     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13976   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13977   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13978   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13979 
13980   if (!AddRec)
13981     return nullptr;
13982 
13983   // Since the transformation was successful, we can now transfer the SCEV
13984   // predicates.
13985   for (auto *P : TransformPreds)
13986     Preds.insert(P);
13987 
13988   return AddRec;
13989 }
13990 
13991 /// SCEV predicates
13992 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13993                              SCEVPredicateKind Kind)
13994     : FastID(ID), Kind(Kind) {}
13995 
13996 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
13997                                    const ICmpInst::Predicate Pred,
13998                                    const SCEV *LHS, const SCEV *RHS)
13999   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14000   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
14001   assert(LHS != RHS && "LHS and RHS are the same SCEV");
14002 }
14003 
14004 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14005   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14006 
14007   if (!Op)
14008     return false;
14009 
14010   if (Pred != ICmpInst::ICMP_EQ)
14011     return false;
14012 
14013   return Op->LHS == LHS && Op->RHS == RHS;
14014 }
14015 
14016 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14017 
14018 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14019   if (Pred == ICmpInst::ICMP_EQ)
14020     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14021   else
14022     OS.indent(Depth) << "Compare predicate: " << *LHS
14023                      << " " << CmpInst::getPredicateName(Pred) << ") "
14024                      << *RHS << "\n";
14025 
14026 }
14027 
14028 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14029                                      const SCEVAddRecExpr *AR,
14030                                      IncrementWrapFlags Flags)
14031     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14032 
14033 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14034 
14035 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14036   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14037 
14038   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14039 }
14040 
14041 bool SCEVWrapPredicate::isAlwaysTrue() const {
14042   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14043   IncrementWrapFlags IFlags = Flags;
14044 
14045   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14046     IFlags = clearFlags(IFlags, IncrementNSSW);
14047 
14048   return IFlags == IncrementAnyWrap;
14049 }
14050 
14051 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14052   OS.indent(Depth) << *getExpr() << " Added Flags: ";
14053   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14054     OS << "<nusw>";
14055   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14056     OS << "<nssw>";
14057   OS << "\n";
14058 }
14059 
14060 SCEVWrapPredicate::IncrementWrapFlags
14061 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14062                                    ScalarEvolution &SE) {
14063   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14064   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14065 
14066   // We can safely transfer the NSW flag as NSSW.
14067   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14068     ImpliedFlags = IncrementNSSW;
14069 
14070   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14071     // If the increment is positive, the SCEV NUW flag will also imply the
14072     // WrapPredicate NUSW flag.
14073     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14074       if (Step->getValue()->getValue().isNonNegative())
14075         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14076   }
14077 
14078   return ImpliedFlags;
14079 }
14080 
14081 /// Union predicates don't get cached so create a dummy set ID for it.
14082 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14083   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14084   for (auto *P : Preds)
14085     add(P);
14086 }
14087 
14088 bool SCEVUnionPredicate::isAlwaysTrue() const {
14089   return all_of(Preds,
14090                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14091 }
14092 
14093 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14094   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14095     return all_of(Set->Preds,
14096                   [this](const SCEVPredicate *I) { return this->implies(I); });
14097 
14098   return any_of(Preds,
14099                 [N](const SCEVPredicate *I) { return I->implies(N); });
14100 }
14101 
14102 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14103   for (auto Pred : Preds)
14104     Pred->print(OS, Depth);
14105 }
14106 
14107 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14108   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14109     for (auto Pred : Set->Preds)
14110       add(Pred);
14111     return;
14112   }
14113 
14114   Preds.push_back(N);
14115 }
14116 
14117 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14118                                                      Loop &L)
14119     : SE(SE), L(L) {
14120   SmallVector<const SCEVPredicate*, 4> Empty;
14121   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14122 }
14123 
14124 void ScalarEvolution::registerUser(const SCEV *User,
14125                                    ArrayRef<const SCEV *> Ops) {
14126   for (auto *Op : Ops)
14127     // We do not expect that forgetting cached data for SCEVConstants will ever
14128     // open any prospects for sharpening or introduce any correctness issues,
14129     // so we don't bother storing their dependencies.
14130     if (!isa<SCEVConstant>(Op))
14131       SCEVUsers[Op].insert(User);
14132 }
14133 
14134 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14135   const SCEV *Expr = SE.getSCEV(V);
14136   RewriteEntry &Entry = RewriteMap[Expr];
14137 
14138   // If we already have an entry and the version matches, return it.
14139   if (Entry.second && Generation == Entry.first)
14140     return Entry.second;
14141 
14142   // We found an entry but it's stale. Rewrite the stale entry
14143   // according to the current predicate.
14144   if (Entry.second)
14145     Expr = Entry.second;
14146 
14147   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14148   Entry = {Generation, NewSCEV};
14149 
14150   return NewSCEV;
14151 }
14152 
14153 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14154   if (!BackedgeCount) {
14155     SmallVector<const SCEVPredicate *, 4> Preds;
14156     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14157     for (auto *P : Preds)
14158       addPredicate(*P);
14159   }
14160   return BackedgeCount;
14161 }
14162 
14163 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14164   if (Preds->implies(&Pred))
14165     return;
14166 
14167   auto &OldPreds = Preds->getPredicates();
14168   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14169   NewPreds.push_back(&Pred);
14170   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14171   updateGeneration();
14172 }
14173 
14174 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14175   return *Preds;
14176 }
14177 
14178 void PredicatedScalarEvolution::updateGeneration() {
14179   // If the generation number wrapped recompute everything.
14180   if (++Generation == 0) {
14181     for (auto &II : RewriteMap) {
14182       const SCEV *Rewritten = II.second.second;
14183       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14184     }
14185   }
14186 }
14187 
14188 void PredicatedScalarEvolution::setNoOverflow(
14189     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14190   const SCEV *Expr = getSCEV(V);
14191   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14192 
14193   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14194 
14195   // Clear the statically implied flags.
14196   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14197   addPredicate(*SE.getWrapPredicate(AR, Flags));
14198 
14199   auto II = FlagsMap.insert({V, Flags});
14200   if (!II.second)
14201     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14202 }
14203 
14204 bool PredicatedScalarEvolution::hasNoOverflow(
14205     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14206   const SCEV *Expr = getSCEV(V);
14207   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14208 
14209   Flags = SCEVWrapPredicate::clearFlags(
14210       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14211 
14212   auto II = FlagsMap.find(V);
14213 
14214   if (II != FlagsMap.end())
14215     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14216 
14217   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14218 }
14219 
14220 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14221   const SCEV *Expr = this->getSCEV(V);
14222   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14223   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14224 
14225   if (!New)
14226     return nullptr;
14227 
14228   for (auto *P : NewPreds)
14229     addPredicate(*P);
14230 
14231   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14232   return New;
14233 }
14234 
14235 PredicatedScalarEvolution::PredicatedScalarEvolution(
14236     const PredicatedScalarEvolution &Init)
14237   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14238     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14239     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14240   for (auto I : Init.FlagsMap)
14241     FlagsMap.insert(I);
14242 }
14243 
14244 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14245   // For each block.
14246   for (auto *BB : L.getBlocks())
14247     for (auto &I : *BB) {
14248       if (!SE.isSCEVable(I.getType()))
14249         continue;
14250 
14251       auto *Expr = SE.getSCEV(&I);
14252       auto II = RewriteMap.find(Expr);
14253 
14254       if (II == RewriteMap.end())
14255         continue;
14256 
14257       // Don't print things that are not interesting.
14258       if (II->second.second == Expr)
14259         continue;
14260 
14261       OS.indent(Depth) << "[PSE]" << I << ":\n";
14262       OS.indent(Depth + 2) << *Expr << "\n";
14263       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14264     }
14265 }
14266 
14267 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14268 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14269 // for URem with constant power-of-2 second operands.
14270 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14271 // 4, A / B becomes X / 8).
14272 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14273                                 const SCEV *&RHS) {
14274   // Try to match 'zext (trunc A to iB) to iY', which is used
14275   // for URem with constant power-of-2 second operands. Make sure the size of
14276   // the operand A matches the size of the whole expressions.
14277   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14278     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14279       LHS = Trunc->getOperand();
14280       // Bail out if the type of the LHS is larger than the type of the
14281       // expression for now.
14282       if (getTypeSizeInBits(LHS->getType()) >
14283           getTypeSizeInBits(Expr->getType()))
14284         return false;
14285       if (LHS->getType() != Expr->getType())
14286         LHS = getZeroExtendExpr(LHS, Expr->getType());
14287       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14288                         << getTypeSizeInBits(Trunc->getType()));
14289       return true;
14290     }
14291   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14292   if (Add == nullptr || Add->getNumOperands() != 2)
14293     return false;
14294 
14295   const SCEV *A = Add->getOperand(1);
14296   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14297 
14298   if (Mul == nullptr)
14299     return false;
14300 
14301   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14302     // (SomeExpr + (-(SomeExpr / B) * B)).
14303     if (Expr == getURemExpr(A, B)) {
14304       LHS = A;
14305       RHS = B;
14306       return true;
14307     }
14308     return false;
14309   };
14310 
14311   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14312   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14313     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14314            MatchURemWithDivisor(Mul->getOperand(2));
14315 
14316   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14317   if (Mul->getNumOperands() == 2)
14318     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14319            MatchURemWithDivisor(Mul->getOperand(0)) ||
14320            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14321            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14322   return false;
14323 }
14324 
14325 const SCEV *
14326 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14327   SmallVector<BasicBlock*, 16> ExitingBlocks;
14328   L->getExitingBlocks(ExitingBlocks);
14329 
14330   // Form an expression for the maximum exit count possible for this loop. We
14331   // merge the max and exact information to approximate a version of
14332   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14333   SmallVector<const SCEV*, 4> ExitCounts;
14334   for (BasicBlock *ExitingBB : ExitingBlocks) {
14335     const SCEV *ExitCount = getExitCount(L, ExitingBB);
14336     if (isa<SCEVCouldNotCompute>(ExitCount))
14337       ExitCount = getExitCount(L, ExitingBB,
14338                                   ScalarEvolution::ConstantMaximum);
14339     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14340       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14341              "We should only have known counts for exiting blocks that "
14342              "dominate latch!");
14343       ExitCounts.push_back(ExitCount);
14344     }
14345   }
14346   if (ExitCounts.empty())
14347     return getCouldNotCompute();
14348   return getUMinFromMismatchedTypes(ExitCounts);
14349 }
14350 
14351 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14352 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14353 /// replacement is loop invariant in the loop of the AddRec.
14354 ///
14355 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
14356 /// supported.
14357 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14358   const DenseMap<const SCEV *, const SCEV *> &Map;
14359 
14360 public:
14361   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14362                         DenseMap<const SCEV *, const SCEV *> &M)
14363       : SCEVRewriteVisitor(SE), Map(M) {}
14364 
14365   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14366 
14367   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14368     auto I = Map.find(Expr);
14369     if (I == Map.end())
14370       return Expr;
14371     return I->second;
14372   }
14373 
14374   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14375     auto I = Map.find(Expr);
14376     if (I == Map.end())
14377       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14378           Expr);
14379     return I->second;
14380   }
14381 };
14382 
14383 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14384   SmallVector<const SCEV *> ExprsToRewrite;
14385   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14386                               const SCEV *RHS,
14387                               DenseMap<const SCEV *, const SCEV *>
14388                                   &RewriteMap) {
14389     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14390     // replacement SCEV which isn't directly implied by the structure of that
14391     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14392     // legal.  See the scoping rules for flags in the header to understand why.
14393 
14394     // If LHS is a constant, apply information to the other expression.
14395     if (isa<SCEVConstant>(LHS)) {
14396       std::swap(LHS, RHS);
14397       Predicate = CmpInst::getSwappedPredicate(Predicate);
14398     }
14399 
14400     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14401     // create this form when combining two checks of the form (X u< C2 + C1) and
14402     // (X >=u C1).
14403     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14404                                  &ExprsToRewrite]() {
14405       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14406       if (!AddExpr || AddExpr->getNumOperands() != 2)
14407         return false;
14408 
14409       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14410       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14411       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14412       if (!C1 || !C2 || !LHSUnknown)
14413         return false;
14414 
14415       auto ExactRegion =
14416           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14417               .sub(C1->getAPInt());
14418 
14419       // Bail out, unless we have a non-wrapping, monotonic range.
14420       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14421         return false;
14422       auto I = RewriteMap.find(LHSUnknown);
14423       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14424       RewriteMap[LHSUnknown] = getUMaxExpr(
14425           getConstant(ExactRegion.getUnsignedMin()),
14426           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14427       ExprsToRewrite.push_back(LHSUnknown);
14428       return true;
14429     };
14430     if (MatchRangeCheckIdiom())
14431       return;
14432 
14433     // If we have LHS == 0, check if LHS is computing a property of some unknown
14434     // SCEV %v which we can rewrite %v to express explicitly.
14435     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
14436     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
14437         RHSC->getValue()->isNullValue()) {
14438       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
14439       // explicitly express that.
14440       const SCEV *URemLHS = nullptr;
14441       const SCEV *URemRHS = nullptr;
14442       if (matchURem(LHS, URemLHS, URemRHS)) {
14443         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
14444           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
14445           RewriteMap[LHSUnknown] = Multiple;
14446           ExprsToRewrite.push_back(LHSUnknown);
14447           return;
14448         }
14449       }
14450     }
14451 
14452     // Do not apply information for constants or if RHS contains an AddRec.
14453     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
14454       return;
14455 
14456     // If RHS is SCEVUnknown, make sure the information is applied to it.
14457     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
14458       std::swap(LHS, RHS);
14459       Predicate = CmpInst::getSwappedPredicate(Predicate);
14460     }
14461 
14462     // Limit to expressions that can be rewritten.
14463     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
14464       return;
14465 
14466     // Check whether LHS has already been rewritten. In that case we want to
14467     // chain further rewrites onto the already rewritten value.
14468     auto I = RewriteMap.find(LHS);
14469     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
14470 
14471     const SCEV *RewrittenRHS = nullptr;
14472     switch (Predicate) {
14473     case CmpInst::ICMP_ULT:
14474       RewrittenRHS =
14475           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14476       break;
14477     case CmpInst::ICMP_SLT:
14478       RewrittenRHS =
14479           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14480       break;
14481     case CmpInst::ICMP_ULE:
14482       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
14483       break;
14484     case CmpInst::ICMP_SLE:
14485       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
14486       break;
14487     case CmpInst::ICMP_UGT:
14488       RewrittenRHS =
14489           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14490       break;
14491     case CmpInst::ICMP_SGT:
14492       RewrittenRHS =
14493           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14494       break;
14495     case CmpInst::ICMP_UGE:
14496       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
14497       break;
14498     case CmpInst::ICMP_SGE:
14499       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
14500       break;
14501     case CmpInst::ICMP_EQ:
14502       if (isa<SCEVConstant>(RHS))
14503         RewrittenRHS = RHS;
14504       break;
14505     case CmpInst::ICMP_NE:
14506       if (isa<SCEVConstant>(RHS) &&
14507           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
14508         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
14509       break;
14510     default:
14511       break;
14512     }
14513 
14514     if (RewrittenRHS) {
14515       RewriteMap[LHS] = RewrittenRHS;
14516       if (LHS == RewrittenLHS)
14517         ExprsToRewrite.push_back(LHS);
14518     }
14519   };
14520 
14521   SmallVector<std::pair<Value *, bool>> Terms;
14522   // First, collect information from assumptions dominating the loop.
14523   for (auto &AssumeVH : AC.assumptions()) {
14524     if (!AssumeVH)
14525       continue;
14526     auto *AssumeI = cast<CallInst>(AssumeVH);
14527     if (!DT.dominates(AssumeI, L->getHeader()))
14528       continue;
14529     Terms.emplace_back(AssumeI->getOperand(0), true);
14530   }
14531 
14532   // Second, collect conditions from dominating branches. Starting at the loop
14533   // predecessor, climb up the predecessor chain, as long as there are
14534   // predecessors that can be found that have unique successors leading to the
14535   // original header.
14536   // TODO: share this logic with isLoopEntryGuardedByCond.
14537   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
14538            L->getLoopPredecessor(), L->getHeader());
14539        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
14540 
14541     const BranchInst *LoopEntryPredicate =
14542         dyn_cast<BranchInst>(Pair.first->getTerminator());
14543     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
14544       continue;
14545 
14546     Terms.emplace_back(LoopEntryPredicate->getCondition(),
14547                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
14548   }
14549 
14550   // Now apply the information from the collected conditions to RewriteMap.
14551   // Conditions are processed in reverse order, so the earliest conditions is
14552   // processed first. This ensures the SCEVs with the shortest dependency chains
14553   // are constructed first.
14554   DenseMap<const SCEV *, const SCEV *> RewriteMap;
14555   for (auto &E : reverse(Terms)) {
14556     bool EnterIfTrue = E.second;
14557     SmallVector<Value *, 8> Worklist;
14558     SmallPtrSet<Value *, 8> Visited;
14559     Worklist.push_back(E.first);
14560     while (!Worklist.empty()) {
14561       Value *Cond = Worklist.pop_back_val();
14562       if (!Visited.insert(Cond).second)
14563         continue;
14564 
14565       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14566         auto Predicate =
14567             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
14568         const auto *LHS = getSCEV(Cmp->getOperand(0));
14569         const auto *RHS = getSCEV(Cmp->getOperand(1));
14570         CollectCondition(Predicate, LHS, RHS, RewriteMap);
14571         continue;
14572       }
14573 
14574       Value *L, *R;
14575       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
14576                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
14577         Worklist.push_back(L);
14578         Worklist.push_back(R);
14579       }
14580     }
14581   }
14582 
14583   if (RewriteMap.empty())
14584     return Expr;
14585 
14586   // Now that all rewrite information is collect, rewrite the collected
14587   // expressions with the information in the map. This applies information to
14588   // sub-expressions.
14589   if (ExprsToRewrite.size() > 1) {
14590     for (const SCEV *Expr : ExprsToRewrite) {
14591       const SCEV *RewriteTo = RewriteMap[Expr];
14592       RewriteMap.erase(Expr);
14593       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14594       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
14595     }
14596   }
14597 
14598   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14599   return Rewriter.visit(Expr);
14600 }
14601