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 STATISTIC(NumFoundPhiSCCs,
145           "Number of found Phi-composed strongly connected components");
146 
147 static cl::opt<unsigned>
148 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
149                         cl::ZeroOrMore,
150                         cl::desc("Maximum number of iterations SCEV will "
151                                  "symbolically execute a constant "
152                                  "derived loop"),
153                         cl::init(100));
154 
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156 static cl::opt<bool> VerifySCEV(
157     "verify-scev", cl::Hidden,
158     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool> VerifySCEVStrict(
160     "verify-scev-strict", cl::Hidden,
161     cl::desc("Enable stricter verification with -verify-scev is passed"));
162 static cl::opt<bool>
163     VerifySCEVMap("verify-scev-maps", cl::Hidden,
164                   cl::desc("Verify no dangling value in ScalarEvolution's "
165                            "ExprValueMap (slow)"));
166 
167 static cl::opt<bool> VerifyIR(
168     "scev-verify-ir", cl::Hidden,
169     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170     cl::init(false));
171 
172 static cl::opt<unsigned> MulOpsInlineThreshold(
173     "scev-mulops-inline-threshold", cl::Hidden,
174     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175     cl::init(32));
176 
177 static cl::opt<unsigned> AddOpsInlineThreshold(
178     "scev-addops-inline-threshold", cl::Hidden,
179     cl::desc("Threshold for inlining addition operands into a SCEV"),
180     cl::init(500));
181 
182 static cl::opt<unsigned> MaxSCEVCompareDepth(
183     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185     cl::init(32));
186 
187 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
188     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190     cl::init(2));
191 
192 static cl::opt<unsigned> MaxValueCompareDepth(
193     "scalar-evolution-max-value-compare-depth", cl::Hidden,
194     cl::desc("Maximum depth of recursive value complexity comparisons"),
195     cl::init(2));
196 
197 static cl::opt<unsigned>
198     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199                   cl::desc("Maximum depth of recursive arithmetics"),
200                   cl::init(32));
201 
202 static cl::opt<unsigned> MaxConstantEvolvingDepth(
203     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205 
206 static cl::opt<unsigned>
207     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209                  cl::init(8));
210 
211 static cl::opt<unsigned>
212     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213                   cl::desc("Max coefficients in AddRec during evolving"),
214                   cl::init(8));
215 
216 static cl::opt<unsigned>
217     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218                   cl::desc("Size of the expression which is considered huge"),
219                   cl::init(4096));
220 
221 static cl::opt<bool>
222 ClassifyExpressions("scalar-evolution-classify-expressions",
223     cl::Hidden, cl::init(true),
224     cl::desc("When printing analysis, include information on every instruction"));
225 
226 static cl::opt<bool> UseExpensiveRangeSharpening(
227     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
228     cl::init(false),
229     cl::desc("Use more powerful methods of sharpening expression ranges. May "
230              "be costly in terms of compile time"));
231 
232 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
233     "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
234     cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
235              "Phi strongly connected components"),
236     cl::init(8));
237 
238 static cl::opt<bool>
239     EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
240                             cl::desc("Handle <= and >= in finite loops"),
241                             cl::init(true));
242 
243 //===----------------------------------------------------------------------===//
244 //                           SCEV class definitions
245 //===----------------------------------------------------------------------===//
246 
247 //===----------------------------------------------------------------------===//
248 // Implementation of the SCEV class.
249 //
250 
251 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
252 LLVM_DUMP_METHOD void SCEV::dump() const {
253   print(dbgs());
254   dbgs() << '\n';
255 }
256 #endif
257 
258 void SCEV::print(raw_ostream &OS) const {
259   switch (getSCEVType()) {
260   case scConstant:
261     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
262     return;
263   case scPtrToInt: {
264     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
265     const SCEV *Op = PtrToInt->getOperand();
266     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
267        << *PtrToInt->getType() << ")";
268     return;
269   }
270   case scTruncate: {
271     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
272     const SCEV *Op = Trunc->getOperand();
273     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
274        << *Trunc->getType() << ")";
275     return;
276   }
277   case scZeroExtend: {
278     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
279     const SCEV *Op = ZExt->getOperand();
280     OS << "(zext " << *Op->getType() << " " << *Op << " to "
281        << *ZExt->getType() << ")";
282     return;
283   }
284   case scSignExtend: {
285     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
286     const SCEV *Op = SExt->getOperand();
287     OS << "(sext " << *Op->getType() << " " << *Op << " to "
288        << *SExt->getType() << ")";
289     return;
290   }
291   case scAddRecExpr: {
292     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
293     OS << "{" << *AR->getOperand(0);
294     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
295       OS << ",+," << *AR->getOperand(i);
296     OS << "}<";
297     if (AR->hasNoUnsignedWrap())
298       OS << "nuw><";
299     if (AR->hasNoSignedWrap())
300       OS << "nsw><";
301     if (AR->hasNoSelfWrap() &&
302         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
303       OS << "nw><";
304     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
305     OS << ">";
306     return;
307   }
308   case scAddExpr:
309   case scMulExpr:
310   case scUMaxExpr:
311   case scSMaxExpr:
312   case scUMinExpr:
313   case scSMinExpr:
314   case scSequentialUMinExpr: {
315     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
316     const char *OpStr = nullptr;
317     switch (NAry->getSCEVType()) {
318     case scAddExpr: OpStr = " + "; break;
319     case scMulExpr: OpStr = " * "; break;
320     case scUMaxExpr: OpStr = " umax "; break;
321     case scSMaxExpr: OpStr = " smax "; break;
322     case scUMinExpr:
323       OpStr = " umin ";
324       break;
325     case scSMinExpr:
326       OpStr = " smin ";
327       break;
328     case scSequentialUMinExpr:
329       OpStr = " umin_seq ";
330       break;
331     default:
332       llvm_unreachable("There are no other nary expression types.");
333     }
334     OS << "(";
335     ListSeparator LS(OpStr);
336     for (const SCEV *Op : NAry->operands())
337       OS << LS << *Op;
338     OS << ")";
339     switch (NAry->getSCEVType()) {
340     case scAddExpr:
341     case scMulExpr:
342       if (NAry->hasNoUnsignedWrap())
343         OS << "<nuw>";
344       if (NAry->hasNoSignedWrap())
345         OS << "<nsw>";
346       break;
347     default:
348       // Nothing to print for other nary expressions.
349       break;
350     }
351     return;
352   }
353   case scUDivExpr: {
354     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
355     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
356     return;
357   }
358   case scUnknown: {
359     const SCEVUnknown *U = cast<SCEVUnknown>(this);
360     Type *AllocTy;
361     if (U->isSizeOf(AllocTy)) {
362       OS << "sizeof(" << *AllocTy << ")";
363       return;
364     }
365     if (U->isAlignOf(AllocTy)) {
366       OS << "alignof(" << *AllocTy << ")";
367       return;
368     }
369 
370     Type *CTy;
371     Constant *FieldNo;
372     if (U->isOffsetOf(CTy, FieldNo)) {
373       OS << "offsetof(" << *CTy << ", ";
374       FieldNo->printAsOperand(OS, false);
375       OS << ")";
376       return;
377     }
378 
379     // Otherwise just print it normally.
380     U->getValue()->printAsOperand(OS, false);
381     return;
382   }
383   case scCouldNotCompute:
384     OS << "***COULDNOTCOMPUTE***";
385     return;
386   }
387   llvm_unreachable("Unknown SCEV kind!");
388 }
389 
390 Type *SCEV::getType() const {
391   switch (getSCEVType()) {
392   case scConstant:
393     return cast<SCEVConstant>(this)->getType();
394   case scPtrToInt:
395   case scTruncate:
396   case scZeroExtend:
397   case scSignExtend:
398     return cast<SCEVCastExpr>(this)->getType();
399   case scAddRecExpr:
400     return cast<SCEVAddRecExpr>(this)->getType();
401   case scMulExpr:
402     return cast<SCEVMulExpr>(this)->getType();
403   case scUMaxExpr:
404   case scSMaxExpr:
405   case scUMinExpr:
406   case scSMinExpr:
407     return cast<SCEVMinMaxExpr>(this)->getType();
408   case scSequentialUMinExpr:
409     return cast<SCEVSequentialMinMaxExpr>(this)->getType();
410   case scAddExpr:
411     return cast<SCEVAddExpr>(this)->getType();
412   case scUDivExpr:
413     return cast<SCEVUDivExpr>(this)->getType();
414   case scUnknown:
415     return cast<SCEVUnknown>(this)->getType();
416   case scCouldNotCompute:
417     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
418   }
419   llvm_unreachable("Unknown SCEV kind!");
420 }
421 
422 bool SCEV::isZero() const {
423   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
424     return SC->getValue()->isZero();
425   return false;
426 }
427 
428 bool SCEV::isOne() const {
429   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
430     return SC->getValue()->isOne();
431   return false;
432 }
433 
434 bool SCEV::isAllOnesValue() const {
435   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
436     return SC->getValue()->isMinusOne();
437   return false;
438 }
439 
440 bool SCEV::isNonConstantNegative() const {
441   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
442   if (!Mul) return false;
443 
444   // If there is a constant factor, it will be first.
445   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
446   if (!SC) return false;
447 
448   // Return true if the value is negative, this matches things like (-42 * V).
449   return SC->getAPInt().isNegative();
450 }
451 
452 SCEVCouldNotCompute::SCEVCouldNotCompute() :
453   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
454 
455 bool SCEVCouldNotCompute::classof(const SCEV *S) {
456   return S->getSCEVType() == scCouldNotCompute;
457 }
458 
459 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
460   FoldingSetNodeID ID;
461   ID.AddInteger(scConstant);
462   ID.AddPointer(V);
463   void *IP = nullptr;
464   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
465   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
466   UniqueSCEVs.InsertNode(S, IP);
467   return S;
468 }
469 
470 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
471   return getConstant(ConstantInt::get(getContext(), Val));
472 }
473 
474 const SCEV *
475 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
476   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
477   return getConstant(ConstantInt::get(ITy, V, isSigned));
478 }
479 
480 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
481                            const SCEV *op, Type *ty)
482     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
483   Operands[0] = op;
484 }
485 
486 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
487                                    Type *ITy)
488     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
489   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
490          "Must be a non-bit-width-changing pointer-to-integer cast!");
491 }
492 
493 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
494                                            SCEVTypes SCEVTy, const SCEV *op,
495                                            Type *ty)
496     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
497 
498 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
499                                    Type *ty)
500     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
501   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
502          "Cannot truncate non-integer value!");
503 }
504 
505 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
506                                        const SCEV *op, Type *ty)
507     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
508   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
509          "Cannot zero extend non-integer value!");
510 }
511 
512 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
513                                        const SCEV *op, Type *ty)
514     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
515   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
516          "Cannot sign extend non-integer value!");
517 }
518 
519 void SCEVUnknown::deleted() {
520   // Clear this SCEVUnknown from various maps.
521   SE->forgetMemoizedResults(this);
522 
523   // Remove this SCEVUnknown from the uniquing map.
524   SE->UniqueSCEVs.RemoveNode(this);
525 
526   // Release the value.
527   setValPtr(nullptr);
528 }
529 
530 void SCEVUnknown::allUsesReplacedWith(Value *New) {
531   // Remove this SCEVUnknown from the uniquing map.
532   SE->UniqueSCEVs.RemoveNode(this);
533 
534   // Update this SCEVUnknown to point to the new value. This is needed
535   // because there may still be outstanding SCEVs which still point to
536   // this SCEVUnknown.
537   setValPtr(New);
538 }
539 
540 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
541   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
542     if (VCE->getOpcode() == Instruction::PtrToInt)
543       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
544         if (CE->getOpcode() == Instruction::GetElementPtr &&
545             CE->getOperand(0)->isNullValue() &&
546             CE->getNumOperands() == 2)
547           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
548             if (CI->isOne()) {
549               AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
550               return true;
551             }
552 
553   return false;
554 }
555 
556 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
557   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
558     if (VCE->getOpcode() == Instruction::PtrToInt)
559       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
560         if (CE->getOpcode() == Instruction::GetElementPtr &&
561             CE->getOperand(0)->isNullValue()) {
562           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
563           if (StructType *STy = dyn_cast<StructType>(Ty))
564             if (!STy->isPacked() &&
565                 CE->getNumOperands() == 3 &&
566                 CE->getOperand(1)->isNullValue()) {
567               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
568                 if (CI->isOne() &&
569                     STy->getNumElements() == 2 &&
570                     STy->getElementType(0)->isIntegerTy(1)) {
571                   AllocTy = STy->getElementType(1);
572                   return true;
573                 }
574             }
575         }
576 
577   return false;
578 }
579 
580 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
581   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
582     if (VCE->getOpcode() == Instruction::PtrToInt)
583       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
584         if (CE->getOpcode() == Instruction::GetElementPtr &&
585             CE->getNumOperands() == 3 &&
586             CE->getOperand(0)->isNullValue() &&
587             CE->getOperand(1)->isNullValue()) {
588           Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
589           // Ignore vector types here so that ScalarEvolutionExpander doesn't
590           // emit getelementptrs that index into vectors.
591           if (Ty->isStructTy() || Ty->isArrayTy()) {
592             CTy = Ty;
593             FieldNo = CE->getOperand(2);
594             return true;
595           }
596         }
597 
598   return false;
599 }
600 
601 //===----------------------------------------------------------------------===//
602 //                               SCEV Utilities
603 //===----------------------------------------------------------------------===//
604 
605 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
606 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
607 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
608 /// have been previously deemed to be "equally complex" by this routine.  It is
609 /// intended to avoid exponential time complexity in cases like:
610 ///
611 ///   %a = f(%x, %y)
612 ///   %b = f(%a, %a)
613 ///   %c = f(%b, %b)
614 ///
615 ///   %d = f(%x, %y)
616 ///   %e = f(%d, %d)
617 ///   %f = f(%e, %e)
618 ///
619 ///   CompareValueComplexity(%f, %c)
620 ///
621 /// Since we do not continue running this routine on expression trees once we
622 /// have seen unequal values, there is no need to track them in the cache.
623 static int
624 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
625                        const LoopInfo *const LI, Value *LV, Value *RV,
626                        unsigned Depth) {
627   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
628     return 0;
629 
630   // Order pointer values after integer values. This helps SCEVExpander form
631   // GEPs.
632   bool LIsPointer = LV->getType()->isPointerTy(),
633        RIsPointer = RV->getType()->isPointerTy();
634   if (LIsPointer != RIsPointer)
635     return (int)LIsPointer - (int)RIsPointer;
636 
637   // Compare getValueID values.
638   unsigned LID = LV->getValueID(), RID = RV->getValueID();
639   if (LID != RID)
640     return (int)LID - (int)RID;
641 
642   // Sort arguments by their position.
643   if (const auto *LA = dyn_cast<Argument>(LV)) {
644     const auto *RA = cast<Argument>(RV);
645     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
646     return (int)LArgNo - (int)RArgNo;
647   }
648 
649   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
650     const auto *RGV = cast<GlobalValue>(RV);
651 
652     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
653       auto LT = GV->getLinkage();
654       return !(GlobalValue::isPrivateLinkage(LT) ||
655                GlobalValue::isInternalLinkage(LT));
656     };
657 
658     // Use the names to distinguish the two values, but only if the
659     // names are semantically important.
660     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
661       return LGV->getName().compare(RGV->getName());
662   }
663 
664   // For instructions, compare their loop depth, and their operand count.  This
665   // is pretty loose.
666   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
667     const auto *RInst = cast<Instruction>(RV);
668 
669     // Compare loop depths.
670     const BasicBlock *LParent = LInst->getParent(),
671                      *RParent = RInst->getParent();
672     if (LParent != RParent) {
673       unsigned LDepth = LI->getLoopDepth(LParent),
674                RDepth = LI->getLoopDepth(RParent);
675       if (LDepth != RDepth)
676         return (int)LDepth - (int)RDepth;
677     }
678 
679     // Compare the number of operands.
680     unsigned LNumOps = LInst->getNumOperands(),
681              RNumOps = RInst->getNumOperands();
682     if (LNumOps != RNumOps)
683       return (int)LNumOps - (int)RNumOps;
684 
685     for (unsigned Idx : seq(0u, LNumOps)) {
686       int Result =
687           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
688                                  RInst->getOperand(Idx), Depth + 1);
689       if (Result != 0)
690         return Result;
691     }
692   }
693 
694   EqCacheValue.unionSets(LV, RV);
695   return 0;
696 }
697 
698 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
699 // than RHS, respectively. A three-way result allows recursive comparisons to be
700 // more efficient.
701 // If the max analysis depth was reached, return None, assuming we do not know
702 // if they are equivalent for sure.
703 static Optional<int>
704 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
705                       EquivalenceClasses<const Value *> &EqCacheValue,
706                       const LoopInfo *const LI, const SCEV *LHS,
707                       const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
708   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
709   if (LHS == RHS)
710     return 0;
711 
712   // Primarily, sort the SCEVs by their getSCEVType().
713   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
714   if (LType != RType)
715     return (int)LType - (int)RType;
716 
717   if (EqCacheSCEV.isEquivalent(LHS, RHS))
718     return 0;
719 
720   if (Depth > MaxSCEVCompareDepth)
721     return None;
722 
723   // Aside from the getSCEVType() ordering, the particular ordering
724   // isn't very important except that it's beneficial to be consistent,
725   // so that (a + b) and (b + a) don't end up as different expressions.
726   switch (LType) {
727   case scUnknown: {
728     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
729     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
730 
731     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
732                                    RU->getValue(), Depth + 1);
733     if (X == 0)
734       EqCacheSCEV.unionSets(LHS, RHS);
735     return X;
736   }
737 
738   case scConstant: {
739     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
740     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
741 
742     // Compare constant values.
743     const APInt &LA = LC->getAPInt();
744     const APInt &RA = RC->getAPInt();
745     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
746     if (LBitWidth != RBitWidth)
747       return (int)LBitWidth - (int)RBitWidth;
748     return LA.ult(RA) ? -1 : 1;
749   }
750 
751   case scAddRecExpr: {
752     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
753     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
754 
755     // There is always a dominance between two recs that are used by one SCEV,
756     // so we can safely sort recs by loop header dominance. We require such
757     // order in getAddExpr.
758     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
759     if (LLoop != RLoop) {
760       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
761       assert(LHead != RHead && "Two loops share the same header?");
762       if (DT.dominates(LHead, RHead))
763         return 1;
764       else
765         assert(DT.dominates(RHead, LHead) &&
766                "No dominance between recurrences used by one SCEV?");
767       return -1;
768     }
769 
770     // Addrec complexity grows with operand count.
771     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
772     if (LNumOps != RNumOps)
773       return (int)LNumOps - (int)RNumOps;
774 
775     // Lexicographically compare.
776     for (unsigned i = 0; i != LNumOps; ++i) {
777       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
778                                      LA->getOperand(i), RA->getOperand(i), DT,
779                                      Depth + 1);
780       if (X != 0)
781         return X;
782     }
783     EqCacheSCEV.unionSets(LHS, RHS);
784     return 0;
785   }
786 
787   case scAddExpr:
788   case scMulExpr:
789   case scSMaxExpr:
790   case scUMaxExpr:
791   case scSMinExpr:
792   case scUMinExpr:
793   case scSequentialUMinExpr: {
794     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
795     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
796 
797     // Lexicographically compare n-ary expressions.
798     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
799     if (LNumOps != RNumOps)
800       return (int)LNumOps - (int)RNumOps;
801 
802     for (unsigned i = 0; i != LNumOps; ++i) {
803       auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
804                                      LC->getOperand(i), RC->getOperand(i), DT,
805                                      Depth + 1);
806       if (X != 0)
807         return X;
808     }
809     EqCacheSCEV.unionSets(LHS, RHS);
810     return 0;
811   }
812 
813   case scUDivExpr: {
814     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
815     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
816 
817     // Lexicographically compare udiv expressions.
818     auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
819                                    RC->getLHS(), DT, Depth + 1);
820     if (X != 0)
821       return X;
822     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
823                               RC->getRHS(), DT, Depth + 1);
824     if (X == 0)
825       EqCacheSCEV.unionSets(LHS, RHS);
826     return X;
827   }
828 
829   case scPtrToInt:
830   case scTruncate:
831   case scZeroExtend:
832   case scSignExtend: {
833     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
834     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
835 
836     // Compare cast expressions by operand.
837     auto X =
838         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(),
839                               RC->getOperand(), DT, Depth + 1);
840     if (X == 0)
841       EqCacheSCEV.unionSets(LHS, RHS);
842     return X;
843   }
844 
845   case scCouldNotCompute:
846     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
847   }
848   llvm_unreachable("Unknown SCEV kind!");
849 }
850 
851 /// Given a list of SCEV objects, order them by their complexity, and group
852 /// objects of the same complexity together by value.  When this routine is
853 /// finished, we know that any duplicates in the vector are consecutive and that
854 /// complexity is monotonically increasing.
855 ///
856 /// Note that we go take special precautions to ensure that we get deterministic
857 /// results from this routine.  In other words, we don't want the results of
858 /// this to depend on where the addresses of various SCEV objects happened to
859 /// land in memory.
860 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
861                               LoopInfo *LI, DominatorTree &DT) {
862   if (Ops.size() < 2) return;  // Noop
863 
864   EquivalenceClasses<const SCEV *> EqCacheSCEV;
865   EquivalenceClasses<const Value *> EqCacheValue;
866 
867   // Whether LHS has provably less complexity than RHS.
868   auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
869     auto Complexity =
870         CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
871     return Complexity && *Complexity < 0;
872   };
873   if (Ops.size() == 2) {
874     // This is the common case, which also happens to be trivially simple.
875     // Special case it.
876     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
877     if (IsLessComplex(RHS, LHS))
878       std::swap(LHS, RHS);
879     return;
880   }
881 
882   // Do the rough sort by complexity.
883   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
884     return IsLessComplex(LHS, RHS);
885   });
886 
887   // Now that we are sorted by complexity, group elements of the same
888   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
889   // be extremely short in practice.  Note that we take this approach because we
890   // do not want to depend on the addresses of the objects we are grouping.
891   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
892     const SCEV *S = Ops[i];
893     unsigned Complexity = S->getSCEVType();
894 
895     // If there are any objects of the same complexity and same value as this
896     // one, group them.
897     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
898       if (Ops[j] == S) { // Found a duplicate.
899         // Move it to immediately after i'th element.
900         std::swap(Ops[i+1], Ops[j]);
901         ++i;   // no need to rescan it.
902         if (i == e-2) return;  // Done!
903       }
904     }
905   }
906 }
907 
908 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
909 /// least HugeExprThreshold nodes).
910 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
911   return any_of(Ops, [](const SCEV *S) {
912     return S->getExpressionSize() >= HugeExprThreshold;
913   });
914 }
915 
916 //===----------------------------------------------------------------------===//
917 //                      Simple SCEV method implementations
918 //===----------------------------------------------------------------------===//
919 
920 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
921 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
922                                        ScalarEvolution &SE,
923                                        Type *ResultTy) {
924   // Handle the simplest case efficiently.
925   if (K == 1)
926     return SE.getTruncateOrZeroExtend(It, ResultTy);
927 
928   // We are using the following formula for BC(It, K):
929   //
930   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
931   //
932   // Suppose, W is the bitwidth of the return value.  We must be prepared for
933   // overflow.  Hence, we must assure that the result of our computation is
934   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
935   // safe in modular arithmetic.
936   //
937   // However, this code doesn't use exactly that formula; the formula it uses
938   // is something like the following, where T is the number of factors of 2 in
939   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
940   // exponentiation:
941   //
942   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
943   //
944   // This formula is trivially equivalent to the previous formula.  However,
945   // this formula can be implemented much more efficiently.  The trick is that
946   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
947   // arithmetic.  To do exact division in modular arithmetic, all we have
948   // to do is multiply by the inverse.  Therefore, this step can be done at
949   // width W.
950   //
951   // The next issue is how to safely do the division by 2^T.  The way this
952   // is done is by doing the multiplication step at a width of at least W + T
953   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
954   // when we perform the division by 2^T (which is equivalent to a right shift
955   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
956   // truncated out after the division by 2^T.
957   //
958   // In comparison to just directly using the first formula, this technique
959   // is much more efficient; using the first formula requires W * K bits,
960   // but this formula less than W + K bits. Also, the first formula requires
961   // a division step, whereas this formula only requires multiplies and shifts.
962   //
963   // It doesn't matter whether the subtraction step is done in the calculation
964   // width or the input iteration count's width; if the subtraction overflows,
965   // the result must be zero anyway.  We prefer here to do it in the width of
966   // the induction variable because it helps a lot for certain cases; CodeGen
967   // isn't smart enough to ignore the overflow, which leads to much less
968   // efficient code if the width of the subtraction is wider than the native
969   // register width.
970   //
971   // (It's possible to not widen at all by pulling out factors of 2 before
972   // the multiplication; for example, K=2 can be calculated as
973   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
974   // extra arithmetic, so it's not an obvious win, and it gets
975   // much more complicated for K > 3.)
976 
977   // Protection from insane SCEVs; this bound is conservative,
978   // but it probably doesn't matter.
979   if (K > 1000)
980     return SE.getCouldNotCompute();
981 
982   unsigned W = SE.getTypeSizeInBits(ResultTy);
983 
984   // Calculate K! / 2^T and T; we divide out the factors of two before
985   // multiplying for calculating K! / 2^T to avoid overflow.
986   // Other overflow doesn't matter because we only care about the bottom
987   // W bits of the result.
988   APInt OddFactorial(W, 1);
989   unsigned T = 1;
990   for (unsigned i = 3; i <= K; ++i) {
991     APInt Mult(W, i);
992     unsigned TwoFactors = Mult.countTrailingZeros();
993     T += TwoFactors;
994     Mult.lshrInPlace(TwoFactors);
995     OddFactorial *= Mult;
996   }
997 
998   // We need at least W + T bits for the multiplication step
999   unsigned CalculationBits = W + T;
1000 
1001   // Calculate 2^T, at width T+W.
1002   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1003 
1004   // Calculate the multiplicative inverse of K! / 2^T;
1005   // this multiplication factor will perform the exact division by
1006   // K! / 2^T.
1007   APInt Mod = APInt::getSignedMinValue(W+1);
1008   APInt MultiplyFactor = OddFactorial.zext(W+1);
1009   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1010   MultiplyFactor = MultiplyFactor.trunc(W);
1011 
1012   // Calculate the product, at width T+W
1013   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1014                                                       CalculationBits);
1015   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1016   for (unsigned i = 1; i != K; ++i) {
1017     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1018     Dividend = SE.getMulExpr(Dividend,
1019                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1020   }
1021 
1022   // Divide by 2^T
1023   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1024 
1025   // Truncate the result, and divide by K! / 2^T.
1026 
1027   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1028                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1029 }
1030 
1031 /// Return the value of this chain of recurrences at the specified iteration
1032 /// number.  We can evaluate this recurrence by multiplying each element in the
1033 /// chain by the binomial coefficient corresponding to it.  In other words, we
1034 /// can evaluate {A,+,B,+,C,+,D} as:
1035 ///
1036 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1037 ///
1038 /// where BC(It, k) stands for binomial coefficient.
1039 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1040                                                 ScalarEvolution &SE) const {
1041   return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE);
1042 }
1043 
1044 const SCEV *
1045 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1046                                     const SCEV *It, ScalarEvolution &SE) {
1047   assert(Operands.size() > 0);
1048   const SCEV *Result = Operands[0];
1049   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1050     // The computation is correct in the face of overflow provided that the
1051     // multiplication is performed _after_ the evaluation of the binomial
1052     // coefficient.
1053     const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1054     if (isa<SCEVCouldNotCompute>(Coeff))
1055       return Coeff;
1056 
1057     Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1058   }
1059   return Result;
1060 }
1061 
1062 //===----------------------------------------------------------------------===//
1063 //                    SCEV Expression folder implementations
1064 //===----------------------------------------------------------------------===//
1065 
1066 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1067                                                      unsigned Depth) {
1068   assert(Depth <= 1 &&
1069          "getLosslessPtrToIntExpr() should self-recurse at most once.");
1070 
1071   // We could be called with an integer-typed operands during SCEV rewrites.
1072   // Since the operand is an integer already, just perform zext/trunc/self cast.
1073   if (!Op->getType()->isPointerTy())
1074     return Op;
1075 
1076   // What would be an ID for such a SCEV cast expression?
1077   FoldingSetNodeID ID;
1078   ID.AddInteger(scPtrToInt);
1079   ID.AddPointer(Op);
1080 
1081   void *IP = nullptr;
1082 
1083   // Is there already an expression for such a cast?
1084   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1085     return S;
1086 
1087   // It isn't legal for optimizations to construct new ptrtoint expressions
1088   // for non-integral pointers.
1089   if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1090     return getCouldNotCompute();
1091 
1092   Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1093 
1094   // We can only trivially model ptrtoint if SCEV's effective (integer) type
1095   // is sufficiently wide to represent all possible pointer values.
1096   // We could theoretically teach SCEV to truncate wider pointers, but
1097   // that isn't implemented for now.
1098   if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1099       getDataLayout().getTypeSizeInBits(IntPtrTy))
1100     return getCouldNotCompute();
1101 
1102   // If not, is this expression something we can't reduce any further?
1103   if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1104     // Perform some basic constant folding. If the operand of the ptr2int cast
1105     // is a null pointer, don't create a ptr2int SCEV expression (that will be
1106     // left as-is), but produce a zero constant.
1107     // NOTE: We could handle a more general case, but lack motivational cases.
1108     if (isa<ConstantPointerNull>(U->getValue()))
1109       return getZero(IntPtrTy);
1110 
1111     // Create an explicit cast node.
1112     // We can reuse the existing insert position since if we get here,
1113     // we won't have made any changes which would invalidate it.
1114     SCEV *S = new (SCEVAllocator)
1115         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1116     UniqueSCEVs.InsertNode(S, IP);
1117     registerUser(S, Op);
1118     return S;
1119   }
1120 
1121   assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1122                        "non-SCEVUnknown's.");
1123 
1124   // Otherwise, we've got some expression that is more complex than just a
1125   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1126   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1127   // only, and the expressions must otherwise be integer-typed.
1128   // So sink the cast down to the SCEVUnknown's.
1129 
1130   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1131   /// which computes a pointer-typed value, and rewrites the whole expression
1132   /// tree so that *all* the computations are done on integers, and the only
1133   /// pointer-typed operands in the expression are SCEVUnknown.
1134   class SCEVPtrToIntSinkingRewriter
1135       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1136     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1137 
1138   public:
1139     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1140 
1141     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1142       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1143       return Rewriter.visit(Scev);
1144     }
1145 
1146     const SCEV *visit(const SCEV *S) {
1147       Type *STy = S->getType();
1148       // If the expression is not pointer-typed, just keep it as-is.
1149       if (!STy->isPointerTy())
1150         return S;
1151       // Else, recursively sink the cast down into it.
1152       return Base::visit(S);
1153     }
1154 
1155     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1156       SmallVector<const SCEV *, 2> Operands;
1157       bool Changed = false;
1158       for (auto *Op : Expr->operands()) {
1159         Operands.push_back(visit(Op));
1160         Changed |= Op != Operands.back();
1161       }
1162       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1163     }
1164 
1165     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1166       SmallVector<const SCEV *, 2> Operands;
1167       bool Changed = false;
1168       for (auto *Op : Expr->operands()) {
1169         Operands.push_back(visit(Op));
1170         Changed |= Op != Operands.back();
1171       }
1172       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1173     }
1174 
1175     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1176       assert(Expr->getType()->isPointerTy() &&
1177              "Should only reach pointer-typed SCEVUnknown's.");
1178       return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1179     }
1180   };
1181 
1182   // And actually perform the cast sinking.
1183   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1184   assert(IntOp->getType()->isIntegerTy() &&
1185          "We must have succeeded in sinking the cast, "
1186          "and ending up with an integer-typed expression!");
1187   return IntOp;
1188 }
1189 
1190 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1191   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1192 
1193   const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1194   if (isa<SCEVCouldNotCompute>(IntOp))
1195     return IntOp;
1196 
1197   return getTruncateOrZeroExtend(IntOp, Ty);
1198 }
1199 
1200 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1201                                              unsigned Depth) {
1202   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1203          "This is not a truncating conversion!");
1204   assert(isSCEVable(Ty) &&
1205          "This is not a conversion to a SCEVable type!");
1206   assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1207   Ty = getEffectiveSCEVType(Ty);
1208 
1209   FoldingSetNodeID ID;
1210   ID.AddInteger(scTruncate);
1211   ID.AddPointer(Op);
1212   ID.AddPointer(Ty);
1213   void *IP = nullptr;
1214   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1215 
1216   // Fold if the operand is constant.
1217   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1218     return getConstant(
1219       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1220 
1221   // trunc(trunc(x)) --> trunc(x)
1222   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1223     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1224 
1225   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1226   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1227     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1228 
1229   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1230   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1231     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1232 
1233   if (Depth > MaxCastDepth) {
1234     SCEV *S =
1235         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1236     UniqueSCEVs.InsertNode(S, IP);
1237     registerUser(S, Op);
1238     return S;
1239   }
1240 
1241   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1242   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1243   // if after transforming we have at most one truncate, not counting truncates
1244   // that replace other casts.
1245   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1246     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1247     SmallVector<const SCEV *, 4> Operands;
1248     unsigned numTruncs = 0;
1249     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1250          ++i) {
1251       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1252       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1253           isa<SCEVTruncateExpr>(S))
1254         numTruncs++;
1255       Operands.push_back(S);
1256     }
1257     if (numTruncs < 2) {
1258       if (isa<SCEVAddExpr>(Op))
1259         return getAddExpr(Operands);
1260       else if (isa<SCEVMulExpr>(Op))
1261         return getMulExpr(Operands);
1262       else
1263         llvm_unreachable("Unexpected SCEV type for Op.");
1264     }
1265     // Although we checked in the beginning that ID is not in the cache, it is
1266     // possible that during recursion and different modification ID was inserted
1267     // into the cache. So if we find it, just return it.
1268     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1269       return S;
1270   }
1271 
1272   // If the input value is a chrec scev, truncate the chrec's operands.
1273   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1274     SmallVector<const SCEV *, 4> Operands;
1275     for (const SCEV *Op : AddRec->operands())
1276       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1277     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1278   }
1279 
1280   // Return zero if truncating to known zeros.
1281   uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1282   if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1283     return getZero(Ty);
1284 
1285   // The cast wasn't folded; create an explicit cast node. We can reuse
1286   // the existing insert position since if we get here, we won't have
1287   // made any changes which would invalidate it.
1288   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1289                                                  Op, Ty);
1290   UniqueSCEVs.InsertNode(S, IP);
1291   registerUser(S, Op);
1292   return S;
1293 }
1294 
1295 // Get the limit of a recurrence such that incrementing by Step cannot cause
1296 // signed overflow as long as the value of the recurrence within the
1297 // loop does not exceed this limit before incrementing.
1298 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1299                                                  ICmpInst::Predicate *Pred,
1300                                                  ScalarEvolution *SE) {
1301   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1302   if (SE->isKnownPositive(Step)) {
1303     *Pred = ICmpInst::ICMP_SLT;
1304     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1305                            SE->getSignedRangeMax(Step));
1306   }
1307   if (SE->isKnownNegative(Step)) {
1308     *Pred = ICmpInst::ICMP_SGT;
1309     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1310                            SE->getSignedRangeMin(Step));
1311   }
1312   return nullptr;
1313 }
1314 
1315 // Get the limit of a recurrence such that incrementing by Step cannot cause
1316 // unsigned overflow as long as the value of the recurrence within the loop does
1317 // not exceed this limit before incrementing.
1318 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1319                                                    ICmpInst::Predicate *Pred,
1320                                                    ScalarEvolution *SE) {
1321   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1322   *Pred = ICmpInst::ICMP_ULT;
1323 
1324   return SE->getConstant(APInt::getMinValue(BitWidth) -
1325                          SE->getUnsignedRangeMax(Step));
1326 }
1327 
1328 namespace {
1329 
1330 struct ExtendOpTraitsBase {
1331   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1332                                                           unsigned);
1333 };
1334 
1335 // Used to make code generic over signed and unsigned overflow.
1336 template <typename ExtendOp> struct ExtendOpTraits {
1337   // Members present:
1338   //
1339   // static const SCEV::NoWrapFlags WrapType;
1340   //
1341   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1342   //
1343   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1344   //                                           ICmpInst::Predicate *Pred,
1345   //                                           ScalarEvolution *SE);
1346 };
1347 
1348 template <>
1349 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1350   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1351 
1352   static const GetExtendExprTy GetExtendExpr;
1353 
1354   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1355                                              ICmpInst::Predicate *Pred,
1356                                              ScalarEvolution *SE) {
1357     return getSignedOverflowLimitForStep(Step, Pred, SE);
1358   }
1359 };
1360 
1361 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1362     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1363 
1364 template <>
1365 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1366   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1367 
1368   static const GetExtendExprTy GetExtendExpr;
1369 
1370   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1371                                              ICmpInst::Predicate *Pred,
1372                                              ScalarEvolution *SE) {
1373     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1374   }
1375 };
1376 
1377 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1378     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1379 
1380 } // end anonymous namespace
1381 
1382 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1383 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1384 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1385 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1386 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1387 // expression "Step + sext/zext(PreIncAR)" is congruent with
1388 // "sext/zext(PostIncAR)"
1389 template <typename ExtendOpTy>
1390 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1391                                         ScalarEvolution *SE, unsigned Depth) {
1392   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1393   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1394 
1395   const Loop *L = AR->getLoop();
1396   const SCEV *Start = AR->getStart();
1397   const SCEV *Step = AR->getStepRecurrence(*SE);
1398 
1399   // Check for a simple looking step prior to loop entry.
1400   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1401   if (!SA)
1402     return nullptr;
1403 
1404   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1405   // subtraction is expensive. For this purpose, perform a quick and dirty
1406   // difference, by checking for Step in the operand list.
1407   SmallVector<const SCEV *, 4> DiffOps;
1408   for (const SCEV *Op : SA->operands())
1409     if (Op != Step)
1410       DiffOps.push_back(Op);
1411 
1412   if (DiffOps.size() == SA->getNumOperands())
1413     return nullptr;
1414 
1415   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1416   // `Step`:
1417 
1418   // 1. NSW/NUW flags on the step increment.
1419   auto PreStartFlags =
1420     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1421   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1422   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1423       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1424 
1425   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1426   // "S+X does not sign/unsign-overflow".
1427   //
1428 
1429   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1430   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1431       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1432     return PreStart;
1433 
1434   // 2. Direct overflow check on the step operation's expression.
1435   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1436   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1437   const SCEV *OperandExtendedStart =
1438       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1439                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1440   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1441     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1442       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1443       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1444       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1445       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1446     }
1447     return PreStart;
1448   }
1449 
1450   // 3. Loop precondition.
1451   ICmpInst::Predicate Pred;
1452   const SCEV *OverflowLimit =
1453       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1454 
1455   if (OverflowLimit &&
1456       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1457     return PreStart;
1458 
1459   return nullptr;
1460 }
1461 
1462 // Get the normalized zero or sign extended expression for this AddRec's Start.
1463 template <typename ExtendOpTy>
1464 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1465                                         ScalarEvolution *SE,
1466                                         unsigned Depth) {
1467   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1468 
1469   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1470   if (!PreStart)
1471     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1472 
1473   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1474                                              Depth),
1475                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1476 }
1477 
1478 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1479 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1480 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1481 //
1482 // Formally:
1483 //
1484 //     {S,+,X} == {S-T,+,X} + T
1485 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1486 //
1487 // If ({S-T,+,X} + T) does not overflow  ... (1)
1488 //
1489 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1490 //
1491 // If {S-T,+,X} does not overflow  ... (2)
1492 //
1493 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1494 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1495 //
1496 // If (S-T)+T does not overflow  ... (3)
1497 //
1498 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1499 //      == {Ext(S),+,Ext(X)} == LHS
1500 //
1501 // Thus, if (1), (2) and (3) are true for some T, then
1502 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1503 //
1504 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1505 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1506 // to check for (1) and (2).
1507 //
1508 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1509 // is `Delta` (defined below).
1510 template <typename ExtendOpTy>
1511 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1512                                                 const SCEV *Step,
1513                                                 const Loop *L) {
1514   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1515 
1516   // We restrict `Start` to a constant to prevent SCEV from spending too much
1517   // time here.  It is correct (but more expensive) to continue with a
1518   // non-constant `Start` and do a general SCEV subtraction to compute
1519   // `PreStart` below.
1520   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1521   if (!StartC)
1522     return false;
1523 
1524   APInt StartAI = StartC->getAPInt();
1525 
1526   for (unsigned Delta : {-2, -1, 1, 2}) {
1527     const SCEV *PreStart = getConstant(StartAI - Delta);
1528 
1529     FoldingSetNodeID ID;
1530     ID.AddInteger(scAddRecExpr);
1531     ID.AddPointer(PreStart);
1532     ID.AddPointer(Step);
1533     ID.AddPointer(L);
1534     void *IP = nullptr;
1535     const auto *PreAR =
1536       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1537 
1538     // Give up if we don't already have the add recurrence we need because
1539     // actually constructing an add recurrence is relatively expensive.
1540     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1541       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1542       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1543       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1544           DeltaS, &Pred, this);
1545       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1546         return true;
1547     }
1548   }
1549 
1550   return false;
1551 }
1552 
1553 // Finds an integer D for an expression (C + x + y + ...) such that the top
1554 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1555 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1556 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1557 // the (C + x + y + ...) expression is \p WholeAddExpr.
1558 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1559                                             const SCEVConstant *ConstantTerm,
1560                                             const SCEVAddExpr *WholeAddExpr) {
1561   const APInt &C = ConstantTerm->getAPInt();
1562   const unsigned BitWidth = C.getBitWidth();
1563   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1564   uint32_t TZ = BitWidth;
1565   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1566     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1567   if (TZ) {
1568     // Set D to be as many least significant bits of C as possible while still
1569     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1570     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1571   }
1572   return APInt(BitWidth, 0);
1573 }
1574 
1575 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1576 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1577 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1578 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1579 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1580                                             const APInt &ConstantStart,
1581                                             const SCEV *Step) {
1582   const unsigned BitWidth = ConstantStart.getBitWidth();
1583   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1584   if (TZ)
1585     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1586                          : ConstantStart;
1587   return APInt(BitWidth, 0);
1588 }
1589 
1590 const SCEV *
1591 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1592   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1593          "This is not an extending conversion!");
1594   assert(isSCEVable(Ty) &&
1595          "This is not a conversion to a SCEVable type!");
1596   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1597   Ty = getEffectiveSCEVType(Ty);
1598 
1599   // Fold if the operand is constant.
1600   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1601     return getConstant(
1602       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1603 
1604   // zext(zext(x)) --> zext(x)
1605   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1606     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1607 
1608   // Before doing any expensive analysis, check to see if we've already
1609   // computed a SCEV for this Op and Ty.
1610   FoldingSetNodeID ID;
1611   ID.AddInteger(scZeroExtend);
1612   ID.AddPointer(Op);
1613   ID.AddPointer(Ty);
1614   void *IP = nullptr;
1615   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1616   if (Depth > MaxCastDepth) {
1617     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1618                                                      Op, Ty);
1619     UniqueSCEVs.InsertNode(S, IP);
1620     registerUser(S, Op);
1621     return S;
1622   }
1623 
1624   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1625   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1626     // It's possible the bits taken off by the truncate were all zero bits. If
1627     // so, we should be able to simplify this further.
1628     const SCEV *X = ST->getOperand();
1629     ConstantRange CR = getUnsignedRange(X);
1630     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1631     unsigned NewBits = getTypeSizeInBits(Ty);
1632     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1633             CR.zextOrTrunc(NewBits)))
1634       return getTruncateOrZeroExtend(X, Ty, Depth);
1635   }
1636 
1637   // If the input value is a chrec scev, and we can prove that the value
1638   // did not overflow the old, smaller, value, we can zero extend all of the
1639   // operands (often constants).  This allows analysis of something like
1640   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1641   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1642     if (AR->isAffine()) {
1643       const SCEV *Start = AR->getStart();
1644       const SCEV *Step = AR->getStepRecurrence(*this);
1645       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1646       const Loop *L = AR->getLoop();
1647 
1648       if (!AR->hasNoUnsignedWrap()) {
1649         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1650         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1651       }
1652 
1653       // If we have special knowledge that this addrec won't overflow,
1654       // we don't need to do any further analysis.
1655       if (AR->hasNoUnsignedWrap())
1656         return getAddRecExpr(
1657             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1658             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1659 
1660       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1661       // Note that this serves two purposes: It filters out loops that are
1662       // simply not analyzable, and it covers the case where this code is
1663       // being called from within backedge-taken count analysis, such that
1664       // attempting to ask for the backedge-taken count would likely result
1665       // in infinite recursion. In the later case, the analysis code will
1666       // cope with a conservative value, and it will take care to purge
1667       // that value once it has finished.
1668       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1669       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1670         // Manually compute the final value for AR, checking for overflow.
1671 
1672         // Check whether the backedge-taken count can be losslessly casted to
1673         // the addrec's type. The count is always unsigned.
1674         const SCEV *CastedMaxBECount =
1675             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1676         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1677             CastedMaxBECount, MaxBECount->getType(), Depth);
1678         if (MaxBECount == RecastedMaxBECount) {
1679           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1680           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1681           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1682                                         SCEV::FlagAnyWrap, Depth + 1);
1683           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1684                                                           SCEV::FlagAnyWrap,
1685                                                           Depth + 1),
1686                                                WideTy, Depth + 1);
1687           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1688           const SCEV *WideMaxBECount =
1689             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1690           const SCEV *OperandExtendedAdd =
1691             getAddExpr(WideStart,
1692                        getMulExpr(WideMaxBECount,
1693                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1694                                   SCEV::FlagAnyWrap, Depth + 1),
1695                        SCEV::FlagAnyWrap, Depth + 1);
1696           if (ZAdd == OperandExtendedAdd) {
1697             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1698             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1699             // Return the expression with the addrec on the outside.
1700             return getAddRecExpr(
1701                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1702                                                          Depth + 1),
1703                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1704                 AR->getNoWrapFlags());
1705           }
1706           // Similar to above, only this time treat the step value as signed.
1707           // This covers loops that count down.
1708           OperandExtendedAdd =
1709             getAddExpr(WideStart,
1710                        getMulExpr(WideMaxBECount,
1711                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1712                                   SCEV::FlagAnyWrap, Depth + 1),
1713                        SCEV::FlagAnyWrap, Depth + 1);
1714           if (ZAdd == OperandExtendedAdd) {
1715             // Cache knowledge of AR NW, which is propagated to this AddRec.
1716             // Negative step causes unsigned wrap, but it still can't self-wrap.
1717             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1718             // Return the expression with the addrec on the outside.
1719             return getAddRecExpr(
1720                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1721                                                          Depth + 1),
1722                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1723                 AR->getNoWrapFlags());
1724           }
1725         }
1726       }
1727 
1728       // Normally, in the cases we can prove no-overflow via a
1729       // backedge guarding condition, we can also compute a backedge
1730       // taken count for the loop.  The exceptions are assumptions and
1731       // guards present in the loop -- SCEV is not great at exploiting
1732       // these to compute max backedge taken counts, but can still use
1733       // these to prove lack of overflow.  Use this fact to avoid
1734       // doing extra work that may not pay off.
1735       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1736           !AC.assumptions().empty()) {
1737 
1738         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1739         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1740         if (AR->hasNoUnsignedWrap()) {
1741           // Same as nuw case above - duplicated here to avoid a compile time
1742           // issue.  It's not clear that the order of checks does matter, but
1743           // it's one of two issue possible causes for a change which was
1744           // reverted.  Be conservative for the moment.
1745           return getAddRecExpr(
1746                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1747                                                          Depth + 1),
1748                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1749                 AR->getNoWrapFlags());
1750         }
1751 
1752         // For a negative step, we can extend the operands iff doing so only
1753         // traverses values in the range zext([0,UINT_MAX]).
1754         if (isKnownNegative(Step)) {
1755           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1756                                       getSignedRangeMin(Step));
1757           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1758               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1759             // Cache knowledge of AR NW, which is propagated to this
1760             // AddRec.  Negative step causes unsigned wrap, but it
1761             // still can't self-wrap.
1762             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1763             // Return the expression with the addrec on the outside.
1764             return getAddRecExpr(
1765                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1766                                                          Depth + 1),
1767                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1768                 AR->getNoWrapFlags());
1769           }
1770         }
1771       }
1772 
1773       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1774       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1775       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1776       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1777         const APInt &C = SC->getAPInt();
1778         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1779         if (D != 0) {
1780           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1781           const SCEV *SResidual =
1782               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1783           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1784           return getAddExpr(SZExtD, SZExtR,
1785                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1786                             Depth + 1);
1787         }
1788       }
1789 
1790       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1791         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1792         return getAddRecExpr(
1793             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1794             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1795       }
1796     }
1797 
1798   // zext(A % B) --> zext(A) % zext(B)
1799   {
1800     const SCEV *LHS;
1801     const SCEV *RHS;
1802     if (matchURem(Op, LHS, RHS))
1803       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1804                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1805   }
1806 
1807   // zext(A / B) --> zext(A) / zext(B).
1808   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1809     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1810                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1811 
1812   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1813     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1814     if (SA->hasNoUnsignedWrap()) {
1815       // If the addition does not unsign overflow then we can, by definition,
1816       // commute the zero extension with the addition operation.
1817       SmallVector<const SCEV *, 4> Ops;
1818       for (const auto *Op : SA->operands())
1819         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1820       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1821     }
1822 
1823     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1824     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1825     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1826     //
1827     // Often address arithmetics contain expressions like
1828     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1829     // This transformation is useful while proving that such expressions are
1830     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1831     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1832       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1833       if (D != 0) {
1834         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1835         const SCEV *SResidual =
1836             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1837         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1838         return getAddExpr(SZExtD, SZExtR,
1839                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1840                           Depth + 1);
1841       }
1842     }
1843   }
1844 
1845   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1846     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1847     if (SM->hasNoUnsignedWrap()) {
1848       // If the multiply does not unsign overflow then we can, by definition,
1849       // commute the zero extension with the multiply operation.
1850       SmallVector<const SCEV *, 4> Ops;
1851       for (const auto *Op : SM->operands())
1852         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1853       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1854     }
1855 
1856     // zext(2^K * (trunc X to iN)) to iM ->
1857     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1858     //
1859     // Proof:
1860     //
1861     //     zext(2^K * (trunc X to iN)) to iM
1862     //   = zext((trunc X to iN) << K) to iM
1863     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1864     //     (because shl removes the top K bits)
1865     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1866     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1867     //
1868     if (SM->getNumOperands() == 2)
1869       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1870         if (MulLHS->getAPInt().isPowerOf2())
1871           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1872             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1873                                MulLHS->getAPInt().logBase2();
1874             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1875             return getMulExpr(
1876                 getZeroExtendExpr(MulLHS, Ty),
1877                 getZeroExtendExpr(
1878                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1879                 SCEV::FlagNUW, Depth + 1);
1880           }
1881   }
1882 
1883   // The cast wasn't folded; create an explicit cast node.
1884   // Recompute the insert position, as it may have been invalidated.
1885   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1886   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1887                                                    Op, Ty);
1888   UniqueSCEVs.InsertNode(S, IP);
1889   registerUser(S, Op);
1890   return S;
1891 }
1892 
1893 const SCEV *
1894 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1895   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1896          "This is not an extending conversion!");
1897   assert(isSCEVable(Ty) &&
1898          "This is not a conversion to a SCEVable type!");
1899   assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1900   Ty = getEffectiveSCEVType(Ty);
1901 
1902   // Fold if the operand is constant.
1903   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1904     return getConstant(
1905       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1906 
1907   // sext(sext(x)) --> sext(x)
1908   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1909     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1910 
1911   // sext(zext(x)) --> zext(x)
1912   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1913     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1914 
1915   // Before doing any expensive analysis, check to see if we've already
1916   // computed a SCEV for this Op and Ty.
1917   FoldingSetNodeID ID;
1918   ID.AddInteger(scSignExtend);
1919   ID.AddPointer(Op);
1920   ID.AddPointer(Ty);
1921   void *IP = nullptr;
1922   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1923   // Limit recursion depth.
1924   if (Depth > MaxCastDepth) {
1925     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1926                                                      Op, Ty);
1927     UniqueSCEVs.InsertNode(S, IP);
1928     registerUser(S, Op);
1929     return S;
1930   }
1931 
1932   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1933   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1934     // It's possible the bits taken off by the truncate were all sign bits. If
1935     // so, we should be able to simplify this further.
1936     const SCEV *X = ST->getOperand();
1937     ConstantRange CR = getSignedRange(X);
1938     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1939     unsigned NewBits = getTypeSizeInBits(Ty);
1940     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1941             CR.sextOrTrunc(NewBits)))
1942       return getTruncateOrSignExtend(X, Ty, Depth);
1943   }
1944 
1945   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1946     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1947     if (SA->hasNoSignedWrap()) {
1948       // If the addition does not sign overflow then we can, by definition,
1949       // commute the sign extension with the addition operation.
1950       SmallVector<const SCEV *, 4> Ops;
1951       for (const auto *Op : SA->operands())
1952         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1953       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1954     }
1955 
1956     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1957     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1958     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1959     //
1960     // For instance, this will bring two seemingly different expressions:
1961     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1962     //         sext(6 + 20 * %x + 24 * %y)
1963     // to the same form:
1964     //     2 + sext(4 + 20 * %x + 24 * %y)
1965     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1966       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1967       if (D != 0) {
1968         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1969         const SCEV *SResidual =
1970             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1971         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1972         return getAddExpr(SSExtD, SSExtR,
1973                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1974                           Depth + 1);
1975       }
1976     }
1977   }
1978   // If the input value is a chrec scev, and we can prove that the value
1979   // did not overflow the old, smaller, value, we can sign extend all of the
1980   // operands (often constants).  This allows analysis of something like
1981   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1982   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1983     if (AR->isAffine()) {
1984       const SCEV *Start = AR->getStart();
1985       const SCEV *Step = AR->getStepRecurrence(*this);
1986       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1987       const Loop *L = AR->getLoop();
1988 
1989       if (!AR->hasNoSignedWrap()) {
1990         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1991         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1992       }
1993 
1994       // If we have special knowledge that this addrec won't overflow,
1995       // we don't need to do any further analysis.
1996       if (AR->hasNoSignedWrap())
1997         return getAddRecExpr(
1998             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1999             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2000 
2001       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2002       // Note that this serves two purposes: It filters out loops that are
2003       // simply not analyzable, and it covers the case where this code is
2004       // being called from within backedge-taken count analysis, such that
2005       // attempting to ask for the backedge-taken count would likely result
2006       // in infinite recursion. In the later case, the analysis code will
2007       // cope with a conservative value, and it will take care to purge
2008       // that value once it has finished.
2009       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2010       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2011         // Manually compute the final value for AR, checking for
2012         // overflow.
2013 
2014         // Check whether the backedge-taken count can be losslessly casted to
2015         // the addrec's type. The count is always unsigned.
2016         const SCEV *CastedMaxBECount =
2017             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2018         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2019             CastedMaxBECount, MaxBECount->getType(), Depth);
2020         if (MaxBECount == RecastedMaxBECount) {
2021           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2022           // Check whether Start+Step*MaxBECount has no signed overflow.
2023           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2024                                         SCEV::FlagAnyWrap, Depth + 1);
2025           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2026                                                           SCEV::FlagAnyWrap,
2027                                                           Depth + 1),
2028                                                WideTy, Depth + 1);
2029           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2030           const SCEV *WideMaxBECount =
2031             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2032           const SCEV *OperandExtendedAdd =
2033             getAddExpr(WideStart,
2034                        getMulExpr(WideMaxBECount,
2035                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2036                                   SCEV::FlagAnyWrap, Depth + 1),
2037                        SCEV::FlagAnyWrap, Depth + 1);
2038           if (SAdd == OperandExtendedAdd) {
2039             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2040             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2041             // Return the expression with the addrec on the outside.
2042             return getAddRecExpr(
2043                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2044                                                          Depth + 1),
2045                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2046                 AR->getNoWrapFlags());
2047           }
2048           // Similar to above, only this time treat the step value as unsigned.
2049           // This covers loops that count up with an unsigned step.
2050           OperandExtendedAdd =
2051             getAddExpr(WideStart,
2052                        getMulExpr(WideMaxBECount,
2053                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2054                                   SCEV::FlagAnyWrap, Depth + 1),
2055                        SCEV::FlagAnyWrap, Depth + 1);
2056           if (SAdd == OperandExtendedAdd) {
2057             // If AR wraps around then
2058             //
2059             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2060             // => SAdd != OperandExtendedAdd
2061             //
2062             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2063             // (SAdd == OperandExtendedAdd => AR is NW)
2064 
2065             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2066 
2067             // Return the expression with the addrec on the outside.
2068             return getAddRecExpr(
2069                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2070                                                          Depth + 1),
2071                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2072                 AR->getNoWrapFlags());
2073           }
2074         }
2075       }
2076 
2077       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2078       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2079       if (AR->hasNoSignedWrap()) {
2080         // Same as nsw case above - duplicated here to avoid a compile time
2081         // issue.  It's not clear that the order of checks does matter, but
2082         // it's one of two issue possible causes for a change which was
2083         // reverted.  Be conservative for the moment.
2084         return getAddRecExpr(
2085             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2086             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2087       }
2088 
2089       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2090       // if D + (C - D + Step * n) could be proven to not signed wrap
2091       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2092       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2093         const APInt &C = SC->getAPInt();
2094         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2095         if (D != 0) {
2096           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2097           const SCEV *SResidual =
2098               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2099           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2100           return getAddExpr(SSExtD, SSExtR,
2101                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2102                             Depth + 1);
2103         }
2104       }
2105 
2106       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2107         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2108         return getAddRecExpr(
2109             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2110             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2111       }
2112     }
2113 
2114   // If the input value is provably positive and we could not simplify
2115   // away the sext build a zext instead.
2116   if (isKnownNonNegative(Op))
2117     return getZeroExtendExpr(Op, Ty, Depth + 1);
2118 
2119   // The cast wasn't folded; create an explicit cast node.
2120   // Recompute the insert position, as it may have been invalidated.
2121   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2122   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2123                                                    Op, Ty);
2124   UniqueSCEVs.InsertNode(S, IP);
2125   registerUser(S, { Op });
2126   return S;
2127 }
2128 
2129 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2130                                          Type *Ty) {
2131   switch (Kind) {
2132   case scTruncate:
2133     return getTruncateExpr(Op, Ty);
2134   case scZeroExtend:
2135     return getZeroExtendExpr(Op, Ty);
2136   case scSignExtend:
2137     return getSignExtendExpr(Op, Ty);
2138   case scPtrToInt:
2139     return getPtrToIntExpr(Op, Ty);
2140   default:
2141     llvm_unreachable("Not a SCEV cast expression!");
2142   }
2143 }
2144 
2145 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2146 /// unspecified bits out to the given type.
2147 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2148                                               Type *Ty) {
2149   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2150          "This is not an extending conversion!");
2151   assert(isSCEVable(Ty) &&
2152          "This is not a conversion to a SCEVable type!");
2153   Ty = getEffectiveSCEVType(Ty);
2154 
2155   // Sign-extend negative constants.
2156   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2157     if (SC->getAPInt().isNegative())
2158       return getSignExtendExpr(Op, Ty);
2159 
2160   // Peel off a truncate cast.
2161   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2162     const SCEV *NewOp = T->getOperand();
2163     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2164       return getAnyExtendExpr(NewOp, Ty);
2165     return getTruncateOrNoop(NewOp, Ty);
2166   }
2167 
2168   // Next try a zext cast. If the cast is folded, use it.
2169   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2170   if (!isa<SCEVZeroExtendExpr>(ZExt))
2171     return ZExt;
2172 
2173   // Next try a sext cast. If the cast is folded, use it.
2174   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2175   if (!isa<SCEVSignExtendExpr>(SExt))
2176     return SExt;
2177 
2178   // Force the cast to be folded into the operands of an addrec.
2179   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2180     SmallVector<const SCEV *, 4> Ops;
2181     for (const SCEV *Op : AR->operands())
2182       Ops.push_back(getAnyExtendExpr(Op, Ty));
2183     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2184   }
2185 
2186   // If the expression is obviously signed, use the sext cast value.
2187   if (isa<SCEVSMaxExpr>(Op))
2188     return SExt;
2189 
2190   // Absent any other information, use the zext cast value.
2191   return ZExt;
2192 }
2193 
2194 /// Process the given Ops list, which is a list of operands to be added under
2195 /// the given scale, update the given map. This is a helper function for
2196 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2197 /// that would form an add expression like this:
2198 ///
2199 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2200 ///
2201 /// where A and B are constants, update the map with these values:
2202 ///
2203 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2204 ///
2205 /// and add 13 + A*B*29 to AccumulatedConstant.
2206 /// This will allow getAddRecExpr to produce this:
2207 ///
2208 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2209 ///
2210 /// This form often exposes folding opportunities that are hidden in
2211 /// the original operand list.
2212 ///
2213 /// Return true iff it appears that any interesting folding opportunities
2214 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2215 /// the common case where no interesting opportunities are present, and
2216 /// is also used as a check to avoid infinite recursion.
2217 static bool
2218 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2219                              SmallVectorImpl<const SCEV *> &NewOps,
2220                              APInt &AccumulatedConstant,
2221                              const SCEV *const *Ops, size_t NumOperands,
2222                              const APInt &Scale,
2223                              ScalarEvolution &SE) {
2224   bool Interesting = false;
2225 
2226   // Iterate over the add operands. They are sorted, with constants first.
2227   unsigned i = 0;
2228   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2229     ++i;
2230     // Pull a buried constant out to the outside.
2231     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2232       Interesting = true;
2233     AccumulatedConstant += Scale * C->getAPInt();
2234   }
2235 
2236   // Next comes everything else. We're especially interested in multiplies
2237   // here, but they're in the middle, so just visit the rest with one loop.
2238   for (; i != NumOperands; ++i) {
2239     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2240     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2241       APInt NewScale =
2242           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2243       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2244         // A multiplication of a constant with another add; recurse.
2245         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2246         Interesting |=
2247           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2248                                        Add->op_begin(), Add->getNumOperands(),
2249                                        NewScale, SE);
2250       } else {
2251         // A multiplication of a constant with some other value. Update
2252         // the map.
2253         SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2254         const SCEV *Key = SE.getMulExpr(MulOps);
2255         auto Pair = M.insert({Key, NewScale});
2256         if (Pair.second) {
2257           NewOps.push_back(Pair.first->first);
2258         } else {
2259           Pair.first->second += NewScale;
2260           // The map already had an entry for this value, which may indicate
2261           // a folding opportunity.
2262           Interesting = true;
2263         }
2264       }
2265     } else {
2266       // An ordinary operand. Update the map.
2267       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2268           M.insert({Ops[i], Scale});
2269       if (Pair.second) {
2270         NewOps.push_back(Pair.first->first);
2271       } else {
2272         Pair.first->second += Scale;
2273         // The map already had an entry for this value, which may indicate
2274         // a folding opportunity.
2275         Interesting = true;
2276       }
2277     }
2278   }
2279 
2280   return Interesting;
2281 }
2282 
2283 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2284                                       const SCEV *LHS, const SCEV *RHS) {
2285   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2286                                             SCEV::NoWrapFlags, unsigned);
2287   switch (BinOp) {
2288   default:
2289     llvm_unreachable("Unsupported binary op");
2290   case Instruction::Add:
2291     Operation = &ScalarEvolution::getAddExpr;
2292     break;
2293   case Instruction::Sub:
2294     Operation = &ScalarEvolution::getMinusSCEV;
2295     break;
2296   case Instruction::Mul:
2297     Operation = &ScalarEvolution::getMulExpr;
2298     break;
2299   }
2300 
2301   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2302       Signed ? &ScalarEvolution::getSignExtendExpr
2303              : &ScalarEvolution::getZeroExtendExpr;
2304 
2305   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2306   auto *NarrowTy = cast<IntegerType>(LHS->getType());
2307   auto *WideTy =
2308       IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2309 
2310   const SCEV *A = (this->*Extension)(
2311       (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2312   const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0),
2313                                      (this->*Extension)(RHS, WideTy, 0),
2314                                      SCEV::FlagAnyWrap, 0);
2315   return A == B;
2316 }
2317 
2318 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/>
2319 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2320     const OverflowingBinaryOperator *OBO) {
2321   SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2322 
2323   if (OBO->hasNoUnsignedWrap())
2324     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2325   if (OBO->hasNoSignedWrap())
2326     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2327 
2328   bool Deduced = false;
2329 
2330   if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2331     return {Flags, Deduced};
2332 
2333   if (OBO->getOpcode() != Instruction::Add &&
2334       OBO->getOpcode() != Instruction::Sub &&
2335       OBO->getOpcode() != Instruction::Mul)
2336     return {Flags, Deduced};
2337 
2338   const SCEV *LHS = getSCEV(OBO->getOperand(0));
2339   const SCEV *RHS = getSCEV(OBO->getOperand(1));
2340 
2341   if (!OBO->hasNoUnsignedWrap() &&
2342       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2343                       /* Signed */ false, LHS, RHS)) {
2344     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2345     Deduced = true;
2346   }
2347 
2348   if (!OBO->hasNoSignedWrap() &&
2349       willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2350                       /* Signed */ true, LHS, RHS)) {
2351     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2352     Deduced = true;
2353   }
2354 
2355   return {Flags, Deduced};
2356 }
2357 
2358 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2359 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2360 // can't-overflow flags for the operation if possible.
2361 static SCEV::NoWrapFlags
2362 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2363                       const ArrayRef<const SCEV *> Ops,
2364                       SCEV::NoWrapFlags Flags) {
2365   using namespace std::placeholders;
2366 
2367   using OBO = OverflowingBinaryOperator;
2368 
2369   bool CanAnalyze =
2370       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2371   (void)CanAnalyze;
2372   assert(CanAnalyze && "don't call from other places!");
2373 
2374   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2375   SCEV::NoWrapFlags SignOrUnsignWrap =
2376       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2377 
2378   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2379   auto IsKnownNonNegative = [&](const SCEV *S) {
2380     return SE->isKnownNonNegative(S);
2381   };
2382 
2383   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2384     Flags =
2385         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2386 
2387   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2388 
2389   if (SignOrUnsignWrap != SignOrUnsignMask &&
2390       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2391       isa<SCEVConstant>(Ops[0])) {
2392 
2393     auto Opcode = [&] {
2394       switch (Type) {
2395       case scAddExpr:
2396         return Instruction::Add;
2397       case scMulExpr:
2398         return Instruction::Mul;
2399       default:
2400         llvm_unreachable("Unexpected SCEV op.");
2401       }
2402     }();
2403 
2404     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2405 
2406     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2407     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2408       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2409           Opcode, C, OBO::NoSignedWrap);
2410       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2411         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2412     }
2413 
2414     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2415     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2416       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2417           Opcode, C, OBO::NoUnsignedWrap);
2418       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2419         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2420     }
2421   }
2422 
2423   // <0,+,nonnegative><nw> is also nuw
2424   // TODO: Add corresponding nsw case
2425   if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2426       !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2427       Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2428     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2429 
2430   // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2431   if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2432       Ops.size() == 2) {
2433     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2434       if (UDiv->getOperand(1) == Ops[1])
2435         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2436     if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2437       if (UDiv->getOperand(1) == Ops[0])
2438         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2439   }
2440 
2441   return Flags;
2442 }
2443 
2444 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2445   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2446 }
2447 
2448 /// Get a canonical add expression, or something simpler if possible.
2449 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2450                                         SCEV::NoWrapFlags OrigFlags,
2451                                         unsigned Depth) {
2452   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2453          "only nuw or nsw allowed");
2454   assert(!Ops.empty() && "Cannot get empty add!");
2455   if (Ops.size() == 1) return Ops[0];
2456 #ifndef NDEBUG
2457   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2458   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2459     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2460            "SCEVAddExpr operand types don't match!");
2461   unsigned NumPtrs = count_if(
2462       Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2463   assert(NumPtrs <= 1 && "add has at most one pointer operand");
2464 #endif
2465 
2466   // Sort by complexity, this groups all similar expression types together.
2467   GroupByComplexity(Ops, &LI, DT);
2468 
2469   // If there are any constants, fold them together.
2470   unsigned Idx = 0;
2471   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2472     ++Idx;
2473     assert(Idx < Ops.size());
2474     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2475       // We found two constants, fold them together!
2476       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2477       if (Ops.size() == 2) return Ops[0];
2478       Ops.erase(Ops.begin()+1);  // Erase the folded element
2479       LHSC = cast<SCEVConstant>(Ops[0]);
2480     }
2481 
2482     // If we are left with a constant zero being added, strip it off.
2483     if (LHSC->getValue()->isZero()) {
2484       Ops.erase(Ops.begin());
2485       --Idx;
2486     }
2487 
2488     if (Ops.size() == 1) return Ops[0];
2489   }
2490 
2491   // Delay expensive flag strengthening until necessary.
2492   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2493     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2494   };
2495 
2496   // Limit recursion calls depth.
2497   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2498     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2499 
2500   if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2501     // Don't strengthen flags if we have no new information.
2502     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2503     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2504       Add->setNoWrapFlags(ComputeFlags(Ops));
2505     return S;
2506   }
2507 
2508   // Okay, check to see if the same value occurs in the operand list more than
2509   // once.  If so, merge them together into an multiply expression.  Since we
2510   // sorted the list, these values are required to be adjacent.
2511   Type *Ty = Ops[0]->getType();
2512   bool FoundMatch = false;
2513   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2514     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2515       // Scan ahead to count how many equal operands there are.
2516       unsigned Count = 2;
2517       while (i+Count != e && Ops[i+Count] == Ops[i])
2518         ++Count;
2519       // Merge the values into a multiply.
2520       const SCEV *Scale = getConstant(Ty, Count);
2521       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2522       if (Ops.size() == Count)
2523         return Mul;
2524       Ops[i] = Mul;
2525       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2526       --i; e -= Count - 1;
2527       FoundMatch = true;
2528     }
2529   if (FoundMatch)
2530     return getAddExpr(Ops, OrigFlags, Depth + 1);
2531 
2532   // Check for truncates. If all the operands are truncated from the same
2533   // type, see if factoring out the truncate would permit the result to be
2534   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2535   // if the contents of the resulting outer trunc fold to something simple.
2536   auto FindTruncSrcType = [&]() -> Type * {
2537     // We're ultimately looking to fold an addrec of truncs and muls of only
2538     // constants and truncs, so if we find any other types of SCEV
2539     // as operands of the addrec then we bail and return nullptr here.
2540     // Otherwise, we return the type of the operand of a trunc that we find.
2541     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2542       return T->getOperand()->getType();
2543     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2544       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2545       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2546         return T->getOperand()->getType();
2547     }
2548     return nullptr;
2549   };
2550   if (auto *SrcType = FindTruncSrcType()) {
2551     SmallVector<const SCEV *, 8> LargeOps;
2552     bool Ok = true;
2553     // Check all the operands to see if they can be represented in the
2554     // source type of the truncate.
2555     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2556       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2557         if (T->getOperand()->getType() != SrcType) {
2558           Ok = false;
2559           break;
2560         }
2561         LargeOps.push_back(T->getOperand());
2562       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2563         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2564       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2565         SmallVector<const SCEV *, 8> LargeMulOps;
2566         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2567           if (const SCEVTruncateExpr *T =
2568                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2569             if (T->getOperand()->getType() != SrcType) {
2570               Ok = false;
2571               break;
2572             }
2573             LargeMulOps.push_back(T->getOperand());
2574           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2575             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2576           } else {
2577             Ok = false;
2578             break;
2579           }
2580         }
2581         if (Ok)
2582           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2583       } else {
2584         Ok = false;
2585         break;
2586       }
2587     }
2588     if (Ok) {
2589       // Evaluate the expression in the larger type.
2590       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2591       // If it folds to something simple, use it. Otherwise, don't.
2592       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2593         return getTruncateExpr(Fold, Ty);
2594     }
2595   }
2596 
2597   if (Ops.size() == 2) {
2598     // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2599     // C2 can be folded in a way that allows retaining wrapping flags of (X +
2600     // C1).
2601     const SCEV *A = Ops[0];
2602     const SCEV *B = Ops[1];
2603     auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2604     auto *C = dyn_cast<SCEVConstant>(A);
2605     if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2606       auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2607       auto C2 = C->getAPInt();
2608       SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2609 
2610       APInt ConstAdd = C1 + C2;
2611       auto AddFlags = AddExpr->getNoWrapFlags();
2612       // Adding a smaller constant is NUW if the original AddExpr was NUW.
2613       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2614           ConstAdd.ule(C1)) {
2615         PreservedFlags =
2616             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2617       }
2618 
2619       // Adding a constant with the same sign and small magnitude is NSW, if the
2620       // original AddExpr was NSW.
2621       if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2622           C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2623           ConstAdd.abs().ule(C1.abs())) {
2624         PreservedFlags =
2625             ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2626       }
2627 
2628       if (PreservedFlags != SCEV::FlagAnyWrap) {
2629         SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2630         NewOps[0] = getConstant(ConstAdd);
2631         return getAddExpr(NewOps, PreservedFlags);
2632       }
2633     }
2634   }
2635 
2636   // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2637   if (Ops.size() == 2) {
2638     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2639     if (Mul && Mul->getNumOperands() == 2 &&
2640         Mul->getOperand(0)->isAllOnesValue()) {
2641       const SCEV *X;
2642       const SCEV *Y;
2643       if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2644         return getMulExpr(Y, getUDivExpr(X, Y));
2645       }
2646     }
2647   }
2648 
2649   // Skip past any other cast SCEVs.
2650   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2651     ++Idx;
2652 
2653   // If there are add operands they would be next.
2654   if (Idx < Ops.size()) {
2655     bool DeletedAdd = false;
2656     // If the original flags and all inlined SCEVAddExprs are NUW, use the
2657     // common NUW flag for expression after inlining. Other flags cannot be
2658     // preserved, because they may depend on the original order of operations.
2659     SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2660     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2661       if (Ops.size() > AddOpsInlineThreshold ||
2662           Add->getNumOperands() > AddOpsInlineThreshold)
2663         break;
2664       // If we have an add, expand the add operands onto the end of the operands
2665       // list.
2666       Ops.erase(Ops.begin()+Idx);
2667       Ops.append(Add->op_begin(), Add->op_end());
2668       DeletedAdd = true;
2669       CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2670     }
2671 
2672     // If we deleted at least one add, we added operands to the end of the list,
2673     // and they are not necessarily sorted.  Recurse to resort and resimplify
2674     // any operands we just acquired.
2675     if (DeletedAdd)
2676       return getAddExpr(Ops, CommonFlags, Depth + 1);
2677   }
2678 
2679   // Skip over the add expression until we get to a multiply.
2680   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2681     ++Idx;
2682 
2683   // Check to see if there are any folding opportunities present with
2684   // operands multiplied by constant values.
2685   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2686     uint64_t BitWidth = getTypeSizeInBits(Ty);
2687     DenseMap<const SCEV *, APInt> M;
2688     SmallVector<const SCEV *, 8> NewOps;
2689     APInt AccumulatedConstant(BitWidth, 0);
2690     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2691                                      Ops.data(), Ops.size(),
2692                                      APInt(BitWidth, 1), *this)) {
2693       struct APIntCompare {
2694         bool operator()(const APInt &LHS, const APInt &RHS) const {
2695           return LHS.ult(RHS);
2696         }
2697       };
2698 
2699       // Some interesting folding opportunity is present, so its worthwhile to
2700       // re-generate the operands list. Group the operands by constant scale,
2701       // to avoid multiplying by the same constant scale multiple times.
2702       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2703       for (const SCEV *NewOp : NewOps)
2704         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2705       // Re-generate the operands list.
2706       Ops.clear();
2707       if (AccumulatedConstant != 0)
2708         Ops.push_back(getConstant(AccumulatedConstant));
2709       for (auto &MulOp : MulOpLists) {
2710         if (MulOp.first == 1) {
2711           Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2712         } else if (MulOp.first != 0) {
2713           Ops.push_back(getMulExpr(
2714               getConstant(MulOp.first),
2715               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2716               SCEV::FlagAnyWrap, Depth + 1));
2717         }
2718       }
2719       if (Ops.empty())
2720         return getZero(Ty);
2721       if (Ops.size() == 1)
2722         return Ops[0];
2723       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2724     }
2725   }
2726 
2727   // If we are adding something to a multiply expression, make sure the
2728   // something is not already an operand of the multiply.  If so, merge it into
2729   // the multiply.
2730   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2731     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2732     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2733       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2734       if (isa<SCEVConstant>(MulOpSCEV))
2735         continue;
2736       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2737         if (MulOpSCEV == Ops[AddOp]) {
2738           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2739           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2740           if (Mul->getNumOperands() != 2) {
2741             // If the multiply has more than two operands, we must get the
2742             // Y*Z term.
2743             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2744                                                 Mul->op_begin()+MulOp);
2745             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2746             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2747           }
2748           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2749           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2750           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2751                                             SCEV::FlagAnyWrap, Depth + 1);
2752           if (Ops.size() == 2) return OuterMul;
2753           if (AddOp < Idx) {
2754             Ops.erase(Ops.begin()+AddOp);
2755             Ops.erase(Ops.begin()+Idx-1);
2756           } else {
2757             Ops.erase(Ops.begin()+Idx);
2758             Ops.erase(Ops.begin()+AddOp-1);
2759           }
2760           Ops.push_back(OuterMul);
2761           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2762         }
2763 
2764       // Check this multiply against other multiplies being added together.
2765       for (unsigned OtherMulIdx = Idx+1;
2766            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2767            ++OtherMulIdx) {
2768         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2769         // If MulOp occurs in OtherMul, we can fold the two multiplies
2770         // together.
2771         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2772              OMulOp != e; ++OMulOp)
2773           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2774             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2775             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2776             if (Mul->getNumOperands() != 2) {
2777               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2778                                                   Mul->op_begin()+MulOp);
2779               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2780               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2781             }
2782             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2783             if (OtherMul->getNumOperands() != 2) {
2784               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2785                                                   OtherMul->op_begin()+OMulOp);
2786               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2787               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2788             }
2789             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2790             const SCEV *InnerMulSum =
2791                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2792             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2793                                               SCEV::FlagAnyWrap, Depth + 1);
2794             if (Ops.size() == 2) return OuterMul;
2795             Ops.erase(Ops.begin()+Idx);
2796             Ops.erase(Ops.begin()+OtherMulIdx-1);
2797             Ops.push_back(OuterMul);
2798             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2799           }
2800       }
2801     }
2802   }
2803 
2804   // If there are any add recurrences in the operands list, see if any other
2805   // added values are loop invariant.  If so, we can fold them into the
2806   // recurrence.
2807   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2808     ++Idx;
2809 
2810   // Scan over all recurrences, trying to fold loop invariants into them.
2811   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2812     // Scan all of the other operands to this add and add them to the vector if
2813     // they are loop invariant w.r.t. the recurrence.
2814     SmallVector<const SCEV *, 8> LIOps;
2815     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2816     const Loop *AddRecLoop = AddRec->getLoop();
2817     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2818       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2819         LIOps.push_back(Ops[i]);
2820         Ops.erase(Ops.begin()+i);
2821         --i; --e;
2822       }
2823 
2824     // If we found some loop invariants, fold them into the recurrence.
2825     if (!LIOps.empty()) {
2826       // Compute nowrap flags for the addition of the loop-invariant ops and
2827       // the addrec. Temporarily push it as an operand for that purpose. These
2828       // flags are valid in the scope of the addrec only.
2829       LIOps.push_back(AddRec);
2830       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2831       LIOps.pop_back();
2832 
2833       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2834       LIOps.push_back(AddRec->getStart());
2835 
2836       SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2837 
2838       // It is not in general safe to propagate flags valid on an add within
2839       // the addrec scope to one outside it.  We must prove that the inner
2840       // scope is guaranteed to execute if the outer one does to be able to
2841       // safely propagate.  We know the program is undefined if poison is
2842       // produced on the inner scoped addrec.  We also know that *for this use*
2843       // the outer scoped add can't overflow (because of the flags we just
2844       // computed for the inner scoped add) without the program being undefined.
2845       // Proving that entry to the outer scope neccesitates entry to the inner
2846       // scope, thus proves the program undefined if the flags would be violated
2847       // in the outer scope.
2848       SCEV::NoWrapFlags AddFlags = Flags;
2849       if (AddFlags != SCEV::FlagAnyWrap) {
2850         auto *DefI = getDefiningScopeBound(LIOps);
2851         auto *ReachI = &*AddRecLoop->getHeader()->begin();
2852         if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2853           AddFlags = SCEV::FlagAnyWrap;
2854       }
2855       AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2856 
2857       // Build the new addrec. Propagate the NUW and NSW flags if both the
2858       // outer add and the inner addrec are guaranteed to have no overflow.
2859       // Always propagate NW.
2860       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2861       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2862 
2863       // If all of the other operands were loop invariant, we are done.
2864       if (Ops.size() == 1) return NewRec;
2865 
2866       // Otherwise, add the folded AddRec by the non-invariant parts.
2867       for (unsigned i = 0;; ++i)
2868         if (Ops[i] == AddRec) {
2869           Ops[i] = NewRec;
2870           break;
2871         }
2872       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2873     }
2874 
2875     // Okay, if there weren't any loop invariants to be folded, check to see if
2876     // there are multiple AddRec's with the same loop induction variable being
2877     // added together.  If so, we can fold them.
2878     for (unsigned OtherIdx = Idx+1;
2879          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2880          ++OtherIdx) {
2881       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2882       // so that the 1st found AddRecExpr is dominated by all others.
2883       assert(DT.dominates(
2884            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2885            AddRec->getLoop()->getHeader()) &&
2886         "AddRecExprs are not sorted in reverse dominance order?");
2887       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2888         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2889         SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2890         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2891              ++OtherIdx) {
2892           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2893           if (OtherAddRec->getLoop() == AddRecLoop) {
2894             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2895                  i != e; ++i) {
2896               if (i >= AddRecOps.size()) {
2897                 AddRecOps.append(OtherAddRec->op_begin()+i,
2898                                  OtherAddRec->op_end());
2899                 break;
2900               }
2901               SmallVector<const SCEV *, 2> TwoOps = {
2902                   AddRecOps[i], OtherAddRec->getOperand(i)};
2903               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2904             }
2905             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2906           }
2907         }
2908         // Step size has changed, so we cannot guarantee no self-wraparound.
2909         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2910         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2911       }
2912     }
2913 
2914     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2915     // next one.
2916   }
2917 
2918   // Okay, it looks like we really DO need an add expr.  Check to see if we
2919   // already have one, otherwise create a new one.
2920   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2921 }
2922 
2923 const SCEV *
2924 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2925                                     SCEV::NoWrapFlags Flags) {
2926   FoldingSetNodeID ID;
2927   ID.AddInteger(scAddExpr);
2928   for (const SCEV *Op : Ops)
2929     ID.AddPointer(Op);
2930   void *IP = nullptr;
2931   SCEVAddExpr *S =
2932       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2933   if (!S) {
2934     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2935     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2936     S = new (SCEVAllocator)
2937         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2938     UniqueSCEVs.InsertNode(S, IP);
2939     registerUser(S, Ops);
2940   }
2941   S->setNoWrapFlags(Flags);
2942   return S;
2943 }
2944 
2945 const SCEV *
2946 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2947                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2948   FoldingSetNodeID ID;
2949   ID.AddInteger(scAddRecExpr);
2950   for (const SCEV *Op : Ops)
2951     ID.AddPointer(Op);
2952   ID.AddPointer(L);
2953   void *IP = nullptr;
2954   SCEVAddRecExpr *S =
2955       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2956   if (!S) {
2957     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2958     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2959     S = new (SCEVAllocator)
2960         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2961     UniqueSCEVs.InsertNode(S, IP);
2962     LoopUsers[L].push_back(S);
2963     registerUser(S, Ops);
2964   }
2965   setNoWrapFlags(S, Flags);
2966   return S;
2967 }
2968 
2969 const SCEV *
2970 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2971                                     SCEV::NoWrapFlags Flags) {
2972   FoldingSetNodeID ID;
2973   ID.AddInteger(scMulExpr);
2974   for (const SCEV *Op : Ops)
2975     ID.AddPointer(Op);
2976   void *IP = nullptr;
2977   SCEVMulExpr *S =
2978     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2979   if (!S) {
2980     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2981     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2982     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2983                                         O, Ops.size());
2984     UniqueSCEVs.InsertNode(S, IP);
2985     registerUser(S, Ops);
2986   }
2987   S->setNoWrapFlags(Flags);
2988   return S;
2989 }
2990 
2991 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2992   uint64_t k = i*j;
2993   if (j > 1 && k / j != i) Overflow = true;
2994   return k;
2995 }
2996 
2997 /// Compute the result of "n choose k", the binomial coefficient.  If an
2998 /// intermediate computation overflows, Overflow will be set and the return will
2999 /// be garbage. Overflow is not cleared on absence of overflow.
3000 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3001   // We use the multiplicative formula:
3002   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3003   // At each iteration, we take the n-th term of the numeral and divide by the
3004   // (k-n)th term of the denominator.  This division will always produce an
3005   // integral result, and helps reduce the chance of overflow in the
3006   // intermediate computations. However, we can still overflow even when the
3007   // final result would fit.
3008 
3009   if (n == 0 || n == k) return 1;
3010   if (k > n) return 0;
3011 
3012   if (k > n/2)
3013     k = n-k;
3014 
3015   uint64_t r = 1;
3016   for (uint64_t i = 1; i <= k; ++i) {
3017     r = umul_ov(r, n-(i-1), Overflow);
3018     r /= i;
3019   }
3020   return r;
3021 }
3022 
3023 /// Determine if any of the operands in this SCEV are a constant or if
3024 /// any of the add or multiply expressions in this SCEV contain a constant.
3025 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3026   struct FindConstantInAddMulChain {
3027     bool FoundConstant = false;
3028 
3029     bool follow(const SCEV *S) {
3030       FoundConstant |= isa<SCEVConstant>(S);
3031       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3032     }
3033 
3034     bool isDone() const {
3035       return FoundConstant;
3036     }
3037   };
3038 
3039   FindConstantInAddMulChain F;
3040   SCEVTraversal<FindConstantInAddMulChain> ST(F);
3041   ST.visitAll(StartExpr);
3042   return F.FoundConstant;
3043 }
3044 
3045 /// Get a canonical multiply expression, or something simpler if possible.
3046 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3047                                         SCEV::NoWrapFlags OrigFlags,
3048                                         unsigned Depth) {
3049   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3050          "only nuw or nsw allowed");
3051   assert(!Ops.empty() && "Cannot get empty mul!");
3052   if (Ops.size() == 1) return Ops[0];
3053 #ifndef NDEBUG
3054   Type *ETy = Ops[0]->getType();
3055   assert(!ETy->isPointerTy());
3056   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3057     assert(Ops[i]->getType() == ETy &&
3058            "SCEVMulExpr operand types don't match!");
3059 #endif
3060 
3061   // Sort by complexity, this groups all similar expression types together.
3062   GroupByComplexity(Ops, &LI, DT);
3063 
3064   // If there are any constants, fold them together.
3065   unsigned Idx = 0;
3066   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3067     ++Idx;
3068     assert(Idx < Ops.size());
3069     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3070       // We found two constants, fold them together!
3071       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3072       if (Ops.size() == 2) return Ops[0];
3073       Ops.erase(Ops.begin()+1);  // Erase the folded element
3074       LHSC = cast<SCEVConstant>(Ops[0]);
3075     }
3076 
3077     // If we have a multiply of zero, it will always be zero.
3078     if (LHSC->getValue()->isZero())
3079       return LHSC;
3080 
3081     // If we are left with a constant one being multiplied, strip it off.
3082     if (LHSC->getValue()->isOne()) {
3083       Ops.erase(Ops.begin());
3084       --Idx;
3085     }
3086 
3087     if (Ops.size() == 1)
3088       return Ops[0];
3089   }
3090 
3091   // Delay expensive flag strengthening until necessary.
3092   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3093     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3094   };
3095 
3096   // Limit recursion calls depth.
3097   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3098     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3099 
3100   if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3101     // Don't strengthen flags if we have no new information.
3102     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3103     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3104       Mul->setNoWrapFlags(ComputeFlags(Ops));
3105     return S;
3106   }
3107 
3108   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3109     if (Ops.size() == 2) {
3110       // C1*(C2+V) -> C1*C2 + C1*V
3111       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3112         // If any of Add's ops are Adds or Muls with a constant, apply this
3113         // transformation as well.
3114         //
3115         // TODO: There are some cases where this transformation is not
3116         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
3117         // this transformation should be narrowed down.
3118         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
3119           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
3120                                        SCEV::FlagAnyWrap, Depth + 1),
3121                             getMulExpr(LHSC, Add->getOperand(1),
3122                                        SCEV::FlagAnyWrap, Depth + 1),
3123                             SCEV::FlagAnyWrap, Depth + 1);
3124 
3125       if (Ops[0]->isAllOnesValue()) {
3126         // If we have a mul by -1 of an add, try distributing the -1 among the
3127         // add operands.
3128         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3129           SmallVector<const SCEV *, 4> NewOps;
3130           bool AnyFolded = false;
3131           for (const SCEV *AddOp : Add->operands()) {
3132             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3133                                          Depth + 1);
3134             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3135             NewOps.push_back(Mul);
3136           }
3137           if (AnyFolded)
3138             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3139         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3140           // Negation preserves a recurrence's no self-wrap property.
3141           SmallVector<const SCEV *, 4> Operands;
3142           for (const SCEV *AddRecOp : AddRec->operands())
3143             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3144                                           Depth + 1));
3145 
3146           return getAddRecExpr(Operands, AddRec->getLoop(),
3147                                AddRec->getNoWrapFlags(SCEV::FlagNW));
3148         }
3149       }
3150     }
3151   }
3152 
3153   // Skip over the add expression until we get to a multiply.
3154   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3155     ++Idx;
3156 
3157   // If there are mul operands inline them all into this expression.
3158   if (Idx < Ops.size()) {
3159     bool DeletedMul = false;
3160     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3161       if (Ops.size() > MulOpsInlineThreshold)
3162         break;
3163       // If we have an mul, expand the mul operands onto the end of the
3164       // operands list.
3165       Ops.erase(Ops.begin()+Idx);
3166       Ops.append(Mul->op_begin(), Mul->op_end());
3167       DeletedMul = true;
3168     }
3169 
3170     // If we deleted at least one mul, we added operands to the end of the
3171     // list, and they are not necessarily sorted.  Recurse to resort and
3172     // resimplify any operands we just acquired.
3173     if (DeletedMul)
3174       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3175   }
3176 
3177   // If there are any add recurrences in the operands list, see if any other
3178   // added values are loop invariant.  If so, we can fold them into the
3179   // recurrence.
3180   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3181     ++Idx;
3182 
3183   // Scan over all recurrences, trying to fold loop invariants into them.
3184   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3185     // Scan all of the other operands to this mul and add them to the vector
3186     // if they are loop invariant w.r.t. the recurrence.
3187     SmallVector<const SCEV *, 8> LIOps;
3188     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3189     const Loop *AddRecLoop = AddRec->getLoop();
3190     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3191       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3192         LIOps.push_back(Ops[i]);
3193         Ops.erase(Ops.begin()+i);
3194         --i; --e;
3195       }
3196 
3197     // If we found some loop invariants, fold them into the recurrence.
3198     if (!LIOps.empty()) {
3199       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3200       SmallVector<const SCEV *, 4> NewOps;
3201       NewOps.reserve(AddRec->getNumOperands());
3202       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3203       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3204         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3205                                     SCEV::FlagAnyWrap, Depth + 1));
3206 
3207       // Build the new addrec. Propagate the NUW and NSW flags if both the
3208       // outer mul and the inner addrec are guaranteed to have no overflow.
3209       //
3210       // No self-wrap cannot be guaranteed after changing the step size, but
3211       // will be inferred if either NUW or NSW is true.
3212       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3213       const SCEV *NewRec = getAddRecExpr(
3214           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3215 
3216       // If all of the other operands were loop invariant, we are done.
3217       if (Ops.size() == 1) return NewRec;
3218 
3219       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3220       for (unsigned i = 0;; ++i)
3221         if (Ops[i] == AddRec) {
3222           Ops[i] = NewRec;
3223           break;
3224         }
3225       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3226     }
3227 
3228     // Okay, if there weren't any loop invariants to be folded, check to see
3229     // if there are multiple AddRec's with the same loop induction variable
3230     // being multiplied together.  If so, we can fold them.
3231 
3232     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3233     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3234     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3235     //   ]]],+,...up to x=2n}.
3236     // Note that the arguments to choose() are always integers with values
3237     // known at compile time, never SCEV objects.
3238     //
3239     // The implementation avoids pointless extra computations when the two
3240     // addrec's are of different length (mathematically, it's equivalent to
3241     // an infinite stream of zeros on the right).
3242     bool OpsModified = false;
3243     for (unsigned OtherIdx = Idx+1;
3244          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3245          ++OtherIdx) {
3246       const SCEVAddRecExpr *OtherAddRec =
3247         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3248       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3249         continue;
3250 
3251       // Limit max number of arguments to avoid creation of unreasonably big
3252       // SCEVAddRecs with very complex operands.
3253       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3254           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3255         continue;
3256 
3257       bool Overflow = false;
3258       Type *Ty = AddRec->getType();
3259       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3260       SmallVector<const SCEV*, 7> AddRecOps;
3261       for (int x = 0, xe = AddRec->getNumOperands() +
3262              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3263         SmallVector <const SCEV *, 7> SumOps;
3264         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3265           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3266           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3267                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3268                z < ze && !Overflow; ++z) {
3269             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3270             uint64_t Coeff;
3271             if (LargerThan64Bits)
3272               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3273             else
3274               Coeff = Coeff1*Coeff2;
3275             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3276             const SCEV *Term1 = AddRec->getOperand(y-z);
3277             const SCEV *Term2 = OtherAddRec->getOperand(z);
3278             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3279                                         SCEV::FlagAnyWrap, Depth + 1));
3280           }
3281         }
3282         if (SumOps.empty())
3283           SumOps.push_back(getZero(Ty));
3284         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3285       }
3286       if (!Overflow) {
3287         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3288                                               SCEV::FlagAnyWrap);
3289         if (Ops.size() == 2) return NewAddRec;
3290         Ops[Idx] = NewAddRec;
3291         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3292         OpsModified = true;
3293         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3294         if (!AddRec)
3295           break;
3296       }
3297     }
3298     if (OpsModified)
3299       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3300 
3301     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3302     // next one.
3303   }
3304 
3305   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3306   // already have one, otherwise create a new one.
3307   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3308 }
3309 
3310 /// Represents an unsigned remainder expression based on unsigned division.
3311 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3312                                          const SCEV *RHS) {
3313   assert(getEffectiveSCEVType(LHS->getType()) ==
3314          getEffectiveSCEVType(RHS->getType()) &&
3315          "SCEVURemExpr operand types don't match!");
3316 
3317   // Short-circuit easy cases
3318   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3319     // If constant is one, the result is trivial
3320     if (RHSC->getValue()->isOne())
3321       return getZero(LHS->getType()); // X urem 1 --> 0
3322 
3323     // If constant is a power of two, fold into a zext(trunc(LHS)).
3324     if (RHSC->getAPInt().isPowerOf2()) {
3325       Type *FullTy = LHS->getType();
3326       Type *TruncTy =
3327           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3328       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3329     }
3330   }
3331 
3332   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3333   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3334   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3335   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3336 }
3337 
3338 /// Get a canonical unsigned division expression, or something simpler if
3339 /// possible.
3340 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3341                                          const SCEV *RHS) {
3342   assert(!LHS->getType()->isPointerTy() &&
3343          "SCEVUDivExpr operand can't be pointer!");
3344   assert(LHS->getType() == RHS->getType() &&
3345          "SCEVUDivExpr operand types don't match!");
3346 
3347   FoldingSetNodeID ID;
3348   ID.AddInteger(scUDivExpr);
3349   ID.AddPointer(LHS);
3350   ID.AddPointer(RHS);
3351   void *IP = nullptr;
3352   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3353     return S;
3354 
3355   // 0 udiv Y == 0
3356   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3357     if (LHSC->getValue()->isZero())
3358       return LHS;
3359 
3360   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3361     if (RHSC->getValue()->isOne())
3362       return LHS;                               // X udiv 1 --> x
3363     // If the denominator is zero, the result of the udiv is undefined. Don't
3364     // try to analyze it, because the resolution chosen here may differ from
3365     // the resolution chosen in other parts of the compiler.
3366     if (!RHSC->getValue()->isZero()) {
3367       // Determine if the division can be folded into the operands of
3368       // its operands.
3369       // TODO: Generalize this to non-constants by using known-bits information.
3370       Type *Ty = LHS->getType();
3371       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3372       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3373       // For non-power-of-two values, effectively round the value up to the
3374       // nearest power of two.
3375       if (!RHSC->getAPInt().isPowerOf2())
3376         ++MaxShiftAmt;
3377       IntegerType *ExtTy =
3378         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3379       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3380         if (const SCEVConstant *Step =
3381             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3382           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3383           const APInt &StepInt = Step->getAPInt();
3384           const APInt &DivInt = RHSC->getAPInt();
3385           if (!StepInt.urem(DivInt) &&
3386               getZeroExtendExpr(AR, ExtTy) ==
3387               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3388                             getZeroExtendExpr(Step, ExtTy),
3389                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3390             SmallVector<const SCEV *, 4> Operands;
3391             for (const SCEV *Op : AR->operands())
3392               Operands.push_back(getUDivExpr(Op, RHS));
3393             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3394           }
3395           /// Get a canonical UDivExpr for a recurrence.
3396           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3397           // We can currently only fold X%N if X is constant.
3398           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3399           if (StartC && !DivInt.urem(StepInt) &&
3400               getZeroExtendExpr(AR, ExtTy) ==
3401               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3402                             getZeroExtendExpr(Step, ExtTy),
3403                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3404             const APInt &StartInt = StartC->getAPInt();
3405             const APInt &StartRem = StartInt.urem(StepInt);
3406             if (StartRem != 0) {
3407               const SCEV *NewLHS =
3408                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3409                                 AR->getLoop(), SCEV::FlagNW);
3410               if (LHS != NewLHS) {
3411                 LHS = NewLHS;
3412 
3413                 // Reset the ID to include the new LHS, and check if it is
3414                 // already cached.
3415                 ID.clear();
3416                 ID.AddInteger(scUDivExpr);
3417                 ID.AddPointer(LHS);
3418                 ID.AddPointer(RHS);
3419                 IP = nullptr;
3420                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3421                   return S;
3422               }
3423             }
3424           }
3425         }
3426       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3427       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3428         SmallVector<const SCEV *, 4> Operands;
3429         for (const SCEV *Op : M->operands())
3430           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3431         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3432           // Find an operand that's safely divisible.
3433           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3434             const SCEV *Op = M->getOperand(i);
3435             const SCEV *Div = getUDivExpr(Op, RHSC);
3436             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3437               Operands = SmallVector<const SCEV *, 4>(M->operands());
3438               Operands[i] = Div;
3439               return getMulExpr(Operands);
3440             }
3441           }
3442       }
3443 
3444       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3445       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3446         if (auto *DivisorConstant =
3447                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3448           bool Overflow = false;
3449           APInt NewRHS =
3450               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3451           if (Overflow) {
3452             return getConstant(RHSC->getType(), 0, false);
3453           }
3454           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3455         }
3456       }
3457 
3458       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3459       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3460         SmallVector<const SCEV *, 4> Operands;
3461         for (const SCEV *Op : A->operands())
3462           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3463         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3464           Operands.clear();
3465           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3466             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3467             if (isa<SCEVUDivExpr>(Op) ||
3468                 getMulExpr(Op, RHS) != A->getOperand(i))
3469               break;
3470             Operands.push_back(Op);
3471           }
3472           if (Operands.size() == A->getNumOperands())
3473             return getAddExpr(Operands);
3474         }
3475       }
3476 
3477       // Fold if both operands are constant.
3478       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3479         Constant *LHSCV = LHSC->getValue();
3480         Constant *RHSCV = RHSC->getValue();
3481         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3482                                                                    RHSCV)));
3483       }
3484     }
3485   }
3486 
3487   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3488   // changes). Make sure we get a new one.
3489   IP = nullptr;
3490   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3491   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3492                                              LHS, RHS);
3493   UniqueSCEVs.InsertNode(S, IP);
3494   registerUser(S, {LHS, RHS});
3495   return S;
3496 }
3497 
3498 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3499   APInt A = C1->getAPInt().abs();
3500   APInt B = C2->getAPInt().abs();
3501   uint32_t ABW = A.getBitWidth();
3502   uint32_t BBW = B.getBitWidth();
3503 
3504   if (ABW > BBW)
3505     B = B.zext(ABW);
3506   else if (ABW < BBW)
3507     A = A.zext(BBW);
3508 
3509   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3510 }
3511 
3512 /// Get a canonical unsigned division expression, or something simpler if
3513 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3514 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3515 /// it's not exact because the udiv may be clearing bits.
3516 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3517                                               const SCEV *RHS) {
3518   // TODO: we could try to find factors in all sorts of things, but for now we
3519   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3520   // end of this file for inspiration.
3521 
3522   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3523   if (!Mul || !Mul->hasNoUnsignedWrap())
3524     return getUDivExpr(LHS, RHS);
3525 
3526   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3527     // If the mulexpr multiplies by a constant, then that constant must be the
3528     // first element of the mulexpr.
3529     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3530       if (LHSCst == RHSCst) {
3531         SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3532         return getMulExpr(Operands);
3533       }
3534 
3535       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3536       // that there's a factor provided by one of the other terms. We need to
3537       // check.
3538       APInt Factor = gcd(LHSCst, RHSCst);
3539       if (!Factor.isIntN(1)) {
3540         LHSCst =
3541             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3542         RHSCst =
3543             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3544         SmallVector<const SCEV *, 2> Operands;
3545         Operands.push_back(LHSCst);
3546         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3547         LHS = getMulExpr(Operands);
3548         RHS = RHSCst;
3549         Mul = dyn_cast<SCEVMulExpr>(LHS);
3550         if (!Mul)
3551           return getUDivExactExpr(LHS, RHS);
3552       }
3553     }
3554   }
3555 
3556   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3557     if (Mul->getOperand(i) == RHS) {
3558       SmallVector<const SCEV *, 2> Operands;
3559       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3560       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3561       return getMulExpr(Operands);
3562     }
3563   }
3564 
3565   return getUDivExpr(LHS, RHS);
3566 }
3567 
3568 /// Get an add recurrence expression for the specified loop.  Simplify the
3569 /// expression as much as possible.
3570 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3571                                            const Loop *L,
3572                                            SCEV::NoWrapFlags Flags) {
3573   SmallVector<const SCEV *, 4> Operands;
3574   Operands.push_back(Start);
3575   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3576     if (StepChrec->getLoop() == L) {
3577       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3578       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3579     }
3580 
3581   Operands.push_back(Step);
3582   return getAddRecExpr(Operands, L, Flags);
3583 }
3584 
3585 /// Get an add recurrence expression for the specified loop.  Simplify the
3586 /// expression as much as possible.
3587 const SCEV *
3588 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3589                                const Loop *L, SCEV::NoWrapFlags Flags) {
3590   if (Operands.size() == 1) return Operands[0];
3591 #ifndef NDEBUG
3592   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3593   for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3594     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3595            "SCEVAddRecExpr operand types don't match!");
3596     assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3597   }
3598   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3599     assert(isLoopInvariant(Operands[i], L) &&
3600            "SCEVAddRecExpr operand is not loop-invariant!");
3601 #endif
3602 
3603   if (Operands.back()->isZero()) {
3604     Operands.pop_back();
3605     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3606   }
3607 
3608   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3609   // use that information to infer NUW and NSW flags. However, computing a
3610   // BE count requires calling getAddRecExpr, so we may not yet have a
3611   // meaningful BE count at this point (and if we don't, we'd be stuck
3612   // with a SCEVCouldNotCompute as the cached BE count).
3613 
3614   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3615 
3616   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3617   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3618     const Loop *NestedLoop = NestedAR->getLoop();
3619     if (L->contains(NestedLoop)
3620             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3621             : (!NestedLoop->contains(L) &&
3622                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3623       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3624       Operands[0] = NestedAR->getStart();
3625       // AddRecs require their operands be loop-invariant with respect to their
3626       // loops. Don't perform this transformation if it would break this
3627       // requirement.
3628       bool AllInvariant = all_of(
3629           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3630 
3631       if (AllInvariant) {
3632         // Create a recurrence for the outer loop with the same step size.
3633         //
3634         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3635         // inner recurrence has the same property.
3636         SCEV::NoWrapFlags OuterFlags =
3637           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3638 
3639         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3640         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3641           return isLoopInvariant(Op, NestedLoop);
3642         });
3643 
3644         if (AllInvariant) {
3645           // Ok, both add recurrences are valid after the transformation.
3646           //
3647           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3648           // the outer recurrence has the same property.
3649           SCEV::NoWrapFlags InnerFlags =
3650             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3651           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3652         }
3653       }
3654       // Reset Operands to its original state.
3655       Operands[0] = NestedAR;
3656     }
3657   }
3658 
3659   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3660   // already have one, otherwise create a new one.
3661   return getOrCreateAddRecExpr(Operands, L, Flags);
3662 }
3663 
3664 const SCEV *
3665 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3666                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3667   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3668   // getSCEV(Base)->getType() has the same address space as Base->getType()
3669   // because SCEV::getType() preserves the address space.
3670   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3671   const bool AssumeInBoundsFlags = [&]() {
3672     if (!GEP->isInBounds())
3673       return false;
3674 
3675     // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3676     // but to do that, we have to ensure that said flag is valid in the entire
3677     // defined scope of the SCEV.
3678     auto *GEPI = dyn_cast<Instruction>(GEP);
3679     // TODO: non-instructions have global scope.  We might be able to prove
3680     // some global scope cases
3681     return GEPI && isSCEVExprNeverPoison(GEPI);
3682   }();
3683 
3684   SCEV::NoWrapFlags OffsetWrap =
3685     AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3686 
3687   Type *CurTy = GEP->getType();
3688   bool FirstIter = true;
3689   SmallVector<const SCEV *, 4> Offsets;
3690   for (const SCEV *IndexExpr : IndexExprs) {
3691     // Compute the (potentially symbolic) offset in bytes for this index.
3692     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3693       // For a struct, add the member offset.
3694       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3695       unsigned FieldNo = Index->getZExtValue();
3696       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3697       Offsets.push_back(FieldOffset);
3698 
3699       // Update CurTy to the type of the field at Index.
3700       CurTy = STy->getTypeAtIndex(Index);
3701     } else {
3702       // Update CurTy to its element type.
3703       if (FirstIter) {
3704         assert(isa<PointerType>(CurTy) &&
3705                "The first index of a GEP indexes a pointer");
3706         CurTy = GEP->getSourceElementType();
3707         FirstIter = false;
3708       } else {
3709         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3710       }
3711       // For an array, add the element offset, explicitly scaled.
3712       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3713       // Getelementptr indices are signed.
3714       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3715 
3716       // Multiply the index by the element size to compute the element offset.
3717       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3718       Offsets.push_back(LocalOffset);
3719     }
3720   }
3721 
3722   // Handle degenerate case of GEP without offsets.
3723   if (Offsets.empty())
3724     return BaseExpr;
3725 
3726   // Add the offsets together, assuming nsw if inbounds.
3727   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3728   // Add the base address and the offset. We cannot use the nsw flag, as the
3729   // base address is unsigned. However, if we know that the offset is
3730   // non-negative, we can use nuw.
3731   SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3732                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3733   auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3734   assert(BaseExpr->getType() == GEPExpr->getType() &&
3735          "GEP should not change type mid-flight.");
3736   return GEPExpr;
3737 }
3738 
3739 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3740                                                ArrayRef<const SCEV *> Ops) {
3741   FoldingSetNodeID ID;
3742   ID.AddInteger(SCEVType);
3743   for (const SCEV *Op : Ops)
3744     ID.AddPointer(Op);
3745   void *IP = nullptr;
3746   return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3747 }
3748 
3749 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3750   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3751   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3752 }
3753 
3754 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3755                                            SmallVectorImpl<const SCEV *> &Ops) {
3756   assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3757   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3758   if (Ops.size() == 1) return Ops[0];
3759 #ifndef NDEBUG
3760   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3761   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3762     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3763            "Operand types don't match!");
3764     assert(Ops[0]->getType()->isPointerTy() ==
3765                Ops[i]->getType()->isPointerTy() &&
3766            "min/max should be consistently pointerish");
3767   }
3768 #endif
3769 
3770   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3771   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3772 
3773   // Sort by complexity, this groups all similar expression types together.
3774   GroupByComplexity(Ops, &LI, DT);
3775 
3776   // Check if we have created the same expression before.
3777   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3778     return S;
3779   }
3780 
3781   // If there are any constants, fold them together.
3782   unsigned Idx = 0;
3783   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3784     ++Idx;
3785     assert(Idx < Ops.size());
3786     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3787       if (Kind == scSMaxExpr)
3788         return APIntOps::smax(LHS, RHS);
3789       else if (Kind == scSMinExpr)
3790         return APIntOps::smin(LHS, RHS);
3791       else if (Kind == scUMaxExpr)
3792         return APIntOps::umax(LHS, RHS);
3793       else if (Kind == scUMinExpr)
3794         return APIntOps::umin(LHS, RHS);
3795       llvm_unreachable("Unknown SCEV min/max opcode");
3796     };
3797 
3798     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3799       // We found two constants, fold them together!
3800       ConstantInt *Fold = ConstantInt::get(
3801           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3802       Ops[0] = getConstant(Fold);
3803       Ops.erase(Ops.begin()+1);  // Erase the folded element
3804       if (Ops.size() == 1) return Ops[0];
3805       LHSC = cast<SCEVConstant>(Ops[0]);
3806     }
3807 
3808     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3809     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3810 
3811     if (IsMax ? IsMinV : IsMaxV) {
3812       // If we are left with a constant minimum(/maximum)-int, strip it off.
3813       Ops.erase(Ops.begin());
3814       --Idx;
3815     } else if (IsMax ? IsMaxV : IsMinV) {
3816       // If we have a max(/min) with a constant maximum(/minimum)-int,
3817       // it will always be the extremum.
3818       return LHSC;
3819     }
3820 
3821     if (Ops.size() == 1) return Ops[0];
3822   }
3823 
3824   // Find the first operation of the same kind
3825   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3826     ++Idx;
3827 
3828   // Check to see if one of the operands is of the same kind. If so, expand its
3829   // operands onto our operand list, and recurse to simplify.
3830   if (Idx < Ops.size()) {
3831     bool DeletedAny = false;
3832     while (Ops[Idx]->getSCEVType() == Kind) {
3833       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3834       Ops.erase(Ops.begin()+Idx);
3835       Ops.append(SMME->op_begin(), SMME->op_end());
3836       DeletedAny = true;
3837     }
3838 
3839     if (DeletedAny)
3840       return getMinMaxExpr(Kind, Ops);
3841   }
3842 
3843   // Okay, check to see if the same value occurs in the operand list twice.  If
3844   // so, delete one.  Since we sorted the list, these values are required to
3845   // be adjacent.
3846   llvm::CmpInst::Predicate GEPred =
3847       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3848   llvm::CmpInst::Predicate LEPred =
3849       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3850   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3851   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3852   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3853     if (Ops[i] == Ops[i + 1] ||
3854         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3855       //  X op Y op Y  -->  X op Y
3856       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3857       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3858       --i;
3859       --e;
3860     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3861                                                Ops[i + 1])) {
3862       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3863       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3864       --i;
3865       --e;
3866     }
3867   }
3868 
3869   if (Ops.size() == 1) return Ops[0];
3870 
3871   assert(!Ops.empty() && "Reduced smax down to nothing!");
3872 
3873   // Okay, it looks like we really DO need an expr.  Check to see if we
3874   // already have one, otherwise create a new one.
3875   FoldingSetNodeID ID;
3876   ID.AddInteger(Kind);
3877   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3878     ID.AddPointer(Ops[i]);
3879   void *IP = nullptr;
3880   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3881   if (ExistingSCEV)
3882     return ExistingSCEV;
3883   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3884   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3885   SCEV *S = new (SCEVAllocator)
3886       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3887 
3888   UniqueSCEVs.InsertNode(S, IP);
3889   registerUser(S, Ops);
3890   return S;
3891 }
3892 
3893 namespace {
3894 
3895 class SCEVSequentialMinMaxDeduplicatingVisitor final
3896     : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3897                          Optional<const SCEV *>> {
3898   using RetVal = Optional<const SCEV *>;
3899   using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3900 
3901   ScalarEvolution &SE;
3902   const SCEVTypes RootKind; // Must be a sequential min/max expression.
3903   const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3904   SmallPtrSet<const SCEV *, 16> SeenOps;
3905 
3906   bool canRecurseInto(SCEVTypes Kind) const {
3907     // We can only recurse into the SCEV expression of the same effective type
3908     // as the type of our root SCEV expression.
3909     return RootKind == Kind || NonSequentialRootKind == Kind;
3910   };
3911 
3912   RetVal visitAnyMinMaxExpr(const SCEV *S) {
3913     assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3914            "Only for min/max expressions.");
3915     SCEVTypes Kind = S->getSCEVType();
3916 
3917     if (!canRecurseInto(Kind))
3918       return S;
3919 
3920     auto *NAry = cast<SCEVNAryExpr>(S);
3921     SmallVector<const SCEV *> NewOps;
3922     bool Changed =
3923         visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps);
3924 
3925     if (!Changed)
3926       return S;
3927     if (NewOps.empty())
3928       return None;
3929 
3930     return isa<SCEVSequentialMinMaxExpr>(S)
3931                ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3932                : SE.getMinMaxExpr(Kind, NewOps);
3933   }
3934 
3935   RetVal visit(const SCEV *S) {
3936     // Has the whole operand been seen already?
3937     if (!SeenOps.insert(S).second)
3938       return None;
3939     return Base::visit(S);
3940   }
3941 
3942 public:
3943   SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3944                                            SCEVTypes RootKind)
3945       : SE(SE), RootKind(RootKind),
3946         NonSequentialRootKind(
3947             SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3948                 RootKind)) {}
3949 
3950   bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
3951                          SmallVectorImpl<const SCEV *> &NewOps) {
3952     bool Changed = false;
3953     SmallVector<const SCEV *> Ops;
3954     Ops.reserve(OrigOps.size());
3955 
3956     for (const SCEV *Op : OrigOps) {
3957       RetVal NewOp = visit(Op);
3958       if (NewOp != Op)
3959         Changed = true;
3960       if (NewOp)
3961         Ops.emplace_back(*NewOp);
3962     }
3963 
3964     if (Changed)
3965       NewOps = std::move(Ops);
3966     return Changed;
3967   }
3968 
3969   RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
3970 
3971   RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
3972 
3973   RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
3974 
3975   RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
3976 
3977   RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
3978 
3979   RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
3980 
3981   RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
3982 
3983   RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
3984 
3985   RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
3986 
3987   RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
3988     return visitAnyMinMaxExpr(Expr);
3989   }
3990 
3991   RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
3992     return visitAnyMinMaxExpr(Expr);
3993   }
3994 
3995   RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
3996     return visitAnyMinMaxExpr(Expr);
3997   }
3998 
3999   RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4000     return visitAnyMinMaxExpr(Expr);
4001   }
4002 
4003   RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4004     return visitAnyMinMaxExpr(Expr);
4005   }
4006 
4007   RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4008 
4009   RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4010 };
4011 
4012 } // namespace
4013 
4014 const SCEV *
4015 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4016                                          SmallVectorImpl<const SCEV *> &Ops) {
4017   assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4018          "Not a SCEVSequentialMinMaxExpr!");
4019   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4020   if (Ops.size() == 1)
4021     return Ops[0];
4022   if (Ops.size() == 2 &&
4023       any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); }))
4024     return getMinMaxExpr(
4025         SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4026         Ops);
4027 #ifndef NDEBUG
4028   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4029   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4030     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4031            "Operand types don't match!");
4032     assert(Ops[0]->getType()->isPointerTy() ==
4033                Ops[i]->getType()->isPointerTy() &&
4034            "min/max should be consistently pointerish");
4035   }
4036 #endif
4037 
4038   // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4039   // so we can *NOT* do any kind of sorting of the expressions!
4040 
4041   // Check if we have created the same expression before.
4042   if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4043     return S;
4044 
4045   // FIXME: there are *some* simplifications that we can do here.
4046 
4047   // Keep only the first instance of an operand.
4048   {
4049     SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4050     bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4051     if (Changed)
4052       return getSequentialMinMaxExpr(Kind, Ops);
4053   }
4054 
4055   // Check to see if one of the operands is of the same kind. If so, expand its
4056   // operands onto our operand list, and recurse to simplify.
4057   {
4058     unsigned Idx = 0;
4059     bool DeletedAny = false;
4060     while (Idx < Ops.size()) {
4061       if (Ops[Idx]->getSCEVType() != Kind) {
4062         ++Idx;
4063         continue;
4064       }
4065       const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4066       Ops.erase(Ops.begin() + Idx);
4067       Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end());
4068       DeletedAny = true;
4069     }
4070 
4071     if (DeletedAny)
4072       return getSequentialMinMaxExpr(Kind, Ops);
4073   }
4074 
4075   // Okay, it looks like we really DO need an expr.  Check to see if we
4076   // already have one, otherwise create a new one.
4077   FoldingSetNodeID ID;
4078   ID.AddInteger(Kind);
4079   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4080     ID.AddPointer(Ops[i]);
4081   void *IP = nullptr;
4082   const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4083   if (ExistingSCEV)
4084     return ExistingSCEV;
4085 
4086   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4087   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4088   SCEV *S = new (SCEVAllocator)
4089       SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4090 
4091   UniqueSCEVs.InsertNode(S, IP);
4092   registerUser(S, Ops);
4093   return S;
4094 }
4095 
4096 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4097   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4098   return getSMaxExpr(Ops);
4099 }
4100 
4101 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4102   return getMinMaxExpr(scSMaxExpr, Ops);
4103 }
4104 
4105 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4106   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4107   return getUMaxExpr(Ops);
4108 }
4109 
4110 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4111   return getMinMaxExpr(scUMaxExpr, Ops);
4112 }
4113 
4114 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4115                                          const SCEV *RHS) {
4116   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4117   return getSMinExpr(Ops);
4118 }
4119 
4120 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4121   return getMinMaxExpr(scSMinExpr, Ops);
4122 }
4123 
4124 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4125                                          bool Sequential) {
4126   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4127   return getUMinExpr(Ops, Sequential);
4128 }
4129 
4130 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4131                                          bool Sequential) {
4132   return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4133                     : getMinMaxExpr(scUMinExpr, Ops);
4134 }
4135 
4136 const SCEV *
4137 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
4138                                              ScalableVectorType *ScalableTy) {
4139   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
4140   Constant *One = ConstantInt::get(IntTy, 1);
4141   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
4142   // Note that the expression we created is the final expression, we don't
4143   // want to simplify it any further Also, if we call a normal getSCEV(),
4144   // we'll end up in an endless recursion. So just create an SCEVUnknown.
4145   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
4146 }
4147 
4148 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4149   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
4150     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
4151   // We can bypass creating a target-independent constant expression and then
4152   // folding it back into a ConstantInt. This is just a compile-time
4153   // optimization.
4154   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4155 }
4156 
4157 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4158   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
4159     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
4160   // We can bypass creating a target-independent constant expression and then
4161   // folding it back into a ConstantInt. This is just a compile-time
4162   // optimization.
4163   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4164 }
4165 
4166 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4167                                              StructType *STy,
4168                                              unsigned FieldNo) {
4169   // We can bypass creating a target-independent constant expression and then
4170   // folding it back into a ConstantInt. This is just a compile-time
4171   // optimization.
4172   return getConstant(
4173       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4174 }
4175 
4176 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4177   // Don't attempt to do anything other than create a SCEVUnknown object
4178   // here.  createSCEV only calls getUnknown after checking for all other
4179   // interesting possibilities, and any other code that calls getUnknown
4180   // is doing so in order to hide a value from SCEV canonicalization.
4181 
4182   FoldingSetNodeID ID;
4183   ID.AddInteger(scUnknown);
4184   ID.AddPointer(V);
4185   void *IP = nullptr;
4186   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4187     assert(cast<SCEVUnknown>(S)->getValue() == V &&
4188            "Stale SCEVUnknown in uniquing map!");
4189     return S;
4190   }
4191   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4192                                             FirstUnknown);
4193   FirstUnknown = cast<SCEVUnknown>(S);
4194   UniqueSCEVs.InsertNode(S, IP);
4195   return S;
4196 }
4197 
4198 //===----------------------------------------------------------------------===//
4199 //            Basic SCEV Analysis and PHI Idiom Recognition Code
4200 //
4201 
4202 /// Test if values of the given type are analyzable within the SCEV
4203 /// framework. This primarily includes integer types, and it can optionally
4204 /// include pointer types if the ScalarEvolution class has access to
4205 /// target-specific information.
4206 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4207   // Integers and pointers are always SCEVable.
4208   return Ty->isIntOrPtrTy();
4209 }
4210 
4211 /// Return the size in bits of the specified type, for which isSCEVable must
4212 /// return true.
4213 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4214   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4215   if (Ty->isPointerTy())
4216     return getDataLayout().getIndexTypeSizeInBits(Ty);
4217   return getDataLayout().getTypeSizeInBits(Ty);
4218 }
4219 
4220 /// Return a type with the same bitwidth as the given type and which represents
4221 /// how SCEV will treat the given type, for which isSCEVable must return
4222 /// true. For pointer types, this is the pointer index sized integer type.
4223 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4224   assert(isSCEVable(Ty) && "Type is not SCEVable!");
4225 
4226   if (Ty->isIntegerTy())
4227     return Ty;
4228 
4229   // The only other support type is pointer.
4230   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4231   return getDataLayout().getIndexType(Ty);
4232 }
4233 
4234 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4235   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4236 }
4237 
4238 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4239                                                          const SCEV *B) {
4240   /// For a valid use point to exist, the defining scope of one operand
4241   /// must dominate the other.
4242   bool PreciseA, PreciseB;
4243   auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4244   auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4245   if (!PreciseA || !PreciseB)
4246     // Can't tell.
4247     return false;
4248   return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4249     DT.dominates(ScopeB, ScopeA);
4250 }
4251 
4252 
4253 const SCEV *ScalarEvolution::getCouldNotCompute() {
4254   return CouldNotCompute.get();
4255 }
4256 
4257 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4258   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4259     auto *SU = dyn_cast<SCEVUnknown>(S);
4260     return SU && SU->getValue() == nullptr;
4261   });
4262 
4263   return !ContainsNulls;
4264 }
4265 
4266 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4267   HasRecMapType::iterator I = HasRecMap.find(S);
4268   if (I != HasRecMap.end())
4269     return I->second;
4270 
4271   bool FoundAddRec =
4272       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4273   HasRecMap.insert({S, FoundAddRec});
4274   return FoundAddRec;
4275 }
4276 
4277 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4278 /// by the value and offset from any ValueOffsetPair in the set.
4279 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4280   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4281   if (SI == ExprValueMap.end())
4282     return None;
4283 #ifndef NDEBUG
4284   if (VerifySCEVMap) {
4285     // Check there is no dangling Value in the set returned.
4286     for (Value *V : SI->second)
4287       assert(ValueExprMap.count(V));
4288   }
4289 #endif
4290   return SI->second.getArrayRef();
4291 }
4292 
4293 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4294 /// cannot be used separately. eraseValueFromMap should be used to remove
4295 /// V from ValueExprMap and ExprValueMap at the same time.
4296 void ScalarEvolution::eraseValueFromMap(Value *V) {
4297   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4298   if (I != ValueExprMap.end()) {
4299     auto EVIt = ExprValueMap.find(I->second);
4300     bool Removed = EVIt->second.remove(V);
4301     (void) Removed;
4302     assert(Removed && "Value not in ExprValueMap?");
4303     ValueExprMap.erase(I);
4304   }
4305 }
4306 
4307 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4308   // A recursive query may have already computed the SCEV. It should be
4309   // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4310   // inferred nowrap flags.
4311   auto It = ValueExprMap.find_as(V);
4312   if (It == ValueExprMap.end()) {
4313     ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4314     ExprValueMap[S].insert(V);
4315   }
4316 }
4317 
4318 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4319 /// create a new one.
4320 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4321   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4322 
4323   const SCEV *S = getExistingSCEV(V);
4324   if (S == nullptr) {
4325     S = createSCEV(V);
4326     // During PHI resolution, it is possible to create two SCEVs for the same
4327     // V, so it is needed to double check whether V->S is inserted into
4328     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
4329     std::pair<ValueExprMapType::iterator, bool> Pair =
4330         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4331     if (Pair.second)
4332       ExprValueMap[S].insert(V);
4333   }
4334   return S;
4335 }
4336 
4337 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4338   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4339 
4340   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4341   if (I != ValueExprMap.end()) {
4342     const SCEV *S = I->second;
4343     assert(checkValidity(S) &&
4344            "existing SCEV has not been properly invalidated");
4345     return S;
4346   }
4347   return nullptr;
4348 }
4349 
4350 /// Return a SCEV corresponding to -V = -1*V
4351 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4352                                              SCEV::NoWrapFlags Flags) {
4353   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4354     return getConstant(
4355                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4356 
4357   Type *Ty = V->getType();
4358   Ty = getEffectiveSCEVType(Ty);
4359   return getMulExpr(V, getMinusOne(Ty), Flags);
4360 }
4361 
4362 /// If Expr computes ~A, return A else return nullptr
4363 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4364   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4365   if (!Add || Add->getNumOperands() != 2 ||
4366       !Add->getOperand(0)->isAllOnesValue())
4367     return nullptr;
4368 
4369   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4370   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4371       !AddRHS->getOperand(0)->isAllOnesValue())
4372     return nullptr;
4373 
4374   return AddRHS->getOperand(1);
4375 }
4376 
4377 /// Return a SCEV corresponding to ~V = -1-V
4378 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4379   assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4380 
4381   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4382     return getConstant(
4383                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4384 
4385   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4386   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4387     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4388       SmallVector<const SCEV *, 2> MatchedOperands;
4389       for (const SCEV *Operand : MME->operands()) {
4390         const SCEV *Matched = MatchNotExpr(Operand);
4391         if (!Matched)
4392           return (const SCEV *)nullptr;
4393         MatchedOperands.push_back(Matched);
4394       }
4395       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4396                            MatchedOperands);
4397     };
4398     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4399       return Replaced;
4400   }
4401 
4402   Type *Ty = V->getType();
4403   Ty = getEffectiveSCEVType(Ty);
4404   return getMinusSCEV(getMinusOne(Ty), V);
4405 }
4406 
4407 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4408   assert(P->getType()->isPointerTy());
4409 
4410   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4411     // The base of an AddRec is the first operand.
4412     SmallVector<const SCEV *> Ops{AddRec->operands()};
4413     Ops[0] = removePointerBase(Ops[0]);
4414     // Don't try to transfer nowrap flags for now. We could in some cases
4415     // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4416     return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4417   }
4418   if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4419     // The base of an Add is the pointer operand.
4420     SmallVector<const SCEV *> Ops{Add->operands()};
4421     const SCEV **PtrOp = nullptr;
4422     for (const SCEV *&AddOp : Ops) {
4423       if (AddOp->getType()->isPointerTy()) {
4424         assert(!PtrOp && "Cannot have multiple pointer ops");
4425         PtrOp = &AddOp;
4426       }
4427     }
4428     *PtrOp = removePointerBase(*PtrOp);
4429     // Don't try to transfer nowrap flags for now. We could in some cases
4430     // (for example, if the pointer operand of the Add is a SCEVUnknown).
4431     return getAddExpr(Ops);
4432   }
4433   // Any other expression must be a pointer base.
4434   return getZero(P->getType());
4435 }
4436 
4437 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4438                                           SCEV::NoWrapFlags Flags,
4439                                           unsigned Depth) {
4440   // Fast path: X - X --> 0.
4441   if (LHS == RHS)
4442     return getZero(LHS->getType());
4443 
4444   // If we subtract two pointers with different pointer bases, bail.
4445   // Eventually, we're going to add an assertion to getMulExpr that we
4446   // can't multiply by a pointer.
4447   if (RHS->getType()->isPointerTy()) {
4448     if (!LHS->getType()->isPointerTy() ||
4449         getPointerBase(LHS) != getPointerBase(RHS))
4450       return getCouldNotCompute();
4451     LHS = removePointerBase(LHS);
4452     RHS = removePointerBase(RHS);
4453   }
4454 
4455   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4456   // makes it so that we cannot make much use of NUW.
4457   auto AddFlags = SCEV::FlagAnyWrap;
4458   const bool RHSIsNotMinSigned =
4459       !getSignedRangeMin(RHS).isMinSignedValue();
4460   if (hasFlags(Flags, SCEV::FlagNSW)) {
4461     // Let M be the minimum representable signed value. Then (-1)*RHS
4462     // signed-wraps if and only if RHS is M. That can happen even for
4463     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4464     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4465     // (-1)*RHS, we need to prove that RHS != M.
4466     //
4467     // If LHS is non-negative and we know that LHS - RHS does not
4468     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4469     // either by proving that RHS > M or that LHS >= 0.
4470     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4471       AddFlags = SCEV::FlagNSW;
4472     }
4473   }
4474 
4475   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4476   // RHS is NSW and LHS >= 0.
4477   //
4478   // The difficulty here is that the NSW flag may have been proven
4479   // relative to a loop that is to be found in a recurrence in LHS and
4480   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4481   // larger scope than intended.
4482   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4483 
4484   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4485 }
4486 
4487 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4488                                                      unsigned Depth) {
4489   Type *SrcTy = V->getType();
4490   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4491          "Cannot truncate or zero extend with non-integer arguments!");
4492   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4493     return V;  // No conversion
4494   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4495     return getTruncateExpr(V, Ty, Depth);
4496   return getZeroExtendExpr(V, Ty, Depth);
4497 }
4498 
4499 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4500                                                      unsigned Depth) {
4501   Type *SrcTy = V->getType();
4502   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4503          "Cannot truncate or zero extend with non-integer arguments!");
4504   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4505     return V;  // No conversion
4506   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4507     return getTruncateExpr(V, Ty, Depth);
4508   return getSignExtendExpr(V, Ty, Depth);
4509 }
4510 
4511 const SCEV *
4512 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4513   Type *SrcTy = V->getType();
4514   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4515          "Cannot noop or zero extend with non-integer arguments!");
4516   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4517          "getNoopOrZeroExtend cannot truncate!");
4518   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4519     return V;  // No conversion
4520   return getZeroExtendExpr(V, Ty);
4521 }
4522 
4523 const SCEV *
4524 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4525   Type *SrcTy = V->getType();
4526   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4527          "Cannot noop or sign extend with non-integer arguments!");
4528   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4529          "getNoopOrSignExtend cannot truncate!");
4530   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4531     return V;  // No conversion
4532   return getSignExtendExpr(V, Ty);
4533 }
4534 
4535 const SCEV *
4536 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4537   Type *SrcTy = V->getType();
4538   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4539          "Cannot noop or any extend with non-integer arguments!");
4540   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4541          "getNoopOrAnyExtend cannot truncate!");
4542   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4543     return V;  // No conversion
4544   return getAnyExtendExpr(V, Ty);
4545 }
4546 
4547 const SCEV *
4548 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4549   Type *SrcTy = V->getType();
4550   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4551          "Cannot truncate or noop with non-integer arguments!");
4552   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4553          "getTruncateOrNoop cannot extend!");
4554   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4555     return V;  // No conversion
4556   return getTruncateExpr(V, Ty);
4557 }
4558 
4559 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4560                                                         const SCEV *RHS) {
4561   const SCEV *PromotedLHS = LHS;
4562   const SCEV *PromotedRHS = RHS;
4563 
4564   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4565     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4566   else
4567     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4568 
4569   return getUMaxExpr(PromotedLHS, PromotedRHS);
4570 }
4571 
4572 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4573                                                         const SCEV *RHS,
4574                                                         bool Sequential) {
4575   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4576   return getUMinFromMismatchedTypes(Ops, Sequential);
4577 }
4578 
4579 const SCEV *
4580 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4581                                             bool Sequential) {
4582   assert(!Ops.empty() && "At least one operand must be!");
4583   // Trivial case.
4584   if (Ops.size() == 1)
4585     return Ops[0];
4586 
4587   // Find the max type first.
4588   Type *MaxType = nullptr;
4589   for (auto *S : Ops)
4590     if (MaxType)
4591       MaxType = getWiderType(MaxType, S->getType());
4592     else
4593       MaxType = S->getType();
4594   assert(MaxType && "Failed to find maximum type!");
4595 
4596   // Extend all ops to max type.
4597   SmallVector<const SCEV *, 2> PromotedOps;
4598   for (auto *S : Ops)
4599     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4600 
4601   // Generate umin.
4602   return getUMinExpr(PromotedOps, Sequential);
4603 }
4604 
4605 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4606   // A pointer operand may evaluate to a nonpointer expression, such as null.
4607   if (!V->getType()->isPointerTy())
4608     return V;
4609 
4610   while (true) {
4611     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4612       V = AddRec->getStart();
4613     } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4614       const SCEV *PtrOp = nullptr;
4615       for (const SCEV *AddOp : Add->operands()) {
4616         if (AddOp->getType()->isPointerTy()) {
4617           assert(!PtrOp && "Cannot have multiple pointer ops");
4618           PtrOp = AddOp;
4619         }
4620       }
4621       assert(PtrOp && "Must have pointer op");
4622       V = PtrOp;
4623     } else // Not something we can look further into.
4624       return V;
4625   }
4626 }
4627 
4628 /// Push users of the given Instruction onto the given Worklist.
4629 static void PushDefUseChildren(Instruction *I,
4630                                SmallVectorImpl<Instruction *> &Worklist,
4631                                SmallPtrSetImpl<Instruction *> &Visited) {
4632   // Push the def-use children onto the Worklist stack.
4633   for (User *U : I->users()) {
4634     auto *UserInsn = cast<Instruction>(U);
4635     if (Visited.insert(UserInsn).second)
4636       Worklist.push_back(UserInsn);
4637   }
4638 }
4639 
4640 namespace {
4641 
4642 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4643 /// expression in case its Loop is L. If it is not L then
4644 /// if IgnoreOtherLoops is true then use AddRec itself
4645 /// otherwise rewrite cannot be done.
4646 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4647 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4648 public:
4649   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4650                              bool IgnoreOtherLoops = true) {
4651     SCEVInitRewriter Rewriter(L, SE);
4652     const SCEV *Result = Rewriter.visit(S);
4653     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4654       return SE.getCouldNotCompute();
4655     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4656                ? SE.getCouldNotCompute()
4657                : Result;
4658   }
4659 
4660   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4661     if (!SE.isLoopInvariant(Expr, L))
4662       SeenLoopVariantSCEVUnknown = true;
4663     return Expr;
4664   }
4665 
4666   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4667     // Only re-write AddRecExprs for this loop.
4668     if (Expr->getLoop() == L)
4669       return Expr->getStart();
4670     SeenOtherLoops = true;
4671     return Expr;
4672   }
4673 
4674   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4675 
4676   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4677 
4678 private:
4679   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4680       : SCEVRewriteVisitor(SE), L(L) {}
4681 
4682   const Loop *L;
4683   bool SeenLoopVariantSCEVUnknown = false;
4684   bool SeenOtherLoops = false;
4685 };
4686 
4687 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4688 /// increment expression in case its Loop is L. If it is not L then
4689 /// use AddRec itself.
4690 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4691 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4692 public:
4693   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4694     SCEVPostIncRewriter Rewriter(L, SE);
4695     const SCEV *Result = Rewriter.visit(S);
4696     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4697         ? SE.getCouldNotCompute()
4698         : Result;
4699   }
4700 
4701   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4702     if (!SE.isLoopInvariant(Expr, L))
4703       SeenLoopVariantSCEVUnknown = true;
4704     return Expr;
4705   }
4706 
4707   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4708     // Only re-write AddRecExprs for this loop.
4709     if (Expr->getLoop() == L)
4710       return Expr->getPostIncExpr(SE);
4711     SeenOtherLoops = true;
4712     return Expr;
4713   }
4714 
4715   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4716 
4717   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4718 
4719 private:
4720   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4721       : SCEVRewriteVisitor(SE), L(L) {}
4722 
4723   const Loop *L;
4724   bool SeenLoopVariantSCEVUnknown = false;
4725   bool SeenOtherLoops = false;
4726 };
4727 
4728 /// This class evaluates the compare condition by matching it against the
4729 /// condition of loop latch. If there is a match we assume a true value
4730 /// for the condition while building SCEV nodes.
4731 class SCEVBackedgeConditionFolder
4732     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4733 public:
4734   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4735                              ScalarEvolution &SE) {
4736     bool IsPosBECond = false;
4737     Value *BECond = nullptr;
4738     if (BasicBlock *Latch = L->getLoopLatch()) {
4739       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4740       if (BI && BI->isConditional()) {
4741         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4742                "Both outgoing branches should not target same header!");
4743         BECond = BI->getCondition();
4744         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4745       } else {
4746         return S;
4747       }
4748     }
4749     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4750     return Rewriter.visit(S);
4751   }
4752 
4753   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4754     const SCEV *Result = Expr;
4755     bool InvariantF = SE.isLoopInvariant(Expr, L);
4756 
4757     if (!InvariantF) {
4758       Instruction *I = cast<Instruction>(Expr->getValue());
4759       switch (I->getOpcode()) {
4760       case Instruction::Select: {
4761         SelectInst *SI = cast<SelectInst>(I);
4762         Optional<const SCEV *> Res =
4763             compareWithBackedgeCondition(SI->getCondition());
4764         if (Res.hasValue()) {
4765           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4766           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4767         }
4768         break;
4769       }
4770       default: {
4771         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4772         if (Res.hasValue())
4773           Result = Res.getValue();
4774         break;
4775       }
4776       }
4777     }
4778     return Result;
4779   }
4780 
4781 private:
4782   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4783                                        bool IsPosBECond, ScalarEvolution &SE)
4784       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4785         IsPositiveBECond(IsPosBECond) {}
4786 
4787   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4788 
4789   const Loop *L;
4790   /// Loop back condition.
4791   Value *BackedgeCond = nullptr;
4792   /// Set to true if loop back is on positive branch condition.
4793   bool IsPositiveBECond;
4794 };
4795 
4796 Optional<const SCEV *>
4797 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4798 
4799   // If value matches the backedge condition for loop latch,
4800   // then return a constant evolution node based on loopback
4801   // branch taken.
4802   if (BackedgeCond == IC)
4803     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4804                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4805   return None;
4806 }
4807 
4808 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4809 public:
4810   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4811                              ScalarEvolution &SE) {
4812     SCEVShiftRewriter Rewriter(L, SE);
4813     const SCEV *Result = Rewriter.visit(S);
4814     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4815   }
4816 
4817   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4818     // Only allow AddRecExprs for this loop.
4819     if (!SE.isLoopInvariant(Expr, L))
4820       Valid = false;
4821     return Expr;
4822   }
4823 
4824   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4825     if (Expr->getLoop() == L && Expr->isAffine())
4826       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4827     Valid = false;
4828     return Expr;
4829   }
4830 
4831   bool isValid() { return Valid; }
4832 
4833 private:
4834   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4835       : SCEVRewriteVisitor(SE), L(L) {}
4836 
4837   const Loop *L;
4838   bool Valid = true;
4839 };
4840 
4841 } // end anonymous namespace
4842 
4843 SCEV::NoWrapFlags
4844 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4845   if (!AR->isAffine())
4846     return SCEV::FlagAnyWrap;
4847 
4848   using OBO = OverflowingBinaryOperator;
4849 
4850   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4851 
4852   if (!AR->hasNoSignedWrap()) {
4853     ConstantRange AddRecRange = getSignedRange(AR);
4854     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4855 
4856     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4857         Instruction::Add, IncRange, OBO::NoSignedWrap);
4858     if (NSWRegion.contains(AddRecRange))
4859       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4860   }
4861 
4862   if (!AR->hasNoUnsignedWrap()) {
4863     ConstantRange AddRecRange = getUnsignedRange(AR);
4864     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4865 
4866     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4867         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4868     if (NUWRegion.contains(AddRecRange))
4869       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4870   }
4871 
4872   return Result;
4873 }
4874 
4875 SCEV::NoWrapFlags
4876 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4877   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4878 
4879   if (AR->hasNoSignedWrap())
4880     return Result;
4881 
4882   if (!AR->isAffine())
4883     return Result;
4884 
4885   const SCEV *Step = AR->getStepRecurrence(*this);
4886   const Loop *L = AR->getLoop();
4887 
4888   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4889   // Note that this serves two purposes: It filters out loops that are
4890   // simply not analyzable, and it covers the case where this code is
4891   // being called from within backedge-taken count analysis, such that
4892   // attempting to ask for the backedge-taken count would likely result
4893   // in infinite recursion. In the later case, the analysis code will
4894   // cope with a conservative value, and it will take care to purge
4895   // that value once it has finished.
4896   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4897 
4898   // Normally, in the cases we can prove no-overflow via a
4899   // backedge guarding condition, we can also compute a backedge
4900   // taken count for the loop.  The exceptions are assumptions and
4901   // guards present in the loop -- SCEV is not great at exploiting
4902   // these to compute max backedge taken counts, but can still use
4903   // these to prove lack of overflow.  Use this fact to avoid
4904   // doing extra work that may not pay off.
4905 
4906   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4907       AC.assumptions().empty())
4908     return Result;
4909 
4910   // If the backedge is guarded by a comparison with the pre-inc  value the
4911   // addrec is safe. Also, if the entry is guarded by a comparison with the
4912   // start value and the backedge is guarded by a comparison with the post-inc
4913   // value, the addrec is safe.
4914   ICmpInst::Predicate Pred;
4915   const SCEV *OverflowLimit =
4916     getSignedOverflowLimitForStep(Step, &Pred, this);
4917   if (OverflowLimit &&
4918       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4919        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4920     Result = setFlags(Result, SCEV::FlagNSW);
4921   }
4922   return Result;
4923 }
4924 SCEV::NoWrapFlags
4925 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4926   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4927 
4928   if (AR->hasNoUnsignedWrap())
4929     return Result;
4930 
4931   if (!AR->isAffine())
4932     return Result;
4933 
4934   const SCEV *Step = AR->getStepRecurrence(*this);
4935   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4936   const Loop *L = AR->getLoop();
4937 
4938   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4939   // Note that this serves two purposes: It filters out loops that are
4940   // simply not analyzable, and it covers the case where this code is
4941   // being called from within backedge-taken count analysis, such that
4942   // attempting to ask for the backedge-taken count would likely result
4943   // in infinite recursion. In the later case, the analysis code will
4944   // cope with a conservative value, and it will take care to purge
4945   // that value once it has finished.
4946   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4947 
4948   // Normally, in the cases we can prove no-overflow via a
4949   // backedge guarding condition, we can also compute a backedge
4950   // taken count for the loop.  The exceptions are assumptions and
4951   // guards present in the loop -- SCEV is not great at exploiting
4952   // these to compute max backedge taken counts, but can still use
4953   // these to prove lack of overflow.  Use this fact to avoid
4954   // doing extra work that may not pay off.
4955 
4956   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4957       AC.assumptions().empty())
4958     return Result;
4959 
4960   // If the backedge is guarded by a comparison with the pre-inc  value the
4961   // addrec is safe. Also, if the entry is guarded by a comparison with the
4962   // start value and the backedge is guarded by a comparison with the post-inc
4963   // value, the addrec is safe.
4964   if (isKnownPositive(Step)) {
4965     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4966                                 getUnsignedRangeMax(Step));
4967     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4968         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4969       Result = setFlags(Result, SCEV::FlagNUW);
4970     }
4971   }
4972 
4973   return Result;
4974 }
4975 
4976 namespace {
4977 
4978 /// Represents an abstract binary operation.  This may exist as a
4979 /// normal instruction or constant expression, or may have been
4980 /// derived from an expression tree.
4981 struct BinaryOp {
4982   unsigned Opcode;
4983   Value *LHS;
4984   Value *RHS;
4985   bool IsNSW = false;
4986   bool IsNUW = false;
4987 
4988   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4989   /// constant expression.
4990   Operator *Op = nullptr;
4991 
4992   explicit BinaryOp(Operator *Op)
4993       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4994         Op(Op) {
4995     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4996       IsNSW = OBO->hasNoSignedWrap();
4997       IsNUW = OBO->hasNoUnsignedWrap();
4998     }
4999   }
5000 
5001   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5002                     bool IsNUW = false)
5003       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5004 };
5005 
5006 } // end anonymous namespace
5007 
5008 /// Try to map \p V into a BinaryOp, and return \c None on failure.
5009 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
5010   auto *Op = dyn_cast<Operator>(V);
5011   if (!Op)
5012     return None;
5013 
5014   // Implementation detail: all the cleverness here should happen without
5015   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5016   // SCEV expressions when possible, and we should not break that.
5017 
5018   switch (Op->getOpcode()) {
5019   case Instruction::Add:
5020   case Instruction::Sub:
5021   case Instruction::Mul:
5022   case Instruction::UDiv:
5023   case Instruction::URem:
5024   case Instruction::And:
5025   case Instruction::Or:
5026   case Instruction::AShr:
5027   case Instruction::Shl:
5028     return BinaryOp(Op);
5029 
5030   case Instruction::Xor:
5031     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5032       // If the RHS of the xor is a signmask, then this is just an add.
5033       // Instcombine turns add of signmask into xor as a strength reduction step.
5034       if (RHSC->getValue().isSignMask())
5035         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5036     // Binary `xor` is a bit-wise `add`.
5037     if (V->getType()->isIntegerTy(1))
5038       return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5039     return BinaryOp(Op);
5040 
5041   case Instruction::LShr:
5042     // Turn logical shift right of a constant into a unsigned divide.
5043     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5044       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5045 
5046       // If the shift count is not less than the bitwidth, the result of
5047       // the shift is undefined. Don't try to analyze it, because the
5048       // resolution chosen here may differ from the resolution chosen in
5049       // other parts of the compiler.
5050       if (SA->getValue().ult(BitWidth)) {
5051         Constant *X =
5052             ConstantInt::get(SA->getContext(),
5053                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5054         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5055       }
5056     }
5057     return BinaryOp(Op);
5058 
5059   case Instruction::ExtractValue: {
5060     auto *EVI = cast<ExtractValueInst>(Op);
5061     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5062       break;
5063 
5064     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5065     if (!WO)
5066       break;
5067 
5068     Instruction::BinaryOps BinOp = WO->getBinaryOp();
5069     bool Signed = WO->isSigned();
5070     // TODO: Should add nuw/nsw flags for mul as well.
5071     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5072       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5073 
5074     // Now that we know that all uses of the arithmetic-result component of
5075     // CI are guarded by the overflow check, we can go ahead and pretend
5076     // that the arithmetic is non-overflowing.
5077     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5078                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5079   }
5080 
5081   default:
5082     break;
5083   }
5084 
5085   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5086   // semantics as a Sub, return a binary sub expression.
5087   if (auto *II = dyn_cast<IntrinsicInst>(V))
5088     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5089       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5090 
5091   return None;
5092 }
5093 
5094 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5095 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5096 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5097 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5098 /// follows one of the following patterns:
5099 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5100 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5101 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5102 /// we return the type of the truncation operation, and indicate whether the
5103 /// truncated type should be treated as signed/unsigned by setting
5104 /// \p Signed to true/false, respectively.
5105 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5106                                bool &Signed, ScalarEvolution &SE) {
5107   // The case where Op == SymbolicPHI (that is, with no type conversions on
5108   // the way) is handled by the regular add recurrence creating logic and
5109   // would have already been triggered in createAddRecForPHI. Reaching it here
5110   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5111   // because one of the other operands of the SCEVAddExpr updating this PHI is
5112   // not invariant).
5113   //
5114   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5115   // this case predicates that allow us to prove that Op == SymbolicPHI will
5116   // be added.
5117   if (Op == SymbolicPHI)
5118     return nullptr;
5119 
5120   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5121   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5122   if (SourceBits != NewBits)
5123     return nullptr;
5124 
5125   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5126   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5127   if (!SExt && !ZExt)
5128     return nullptr;
5129   const SCEVTruncateExpr *Trunc =
5130       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5131            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5132   if (!Trunc)
5133     return nullptr;
5134   const SCEV *X = Trunc->getOperand();
5135   if (X != SymbolicPHI)
5136     return nullptr;
5137   Signed = SExt != nullptr;
5138   return Trunc->getType();
5139 }
5140 
5141 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5142   if (!PN->getType()->isIntegerTy())
5143     return nullptr;
5144   const Loop *L = LI.getLoopFor(PN->getParent());
5145   if (!L || L->getHeader() != PN->getParent())
5146     return nullptr;
5147   return L;
5148 }
5149 
5150 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5151 // computation that updates the phi follows the following pattern:
5152 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5153 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5154 // If so, try to see if it can be rewritten as an AddRecExpr under some
5155 // Predicates. If successful, return them as a pair. Also cache the results
5156 // of the analysis.
5157 //
5158 // Example usage scenario:
5159 //    Say the Rewriter is called for the following SCEV:
5160 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5161 //    where:
5162 //         %X = phi i64 (%Start, %BEValue)
5163 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5164 //    and call this function with %SymbolicPHI = %X.
5165 //
5166 //    The analysis will find that the value coming around the backedge has
5167 //    the following SCEV:
5168 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5169 //    Upon concluding that this matches the desired pattern, the function
5170 //    will return the pair {NewAddRec, SmallPredsVec} where:
5171 //         NewAddRec = {%Start,+,%Step}
5172 //         SmallPredsVec = {P1, P2, P3} as follows:
5173 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5174 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5175 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5176 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5177 //    under the predicates {P1,P2,P3}.
5178 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
5179 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5180 //
5181 // TODO's:
5182 //
5183 // 1) Extend the Induction descriptor to also support inductions that involve
5184 //    casts: When needed (namely, when we are called in the context of the
5185 //    vectorizer induction analysis), a Set of cast instructions will be
5186 //    populated by this method, and provided back to isInductionPHI. This is
5187 //    needed to allow the vectorizer to properly record them to be ignored by
5188 //    the cost model and to avoid vectorizing them (otherwise these casts,
5189 //    which are redundant under the runtime overflow checks, will be
5190 //    vectorized, which can be costly).
5191 //
5192 // 2) Support additional induction/PHISCEV patterns: We also want to support
5193 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
5194 //    after the induction update operation (the induction increment):
5195 //
5196 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5197 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
5198 //
5199 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5200 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
5201 //
5202 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5203 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5204 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5205   SmallVector<const SCEVPredicate *, 3> Predicates;
5206 
5207   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5208   // return an AddRec expression under some predicate.
5209 
5210   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5211   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5212   assert(L && "Expecting an integer loop header phi");
5213 
5214   // The loop may have multiple entrances or multiple exits; we can analyze
5215   // this phi as an addrec if it has a unique entry value and a unique
5216   // backedge value.
5217   Value *BEValueV = nullptr, *StartValueV = nullptr;
5218   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5219     Value *V = PN->getIncomingValue(i);
5220     if (L->contains(PN->getIncomingBlock(i))) {
5221       if (!BEValueV) {
5222         BEValueV = V;
5223       } else if (BEValueV != V) {
5224         BEValueV = nullptr;
5225         break;
5226       }
5227     } else if (!StartValueV) {
5228       StartValueV = V;
5229     } else if (StartValueV != V) {
5230       StartValueV = nullptr;
5231       break;
5232     }
5233   }
5234   if (!BEValueV || !StartValueV)
5235     return None;
5236 
5237   const SCEV *BEValue = getSCEV(BEValueV);
5238 
5239   // If the value coming around the backedge is an add with the symbolic
5240   // value we just inserted, possibly with casts that we can ignore under
5241   // an appropriate runtime guard, then we found a simple induction variable!
5242   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5243   if (!Add)
5244     return None;
5245 
5246   // If there is a single occurrence of the symbolic value, possibly
5247   // casted, replace it with a recurrence.
5248   unsigned FoundIndex = Add->getNumOperands();
5249   Type *TruncTy = nullptr;
5250   bool Signed;
5251   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5252     if ((TruncTy =
5253              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5254       if (FoundIndex == e) {
5255         FoundIndex = i;
5256         break;
5257       }
5258 
5259   if (FoundIndex == Add->getNumOperands())
5260     return None;
5261 
5262   // Create an add with everything but the specified operand.
5263   SmallVector<const SCEV *, 8> Ops;
5264   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5265     if (i != FoundIndex)
5266       Ops.push_back(Add->getOperand(i));
5267   const SCEV *Accum = getAddExpr(Ops);
5268 
5269   // The runtime checks will not be valid if the step amount is
5270   // varying inside the loop.
5271   if (!isLoopInvariant(Accum, L))
5272     return None;
5273 
5274   // *** Part2: Create the predicates
5275 
5276   // Analysis was successful: we have a phi-with-cast pattern for which we
5277   // can return an AddRec expression under the following predicates:
5278   //
5279   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5280   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
5281   // P2: An Equal predicate that guarantees that
5282   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5283   // P3: An Equal predicate that guarantees that
5284   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5285   //
5286   // As we next prove, the above predicates guarantee that:
5287   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5288   //
5289   //
5290   // More formally, we want to prove that:
5291   //     Expr(i+1) = Start + (i+1) * Accum
5292   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5293   //
5294   // Given that:
5295   // 1) Expr(0) = Start
5296   // 2) Expr(1) = Start + Accum
5297   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5298   // 3) Induction hypothesis (step i):
5299   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5300   //
5301   // Proof:
5302   //  Expr(i+1) =
5303   //   = Start + (i+1)*Accum
5304   //   = (Start + i*Accum) + Accum
5305   //   = Expr(i) + Accum
5306   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5307   //                                                             :: from step i
5308   //
5309   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5310   //
5311   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5312   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
5313   //     + Accum                                                     :: from P3
5314   //
5315   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5316   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5317   //
5318   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5319   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5320   //
5321   // By induction, the same applies to all iterations 1<=i<n:
5322   //
5323 
5324   // Create a truncated addrec for which we will add a no overflow check (P1).
5325   const SCEV *StartVal = getSCEV(StartValueV);
5326   const SCEV *PHISCEV =
5327       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5328                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5329 
5330   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5331   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5332   // will be constant.
5333   //
5334   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5335   // add P1.
5336   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5337     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5338         Signed ? SCEVWrapPredicate::IncrementNSSW
5339                : SCEVWrapPredicate::IncrementNUSW;
5340     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5341     Predicates.push_back(AddRecPred);
5342   }
5343 
5344   // Create the Equal Predicates P2,P3:
5345 
5346   // It is possible that the predicates P2 and/or P3 are computable at
5347   // compile time due to StartVal and/or Accum being constants.
5348   // If either one is, then we can check that now and escape if either P2
5349   // or P3 is false.
5350 
5351   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5352   // for each of StartVal and Accum
5353   auto getExtendedExpr = [&](const SCEV *Expr,
5354                              bool CreateSignExtend) -> const SCEV * {
5355     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5356     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5357     const SCEV *ExtendedExpr =
5358         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5359                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5360     return ExtendedExpr;
5361   };
5362 
5363   // Given:
5364   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5365   //               = getExtendedExpr(Expr)
5366   // Determine whether the predicate P: Expr == ExtendedExpr
5367   // is known to be false at compile time
5368   auto PredIsKnownFalse = [&](const SCEV *Expr,
5369                               const SCEV *ExtendedExpr) -> bool {
5370     return Expr != ExtendedExpr &&
5371            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5372   };
5373 
5374   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5375   if (PredIsKnownFalse(StartVal, StartExtended)) {
5376     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5377     return None;
5378   }
5379 
5380   // The Step is always Signed (because the overflow checks are either
5381   // NSSW or NUSW)
5382   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5383   if (PredIsKnownFalse(Accum, AccumExtended)) {
5384     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5385     return None;
5386   }
5387 
5388   auto AppendPredicate = [&](const SCEV *Expr,
5389                              const SCEV *ExtendedExpr) -> void {
5390     if (Expr != ExtendedExpr &&
5391         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5392       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5393       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5394       Predicates.push_back(Pred);
5395     }
5396   };
5397 
5398   AppendPredicate(StartVal, StartExtended);
5399   AppendPredicate(Accum, AccumExtended);
5400 
5401   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5402   // which the casts had been folded away. The caller can rewrite SymbolicPHI
5403   // into NewAR if it will also add the runtime overflow checks specified in
5404   // Predicates.
5405   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5406 
5407   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5408       std::make_pair(NewAR, Predicates);
5409   // Remember the result of the analysis for this SCEV at this locayyytion.
5410   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5411   return PredRewrite;
5412 }
5413 
5414 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5415 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5416   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5417   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5418   if (!L)
5419     return None;
5420 
5421   // Check to see if we already analyzed this PHI.
5422   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5423   if (I != PredicatedSCEVRewrites.end()) {
5424     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5425         I->second;
5426     // Analysis was done before and failed to create an AddRec:
5427     if (Rewrite.first == SymbolicPHI)
5428       return None;
5429     // Analysis was done before and succeeded to create an AddRec under
5430     // a predicate:
5431     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5432     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5433     return Rewrite;
5434   }
5435 
5436   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5437     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5438 
5439   // Record in the cache that the analysis failed
5440   if (!Rewrite) {
5441     SmallVector<const SCEVPredicate *, 3> Predicates;
5442     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5443     return None;
5444   }
5445 
5446   return Rewrite;
5447 }
5448 
5449 // FIXME: This utility is currently required because the Rewriter currently
5450 // does not rewrite this expression:
5451 // {0, +, (sext ix (trunc iy to ix) to iy)}
5452 // into {0, +, %step},
5453 // even when the following Equal predicate exists:
5454 // "%step == (sext ix (trunc iy to ix) to iy)".
5455 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5456     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5457   if (AR1 == AR2)
5458     return true;
5459 
5460   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5461     if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5462         !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5463       return false;
5464     return true;
5465   };
5466 
5467   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5468       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5469     return false;
5470   return true;
5471 }
5472 
5473 /// A helper function for createAddRecFromPHI to handle simple cases.
5474 ///
5475 /// This function tries to find an AddRec expression for the simplest (yet most
5476 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5477 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5478 /// technique for finding the AddRec expression.
5479 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5480                                                       Value *BEValueV,
5481                                                       Value *StartValueV) {
5482   const Loop *L = LI.getLoopFor(PN->getParent());
5483   assert(L && L->getHeader() == PN->getParent());
5484   assert(BEValueV && StartValueV);
5485 
5486   auto BO = MatchBinaryOp(BEValueV, DT);
5487   if (!BO)
5488     return nullptr;
5489 
5490   if (BO->Opcode != Instruction::Add)
5491     return nullptr;
5492 
5493   const SCEV *Accum = nullptr;
5494   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5495     Accum = getSCEV(BO->RHS);
5496   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5497     Accum = getSCEV(BO->LHS);
5498 
5499   if (!Accum)
5500     return nullptr;
5501 
5502   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5503   if (BO->IsNUW)
5504     Flags = setFlags(Flags, SCEV::FlagNUW);
5505   if (BO->IsNSW)
5506     Flags = setFlags(Flags, SCEV::FlagNSW);
5507 
5508   const SCEV *StartVal = getSCEV(StartValueV);
5509   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5510   insertValueToMap(PN, PHISCEV);
5511 
5512   // We can add Flags to the post-inc expression only if we
5513   // know that it is *undefined behavior* for BEValueV to
5514   // overflow.
5515   if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5516     assert(isLoopInvariant(Accum, L) &&
5517            "Accum is defined outside L, but is not invariant?");
5518     if (isAddRecNeverPoison(BEInst, L))
5519       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5520   }
5521 
5522   return PHISCEV;
5523 }
5524 
5525 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5526   const Loop *L = LI.getLoopFor(PN->getParent());
5527   if (!L || L->getHeader() != PN->getParent())
5528     return nullptr;
5529 
5530   // The loop may have multiple entrances or multiple exits; we can analyze
5531   // this phi as an addrec if it has a unique entry value and a unique
5532   // backedge value.
5533   Value *BEValueV = nullptr, *StartValueV = nullptr;
5534   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5535     Value *V = PN->getIncomingValue(i);
5536     if (L->contains(PN->getIncomingBlock(i))) {
5537       if (!BEValueV) {
5538         BEValueV = V;
5539       } else if (BEValueV != V) {
5540         BEValueV = nullptr;
5541         break;
5542       }
5543     } else if (!StartValueV) {
5544       StartValueV = V;
5545     } else if (StartValueV != V) {
5546       StartValueV = nullptr;
5547       break;
5548     }
5549   }
5550   if (!BEValueV || !StartValueV)
5551     return nullptr;
5552 
5553   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5554          "PHI node already processed?");
5555 
5556   // First, try to find AddRec expression without creating a fictituos symbolic
5557   // value for PN.
5558   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5559     return S;
5560 
5561   // Handle PHI node value symbolically.
5562   const SCEV *SymbolicName = getUnknown(PN);
5563   insertValueToMap(PN, SymbolicName);
5564 
5565   // Using this symbolic name for the PHI, analyze the value coming around
5566   // the back-edge.
5567   const SCEV *BEValue = getSCEV(BEValueV);
5568 
5569   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5570   // has a special value for the first iteration of the loop.
5571 
5572   // If the value coming around the backedge is an add with the symbolic
5573   // value we just inserted, then we found a simple induction variable!
5574   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5575     // If there is a single occurrence of the symbolic value, replace it
5576     // with a recurrence.
5577     unsigned FoundIndex = Add->getNumOperands();
5578     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5579       if (Add->getOperand(i) == SymbolicName)
5580         if (FoundIndex == e) {
5581           FoundIndex = i;
5582           break;
5583         }
5584 
5585     if (FoundIndex != Add->getNumOperands()) {
5586       // Create an add with everything but the specified operand.
5587       SmallVector<const SCEV *, 8> Ops;
5588       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5589         if (i != FoundIndex)
5590           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5591                                                              L, *this));
5592       const SCEV *Accum = getAddExpr(Ops);
5593 
5594       // This is not a valid addrec if the step amount is varying each
5595       // loop iteration, but is not itself an addrec in this loop.
5596       if (isLoopInvariant(Accum, L) ||
5597           (isa<SCEVAddRecExpr>(Accum) &&
5598            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5599         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5600 
5601         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5602           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5603             if (BO->IsNUW)
5604               Flags = setFlags(Flags, SCEV::FlagNUW);
5605             if (BO->IsNSW)
5606               Flags = setFlags(Flags, SCEV::FlagNSW);
5607           }
5608         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5609           // If the increment is an inbounds GEP, then we know the address
5610           // space cannot be wrapped around. We cannot make any guarantee
5611           // about signed or unsigned overflow because pointers are
5612           // unsigned but we may have a negative index from the base
5613           // pointer. We can guarantee that no unsigned wrap occurs if the
5614           // indices form a positive value.
5615           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5616             Flags = setFlags(Flags, SCEV::FlagNW);
5617 
5618             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5619             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5620               Flags = setFlags(Flags, SCEV::FlagNUW);
5621           }
5622 
5623           // We cannot transfer nuw and nsw flags from subtraction
5624           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5625           // for instance.
5626         }
5627 
5628         const SCEV *StartVal = getSCEV(StartValueV);
5629         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5630 
5631         // Okay, for the entire analysis of this edge we assumed the PHI
5632         // to be symbolic.  We now need to go back and purge all of the
5633         // entries for the scalars that use the symbolic expression.
5634         forgetMemoizedResults(SymbolicName);
5635         insertValueToMap(PN, PHISCEV);
5636 
5637         // We can add Flags to the post-inc expression only if we
5638         // know that it is *undefined behavior* for BEValueV to
5639         // overflow.
5640         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5641           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5642             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5643 
5644         return PHISCEV;
5645       }
5646     }
5647   } else {
5648     // Otherwise, this could be a loop like this:
5649     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5650     // In this case, j = {1,+,1}  and BEValue is j.
5651     // Because the other in-value of i (0) fits the evolution of BEValue
5652     // i really is an addrec evolution.
5653     //
5654     // We can generalize this saying that i is the shifted value of BEValue
5655     // by one iteration:
5656     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5657     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5658     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5659     if (Shifted != getCouldNotCompute() &&
5660         Start != getCouldNotCompute()) {
5661       const SCEV *StartVal = getSCEV(StartValueV);
5662       if (Start == StartVal) {
5663         // Okay, for the entire analysis of this edge we assumed the PHI
5664         // to be symbolic.  We now need to go back and purge all of the
5665         // entries for the scalars that use the symbolic expression.
5666         forgetMemoizedResults(SymbolicName);
5667         insertValueToMap(PN, Shifted);
5668         return Shifted;
5669       }
5670     }
5671   }
5672 
5673   // Remove the temporary PHI node SCEV that has been inserted while intending
5674   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5675   // as it will prevent later (possibly simpler) SCEV expressions to be added
5676   // to the ValueExprMap.
5677   eraseValueFromMap(PN);
5678 
5679   return nullptr;
5680 }
5681 
5682 // Checks if the SCEV S is available at BB.  S is considered available at BB
5683 // if S can be materialized at BB without introducing a fault.
5684 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5685                                BasicBlock *BB) {
5686   struct CheckAvailable {
5687     bool TraversalDone = false;
5688     bool Available = true;
5689 
5690     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5691     BasicBlock *BB = nullptr;
5692     DominatorTree &DT;
5693 
5694     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5695       : L(L), BB(BB), DT(DT) {}
5696 
5697     bool setUnavailable() {
5698       TraversalDone = true;
5699       Available = false;
5700       return false;
5701     }
5702 
5703     bool follow(const SCEV *S) {
5704       switch (S->getSCEVType()) {
5705       case scConstant:
5706       case scPtrToInt:
5707       case scTruncate:
5708       case scZeroExtend:
5709       case scSignExtend:
5710       case scAddExpr:
5711       case scMulExpr:
5712       case scUMaxExpr:
5713       case scSMaxExpr:
5714       case scUMinExpr:
5715       case scSMinExpr:
5716       case scSequentialUMinExpr:
5717         // These expressions are available if their operand(s) is/are.
5718         return true;
5719 
5720       case scAddRecExpr: {
5721         // We allow add recurrences that are on the loop BB is in, or some
5722         // outer loop.  This guarantees availability because the value of the
5723         // add recurrence at BB is simply the "current" value of the induction
5724         // variable.  We can relax this in the future; for instance an add
5725         // recurrence on a sibling dominating loop is also available at BB.
5726         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5727         if (L && (ARLoop == L || ARLoop->contains(L)))
5728           return true;
5729 
5730         return setUnavailable();
5731       }
5732 
5733       case scUnknown: {
5734         // For SCEVUnknown, we check for simple dominance.
5735         const auto *SU = cast<SCEVUnknown>(S);
5736         Value *V = SU->getValue();
5737 
5738         if (isa<Argument>(V))
5739           return false;
5740 
5741         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5742           return false;
5743 
5744         return setUnavailable();
5745       }
5746 
5747       case scUDivExpr:
5748       case scCouldNotCompute:
5749         // We do not try to smart about these at all.
5750         return setUnavailable();
5751       }
5752       llvm_unreachable("Unknown SCEV kind!");
5753     }
5754 
5755     bool isDone() { return TraversalDone; }
5756   };
5757 
5758   CheckAvailable CA(L, BB, DT);
5759   SCEVTraversal<CheckAvailable> ST(CA);
5760 
5761   ST.visitAll(S);
5762   return CA.Available;
5763 }
5764 
5765 // Try to match a control flow sequence that branches out at BI and merges back
5766 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5767 // match.
5768 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5769                           Value *&C, Value *&LHS, Value *&RHS) {
5770   C = BI->getCondition();
5771 
5772   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5773   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5774 
5775   if (!LeftEdge.isSingleEdge())
5776     return false;
5777 
5778   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5779 
5780   Use &LeftUse = Merge->getOperandUse(0);
5781   Use &RightUse = Merge->getOperandUse(1);
5782 
5783   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5784     LHS = LeftUse;
5785     RHS = RightUse;
5786     return true;
5787   }
5788 
5789   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5790     LHS = RightUse;
5791     RHS = LeftUse;
5792     return true;
5793   }
5794 
5795   return false;
5796 }
5797 
5798 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5799   auto IsReachable =
5800       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5801   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5802     const Loop *L = LI.getLoopFor(PN->getParent());
5803 
5804     // We don't want to break LCSSA, even in a SCEV expression tree.
5805     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5806       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5807         return nullptr;
5808 
5809     // Try to match
5810     //
5811     //  br %cond, label %left, label %right
5812     // left:
5813     //  br label %merge
5814     // right:
5815     //  br label %merge
5816     // merge:
5817     //  V = phi [ %x, %left ], [ %y, %right ]
5818     //
5819     // as "select %cond, %x, %y"
5820 
5821     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5822     assert(IDom && "At least the entry block should dominate PN");
5823 
5824     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5825     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5826 
5827     if (BI && BI->isConditional() &&
5828         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5829         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5830         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5831       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5832   }
5833 
5834   return nullptr;
5835 }
5836 
5837 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5838   if (const SCEV *S = createAddRecFromPHI(PN))
5839     return S;
5840 
5841   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5842     return S;
5843 
5844   // If the PHI has a single incoming value, follow that value, unless the
5845   // PHI's incoming blocks are in a different loop, in which case doing so
5846   // risks breaking LCSSA form. Instcombine would normally zap these, but
5847   // it doesn't have DominatorTree information, so it may miss cases.
5848   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5849     if (LI.replacementPreservesLCSSAForm(PN, V))
5850       return getSCEV(V);
5851 
5852   // If it's not a loop phi, we can't handle it yet.
5853   return getUnknown(PN);
5854 }
5855 
5856 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5857                             SCEVTypes RootKind) {
5858   struct FindClosure {
5859     const SCEV *OperandToFind;
5860     const SCEVTypes RootKind; // Must be a sequential min/max expression.
5861     const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5862 
5863     bool Found = false;
5864 
5865     bool canRecurseInto(SCEVTypes Kind) const {
5866       // We can only recurse into the SCEV expression of the same effective type
5867       // as the type of our root SCEV expression, and into zero-extensions.
5868       return RootKind == Kind || NonSequentialRootKind == Kind ||
5869              scZeroExtend == Kind;
5870     };
5871 
5872     FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5873         : OperandToFind(OperandToFind), RootKind(RootKind),
5874           NonSequentialRootKind(
5875               SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5876                   RootKind)) {}
5877 
5878     bool follow(const SCEV *S) {
5879       Found = S == OperandToFind;
5880 
5881       return !isDone() && canRecurseInto(S->getSCEVType());
5882     }
5883 
5884     bool isDone() const { return Found; }
5885   };
5886 
5887   FindClosure FC(OperandToFind, RootKind);
5888   visitAll(Root, FC);
5889   return FC.Found;
5890 }
5891 
5892 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(
5893     Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) {
5894   // Try to match some simple smax or umax patterns.
5895   auto *ICI = Cond;
5896 
5897   Value *LHS = ICI->getOperand(0);
5898   Value *RHS = ICI->getOperand(1);
5899 
5900   switch (ICI->getPredicate()) {
5901   case ICmpInst::ICMP_SLT:
5902   case ICmpInst::ICMP_SLE:
5903   case ICmpInst::ICMP_ULT:
5904   case ICmpInst::ICMP_ULE:
5905     std::swap(LHS, RHS);
5906     LLVM_FALLTHROUGH;
5907   case ICmpInst::ICMP_SGT:
5908   case ICmpInst::ICMP_SGE:
5909   case ICmpInst::ICMP_UGT:
5910   case ICmpInst::ICMP_UGE:
5911     // a > b ? a+x : b+x  ->  max(a, b)+x
5912     // a > b ? b+x : a+x  ->  min(a, b)+x
5913     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5914       bool Signed = ICI->isSigned();
5915       const SCEV *LA = getSCEV(TrueVal);
5916       const SCEV *RA = getSCEV(FalseVal);
5917       const SCEV *LS = getSCEV(LHS);
5918       const SCEV *RS = getSCEV(RHS);
5919       if (LA->getType()->isPointerTy()) {
5920         // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5921         // Need to make sure we can't produce weird expressions involving
5922         // negated pointers.
5923         if (LA == LS && RA == RS)
5924           return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5925         if (LA == RS && RA == LS)
5926           return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5927       }
5928       auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
5929         if (Op->getType()->isPointerTy()) {
5930           Op = getLosslessPtrToIntExpr(Op);
5931           if (isa<SCEVCouldNotCompute>(Op))
5932             return Op;
5933         }
5934         if (Signed)
5935           Op = getNoopOrSignExtend(Op, I->getType());
5936         else
5937           Op = getNoopOrZeroExtend(Op, I->getType());
5938         return Op;
5939       };
5940       LS = CoerceOperand(LS);
5941       RS = CoerceOperand(RS);
5942       if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
5943         break;
5944       const SCEV *LDiff = getMinusSCEV(LA, LS);
5945       const SCEV *RDiff = getMinusSCEV(RA, RS);
5946       if (LDiff == RDiff)
5947         return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
5948                           LDiff);
5949       LDiff = getMinusSCEV(LA, RS);
5950       RDiff = getMinusSCEV(RA, LS);
5951       if (LDiff == RDiff)
5952         return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
5953                           LDiff);
5954     }
5955     break;
5956   case ICmpInst::ICMP_NE:
5957     // x != 0 ? x+y : C+y  ->  x == 0 ? C+y : x+y
5958     std::swap(TrueVal, FalseVal);
5959     LLVM_FALLTHROUGH;
5960   case ICmpInst::ICMP_EQ:
5961     // x == 0 ? C+y : x+y  ->  umax(x, C)+y   iff C u<= 1
5962     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5963         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5964       const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5965       const SCEV *TrueValExpr = getSCEV(TrueVal);    // C+y
5966       const SCEV *FalseValExpr = getSCEV(FalseVal);  // x+y
5967       const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
5968       const SCEV *C = getMinusSCEV(TrueValExpr, Y);  // C = (C+y)-y
5969       if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
5970         return getAddExpr(getUMaxExpr(X, C), Y);
5971     }
5972     // x == 0 ? 0 : umin    (..., x, ...)  ->  umin_seq(x, umin    (...))
5973     // x == 0 ? 0 : umin_seq(..., x, ...)  ->  umin_seq(x, umin_seq(...))
5974     // x == 0 ? 0 : umin    (..., umin_seq(..., x, ...), ...)
5975     //                    ->  umin_seq(x, umin (..., umin_seq(...), ...))
5976     if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
5977         isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
5978       const SCEV *X = getSCEV(LHS);
5979       while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
5980         X = ZExt->getOperand();
5981       if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) {
5982         const SCEV *FalseValExpr = getSCEV(FalseVal);
5983         if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
5984           return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr,
5985                              /*Sequential=*/true);
5986       }
5987     }
5988     break;
5989   default:
5990     break;
5991   }
5992 
5993   return getUnknown(I);
5994 }
5995 
5996 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
5997     Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
5998   // For now, only deal with i1-typed `select`s.
5999   if (!V->getType()->isIntegerTy(1) || !Cond->getType()->isIntegerTy(1) ||
6000       !TrueVal->getType()->isIntegerTy(1) ||
6001       !FalseVal->getType()->isIntegerTy(1))
6002     return getUnknown(V);
6003 
6004   // i1 cond ? i1 x : i1 C  -->  C + (i1  cond ? (i1 x - i1 C) : i1 0)
6005   //                        -->  C + (umin_seq  cond, x - C)
6006   //
6007   // i1 cond ? i1 C : i1 x  -->  C + (i1  cond ? i1 0 : (i1 x - i1 C))
6008   //                        -->  C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6009   //                        -->  C + (umin_seq ~cond, x - C)
6010   if (isa<ConstantInt>(TrueVal) || isa<ConstantInt>(FalseVal)) {
6011     const SCEV *CondExpr = getSCEV(Cond);
6012     const SCEV *TrueExpr = getSCEV(TrueVal);
6013     const SCEV *FalseExpr = getSCEV(FalseVal);
6014     const SCEV *X, *C;
6015     if (isa<ConstantInt>(TrueVal)) {
6016       CondExpr = getNotSCEV(CondExpr);
6017       X = FalseExpr;
6018       C = TrueExpr;
6019     } else {
6020       X = TrueExpr;
6021       C = FalseExpr;
6022     }
6023     return getAddExpr(
6024         C, getUMinExpr(CondExpr, getMinusSCEV(X, C), /*Sequential=*/true));
6025   }
6026 
6027   return getUnknown(V);
6028 }
6029 
6030 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6031                                                       Value *TrueVal,
6032                                                       Value *FalseVal) {
6033   // Handle "constant" branch or select. This can occur for instance when a
6034   // loop pass transforms an inner loop and moves on to process the outer loop.
6035   if (auto *CI = dyn_cast<ConstantInt>(Cond))
6036     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6037 
6038   if (auto *I = dyn_cast<Instruction>(V)) {
6039     if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6040       const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond(
6041           I, ICI, TrueVal, FalseVal);
6042       if (!isa<SCEVUnknown>(S))
6043         return S;
6044     }
6045   }
6046 
6047   return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6048 }
6049 
6050 /// Expand GEP instructions into add and multiply operations. This allows them
6051 /// to be analyzed by regular SCEV code.
6052 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6053   // Don't attempt to analyze GEPs over unsized objects.
6054   if (!GEP->getSourceElementType()->isSized())
6055     return getUnknown(GEP);
6056 
6057   SmallVector<const SCEV *, 4> IndexExprs;
6058   for (Value *Index : GEP->indices())
6059     IndexExprs.push_back(getSCEV(Index));
6060   return getGEPExpr(GEP, IndexExprs);
6061 }
6062 
6063 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
6064   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6065     return C->getAPInt().countTrailingZeros();
6066 
6067   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
6068     return GetMinTrailingZeros(I->getOperand());
6069 
6070   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
6071     return std::min(GetMinTrailingZeros(T->getOperand()),
6072                     (uint32_t)getTypeSizeInBits(T->getType()));
6073 
6074   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
6075     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6076     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6077                ? getTypeSizeInBits(E->getType())
6078                : OpRes;
6079   }
6080 
6081   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
6082     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6083     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6084                ? getTypeSizeInBits(E->getType())
6085                : OpRes;
6086   }
6087 
6088   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
6089     // The result is the min of all operands results.
6090     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6091     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6092       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6093     return MinOpRes;
6094   }
6095 
6096   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
6097     // The result is the sum of all operands results.
6098     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
6099     uint32_t BitWidth = getTypeSizeInBits(M->getType());
6100     for (unsigned i = 1, e = M->getNumOperands();
6101          SumOpRes != BitWidth && i != e; ++i)
6102       SumOpRes =
6103           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
6104     return SumOpRes;
6105   }
6106 
6107   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
6108     // The result is the min of all operands results.
6109     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
6110     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
6111       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
6112     return MinOpRes;
6113   }
6114 
6115   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
6116     // The result is the min of all operands results.
6117     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6118     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6119       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6120     return MinOpRes;
6121   }
6122 
6123   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
6124     // The result is the min of all operands results.
6125     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
6126     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
6127       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
6128     return MinOpRes;
6129   }
6130 
6131   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6132     // For a SCEVUnknown, ask ValueTracking.
6133     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
6134     return Known.countMinTrailingZeros();
6135   }
6136 
6137   // SCEVUDivExpr
6138   return 0;
6139 }
6140 
6141 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
6142   auto I = MinTrailingZerosCache.find(S);
6143   if (I != MinTrailingZerosCache.end())
6144     return I->second;
6145 
6146   uint32_t Result = GetMinTrailingZerosImpl(S);
6147   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
6148   assert(InsertPair.second && "Should insert a new key");
6149   return InsertPair.first->second;
6150 }
6151 
6152 /// Helper method to assign a range to V from metadata present in the IR.
6153 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6154   if (Instruction *I = dyn_cast<Instruction>(V))
6155     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6156       return getConstantRangeFromMetadata(*MD);
6157 
6158   return None;
6159 }
6160 
6161 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6162                                      SCEV::NoWrapFlags Flags) {
6163   if (AddRec->getNoWrapFlags(Flags) != Flags) {
6164     AddRec->setNoWrapFlags(Flags);
6165     UnsignedRanges.erase(AddRec);
6166     SignedRanges.erase(AddRec);
6167   }
6168 }
6169 
6170 ConstantRange ScalarEvolution::
6171 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6172   const DataLayout &DL = getDataLayout();
6173 
6174   unsigned BitWidth = getTypeSizeInBits(U->getType());
6175   const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6176 
6177   // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6178   // use information about the trip count to improve our available range.  Note
6179   // that the trip count independent cases are already handled by known bits.
6180   // WARNING: The definition of recurrence used here is subtly different than
6181   // the one used by AddRec (and thus most of this file).  Step is allowed to
6182   // be arbitrarily loop varying here, where AddRec allows only loop invariant
6183   // and other addrecs in the same loop (for non-affine addrecs).  The code
6184   // below intentionally handles the case where step is not loop invariant.
6185   auto *P = dyn_cast<PHINode>(U->getValue());
6186   if (!P)
6187     return FullSet;
6188 
6189   // Make sure that no Phi input comes from an unreachable block. Otherwise,
6190   // even the values that are not available in these blocks may come from them,
6191   // and this leads to false-positive recurrence test.
6192   for (auto *Pred : predecessors(P->getParent()))
6193     if (!DT.isReachableFromEntry(Pred))
6194       return FullSet;
6195 
6196   BinaryOperator *BO;
6197   Value *Start, *Step;
6198   if (!matchSimpleRecurrence(P, BO, Start, Step))
6199     return FullSet;
6200 
6201   // If we found a recurrence in reachable code, we must be in a loop. Note
6202   // that BO might be in some subloop of L, and that's completely okay.
6203   auto *L = LI.getLoopFor(P->getParent());
6204   assert(L && L->getHeader() == P->getParent());
6205   if (!L->contains(BO->getParent()))
6206     // NOTE: This bailout should be an assert instead.  However, asserting
6207     // the condition here exposes a case where LoopFusion is querying SCEV
6208     // with malformed loop information during the midst of the transform.
6209     // There doesn't appear to be an obvious fix, so for the moment bailout
6210     // until the caller issue can be fixed.  PR49566 tracks the bug.
6211     return FullSet;
6212 
6213   // TODO: Extend to other opcodes such as mul, and div
6214   switch (BO->getOpcode()) {
6215   default:
6216     return FullSet;
6217   case Instruction::AShr:
6218   case Instruction::LShr:
6219   case Instruction::Shl:
6220     break;
6221   };
6222 
6223   if (BO->getOperand(0) != P)
6224     // TODO: Handle the power function forms some day.
6225     return FullSet;
6226 
6227   unsigned TC = getSmallConstantMaxTripCount(L);
6228   if (!TC || TC >= BitWidth)
6229     return FullSet;
6230 
6231   auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6232   auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6233   assert(KnownStart.getBitWidth() == BitWidth &&
6234          KnownStep.getBitWidth() == BitWidth);
6235 
6236   // Compute total shift amount, being careful of overflow and bitwidths.
6237   auto MaxShiftAmt = KnownStep.getMaxValue();
6238   APInt TCAP(BitWidth, TC-1);
6239   bool Overflow = false;
6240   auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6241   if (Overflow)
6242     return FullSet;
6243 
6244   switch (BO->getOpcode()) {
6245   default:
6246     llvm_unreachable("filtered out above");
6247   case Instruction::AShr: {
6248     // For each ashr, three cases:
6249     //   shift = 0 => unchanged value
6250     //   saturation => 0 or -1
6251     //   other => a value closer to zero (of the same sign)
6252     // Thus, the end value is closer to zero than the start.
6253     auto KnownEnd = KnownBits::ashr(KnownStart,
6254                                     KnownBits::makeConstant(TotalShift));
6255     if (KnownStart.isNonNegative())
6256       // Analogous to lshr (simply not yet canonicalized)
6257       return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6258                                         KnownStart.getMaxValue() + 1);
6259     if (KnownStart.isNegative())
6260       // End >=u Start && End <=s Start
6261       return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6262                                         KnownEnd.getMaxValue() + 1);
6263     break;
6264   }
6265   case Instruction::LShr: {
6266     // For each lshr, three cases:
6267     //   shift = 0 => unchanged value
6268     //   saturation => 0
6269     //   other => a smaller positive number
6270     // Thus, the low end of the unsigned range is the last value produced.
6271     auto KnownEnd = KnownBits::lshr(KnownStart,
6272                                     KnownBits::makeConstant(TotalShift));
6273     return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6274                                       KnownStart.getMaxValue() + 1);
6275   }
6276   case Instruction::Shl: {
6277     // Iff no bits are shifted out, value increases on every shift.
6278     auto KnownEnd = KnownBits::shl(KnownStart,
6279                                    KnownBits::makeConstant(TotalShift));
6280     if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6281       return ConstantRange(KnownStart.getMinValue(),
6282                            KnownEnd.getMaxValue() + 1);
6283     break;
6284   }
6285   };
6286   return FullSet;
6287 }
6288 
6289 /// Determine the range for a particular SCEV.  If SignHint is
6290 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6291 /// with a "cleaner" unsigned (resp. signed) representation.
6292 const ConstantRange &
6293 ScalarEvolution::getRangeRef(const SCEV *S,
6294                              ScalarEvolution::RangeSignHint SignHint) {
6295   DenseMap<const SCEV *, ConstantRange> &Cache =
6296       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6297                                                        : SignedRanges;
6298   ConstantRange::PreferredRangeType RangeType =
6299       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
6300           ? ConstantRange::Unsigned : ConstantRange::Signed;
6301 
6302   // See if we've computed this range already.
6303   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6304   if (I != Cache.end())
6305     return I->second;
6306 
6307   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6308     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6309 
6310   unsigned BitWidth = getTypeSizeInBits(S->getType());
6311   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6312   using OBO = OverflowingBinaryOperator;
6313 
6314   // If the value has known zeros, the maximum value will have those known zeros
6315   // as well.
6316   uint32_t TZ = GetMinTrailingZeros(S);
6317   if (TZ != 0) {
6318     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6319       ConservativeResult =
6320           ConstantRange(APInt::getMinValue(BitWidth),
6321                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6322     else
6323       ConservativeResult = ConstantRange(
6324           APInt::getSignedMinValue(BitWidth),
6325           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6326   }
6327 
6328   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
6329     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
6330     unsigned WrapType = OBO::AnyWrap;
6331     if (Add->hasNoSignedWrap())
6332       WrapType |= OBO::NoSignedWrap;
6333     if (Add->hasNoUnsignedWrap())
6334       WrapType |= OBO::NoUnsignedWrap;
6335     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6336       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
6337                           WrapType, RangeType);
6338     return setRange(Add, SignHint,
6339                     ConservativeResult.intersectWith(X, RangeType));
6340   }
6341 
6342   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
6343     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
6344     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6345       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
6346     return setRange(Mul, SignHint,
6347                     ConservativeResult.intersectWith(X, RangeType));
6348   }
6349 
6350   if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) {
6351     Intrinsic::ID ID;
6352     switch (S->getSCEVType()) {
6353     case scUMaxExpr:
6354       ID = Intrinsic::umax;
6355       break;
6356     case scSMaxExpr:
6357       ID = Intrinsic::smax;
6358       break;
6359     case scUMinExpr:
6360     case scSequentialUMinExpr:
6361       ID = Intrinsic::umin;
6362       break;
6363     case scSMinExpr:
6364       ID = Intrinsic::smin;
6365       break;
6366     default:
6367       llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6368     }
6369 
6370     const auto *NAry = cast<SCEVNAryExpr>(S);
6371     ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint);
6372     for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6373       X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)});
6374     return setRange(S, SignHint,
6375                     ConservativeResult.intersectWith(X, RangeType));
6376   }
6377 
6378   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
6379     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
6380     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
6381     return setRange(UDiv, SignHint,
6382                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6383   }
6384 
6385   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
6386     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
6387     return setRange(ZExt, SignHint,
6388                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
6389                                                      RangeType));
6390   }
6391 
6392   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
6393     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
6394     return setRange(SExt, SignHint,
6395                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
6396                                                      RangeType));
6397   }
6398 
6399   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
6400     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
6401     return setRange(PtrToInt, SignHint, X);
6402   }
6403 
6404   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
6405     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
6406     return setRange(Trunc, SignHint,
6407                     ConservativeResult.intersectWith(X.truncate(BitWidth),
6408                                                      RangeType));
6409   }
6410 
6411   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
6412     // If there's no unsigned wrap, the value will never be less than its
6413     // initial value.
6414     if (AddRec->hasNoUnsignedWrap()) {
6415       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6416       if (!UnsignedMinValue.isZero())
6417         ConservativeResult = ConservativeResult.intersectWith(
6418             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6419     }
6420 
6421     // If there's no signed wrap, and all the operands except initial value have
6422     // the same sign or zero, the value won't ever be:
6423     // 1: smaller than initial value if operands are non negative,
6424     // 2: bigger than initial value if operands are non positive.
6425     // For both cases, value can not cross signed min/max boundary.
6426     if (AddRec->hasNoSignedWrap()) {
6427       bool AllNonNeg = true;
6428       bool AllNonPos = true;
6429       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6430         if (!isKnownNonNegative(AddRec->getOperand(i)))
6431           AllNonNeg = false;
6432         if (!isKnownNonPositive(AddRec->getOperand(i)))
6433           AllNonPos = false;
6434       }
6435       if (AllNonNeg)
6436         ConservativeResult = ConservativeResult.intersectWith(
6437             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6438                                        APInt::getSignedMinValue(BitWidth)),
6439             RangeType);
6440       else if (AllNonPos)
6441         ConservativeResult = ConservativeResult.intersectWith(
6442             ConstantRange::getNonEmpty(
6443                 APInt::getSignedMinValue(BitWidth),
6444                 getSignedRangeMax(AddRec->getStart()) + 1),
6445             RangeType);
6446     }
6447 
6448     // TODO: non-affine addrec
6449     if (AddRec->isAffine()) {
6450       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6451       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6452           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6453         auto RangeFromAffine = getRangeForAffineAR(
6454             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6455             BitWidth);
6456         ConservativeResult =
6457             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6458 
6459         auto RangeFromFactoring = getRangeViaFactoring(
6460             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6461             BitWidth);
6462         ConservativeResult =
6463             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6464       }
6465 
6466       // Now try symbolic BE count and more powerful methods.
6467       if (UseExpensiveRangeSharpening) {
6468         const SCEV *SymbolicMaxBECount =
6469             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6470         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6471             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6472             AddRec->hasNoSelfWrap()) {
6473           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6474               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6475           ConservativeResult =
6476               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6477         }
6478       }
6479     }
6480 
6481     return setRange(AddRec, SignHint, std::move(ConservativeResult));
6482   }
6483 
6484   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
6485 
6486     // Check if the IR explicitly contains !range metadata.
6487     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6488     if (MDRange.hasValue())
6489       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
6490                                                             RangeType);
6491 
6492     // Use facts about recurrences in the underlying IR.  Note that add
6493     // recurrences are AddRecExprs and thus don't hit this path.  This
6494     // primarily handles shift recurrences.
6495     auto CR = getRangeForUnknownRecurrence(U);
6496     ConservativeResult = ConservativeResult.intersectWith(CR);
6497 
6498     // See if ValueTracking can give us a useful range.
6499     const DataLayout &DL = getDataLayout();
6500     KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6501     if (Known.getBitWidth() != BitWidth)
6502       Known = Known.zextOrTrunc(BitWidth);
6503 
6504     // ValueTracking may be able to compute a tighter result for the number of
6505     // sign bits than for the value of those sign bits.
6506     unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6507     if (U->getType()->isPointerTy()) {
6508       // If the pointer size is larger than the index size type, this can cause
6509       // NS to be larger than BitWidth. So compensate for this.
6510       unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6511       int ptrIdxDiff = ptrSize - BitWidth;
6512       if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6513         NS -= ptrIdxDiff;
6514     }
6515 
6516     if (NS > 1) {
6517       // If we know any of the sign bits, we know all of the sign bits.
6518       if (!Known.Zero.getHiBits(NS).isZero())
6519         Known.Zero.setHighBits(NS);
6520       if (!Known.One.getHiBits(NS).isZero())
6521         Known.One.setHighBits(NS);
6522     }
6523 
6524     if (Known.getMinValue() != Known.getMaxValue() + 1)
6525       ConservativeResult = ConservativeResult.intersectWith(
6526           ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6527           RangeType);
6528     if (NS > 1)
6529       ConservativeResult = ConservativeResult.intersectWith(
6530           ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6531                         APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6532           RangeType);
6533 
6534     // A range of Phi is a subset of union of all ranges of its input.
6535     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue()))
6536       if (!PendingPhiRanges.count(Phi))
6537         sharpenPhiSCCRange(Phi, ConservativeResult, SignHint);
6538 
6539     return setRange(U, SignHint, std::move(ConservativeResult));
6540   }
6541 
6542   return setRange(S, SignHint, std::move(ConservativeResult));
6543 }
6544 
6545 bool ScalarEvolution::collectSCC(const PHINode *Phi,
6546                                  SmallVectorImpl<const PHINode *> &SCC) const {
6547   assert(SCC.empty() && "Precondition: SCC should be empty.");
6548   auto Bail = [&]() {
6549     SCC.clear();
6550     SCC.push_back(Phi);
6551     return false;
6552   };
6553   SmallPtrSet<const PHINode *, 4> Reachable;
6554   {
6555     // First, find all PHI nodes that are reachable from Phi.
6556     SmallVector<const PHINode *, 4> Worklist;
6557     Reachable.insert(Phi);
6558     Worklist.push_back(Phi);
6559     while (!Worklist.empty()) {
6560       if (Reachable.size() > MaxPhiSCCAnalysisSize)
6561         // Too many nodes to process. Assume that SCC is composed of Phi alone.
6562         return Bail();
6563       auto *Curr = Worklist.pop_back_val();
6564       for (auto &Op : Curr->operands()) {
6565         if (auto *PhiOp = dyn_cast<PHINode>(&*Op)) {
6566           if (PendingPhiRanges.count(PhiOp))
6567             // Do not want to deal with this situation, so conservatively bail.
6568             return Bail();
6569           if (Reachable.insert(PhiOp).second)
6570             Worklist.push_back(PhiOp);
6571         }
6572       }
6573     }
6574   }
6575   {
6576     // Out of reachable nodes, find those from which Phi is also reachable. This
6577     // defines a SCC.
6578     SmallVector<const PHINode *, 4> Worklist;
6579     SmallPtrSet<const PHINode *, 4> SCCSet;
6580     SCCSet.insert(Phi);
6581     SCC.push_back(Phi);
6582     Worklist.push_back(Phi);
6583     while (!Worklist.empty()) {
6584       auto *Curr = Worklist.pop_back_val();
6585       for (auto *User : Curr->users())
6586         if (auto *PN = dyn_cast<PHINode>(User))
6587           if (Reachable.count(PN) && SCCSet.insert(PN).second) {
6588             Worklist.push_back(PN);
6589             SCC.push_back(PN);
6590           }
6591     }
6592   }
6593   return true;
6594 }
6595 
6596 void
6597 ScalarEvolution::sharpenPhiSCCRange(const PHINode *Phi,
6598                                     ConstantRange &ConservativeResult,
6599                                     ScalarEvolution::RangeSignHint SignHint) {
6600   // Collect strongly connected component (further on - SCC ) composed of Phis.
6601   // Analyze all values that are incoming to this SCC (we call them roots).
6602   // All SCC elements have range that is not wider than union of ranges of
6603   // roots.
6604   SmallVector<const PHINode *, 8> SCC;
6605   if (collectSCC(Phi, SCC))
6606     ++NumFoundPhiSCCs;
6607 
6608   // Collect roots: inputs of SCC nodes that come from outside of SCC.
6609   SmallPtrSet<Value *, 4> Roots;
6610   const SmallPtrSet<const PHINode *, 8> SCCSet(SCC.begin(), SCC.end());
6611   for (auto *PN : SCC)
6612     for (auto &Op : PN->operands()) {
6613       auto *PhiInput = dyn_cast<PHINode>(Op);
6614       if (!PhiInput || !SCCSet.count(PhiInput))
6615         Roots.insert(Op);
6616     }
6617 
6618   // Mark SCC elements as pending to avoid infinite recursion if there is a
6619   // cyclic dependency through some instruction that is not a PHI.
6620   for (auto *PN : SCC) {
6621     bool Inserted = PendingPhiRanges.insert(PN).second;
6622     assert(Inserted && "PHI is already pending?");
6623     (void)Inserted;
6624   }
6625 
6626   auto BitWidth = ConservativeResult.getBitWidth();
6627   ConstantRange RangeFromRoots(BitWidth, /*isFullSet=*/false);
6628   for (auto *Root : Roots) {
6629     auto OpRange = getRangeRef(getSCEV(Root), SignHint);
6630     RangeFromRoots = RangeFromRoots.unionWith(OpRange);
6631     // No point to continue if we already have a full set.
6632     if (RangeFromRoots.isFullSet())
6633       break;
6634   }
6635   ConstantRange::PreferredRangeType RangeType =
6636       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6637                                                        : ConstantRange::Signed;
6638   ConservativeResult =
6639       ConservativeResult.intersectWith(RangeFromRoots, RangeType);
6640 
6641   DenseMap<const SCEV *, ConstantRange> &Cache =
6642       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6643                                                        : SignedRanges;
6644   // Entire SCC has the same range.
6645   for (auto *PN : SCC) {
6646     bool Erased = PendingPhiRanges.erase(PN);
6647     assert(Erased && "Failed to erase Phi properly?");
6648     (void)Erased;
6649     auto *PNSCEV = getSCEV(const_cast<PHINode *>(PN));
6650     auto I = Cache.find(PNSCEV);
6651     if (I == Cache.end())
6652       setRange(PNSCEV, SignHint, ConservativeResult);
6653     else {
6654       auto SharpenedRange =
6655           I->second.intersectWith(ConservativeResult, RangeType);
6656       setRange(PNSCEV, SignHint, SharpenedRange);
6657     }
6658   }
6659 }
6660 
6661 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6662 // values that the expression can take. Initially, the expression has a value
6663 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6664 // argument defines if we treat Step as signed or unsigned.
6665 static ConstantRange getRangeForAffineARHelper(APInt Step,
6666                                                const ConstantRange &StartRange,
6667                                                const APInt &MaxBECount,
6668                                                unsigned BitWidth, bool Signed) {
6669   // If either Step or MaxBECount is 0, then the expression won't change, and we
6670   // just need to return the initial range.
6671   if (Step == 0 || MaxBECount == 0)
6672     return StartRange;
6673 
6674   // If we don't know anything about the initial value (i.e. StartRange is
6675   // FullRange), then we don't know anything about the final range either.
6676   // Return FullRange.
6677   if (StartRange.isFullSet())
6678     return ConstantRange::getFull(BitWidth);
6679 
6680   // If Step is signed and negative, then we use its absolute value, but we also
6681   // note that we're moving in the opposite direction.
6682   bool Descending = Signed && Step.isNegative();
6683 
6684   if (Signed)
6685     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6686     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6687     // This equations hold true due to the well-defined wrap-around behavior of
6688     // APInt.
6689     Step = Step.abs();
6690 
6691   // Check if Offset is more than full span of BitWidth. If it is, the
6692   // expression is guaranteed to overflow.
6693   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6694     return ConstantRange::getFull(BitWidth);
6695 
6696   // Offset is by how much the expression can change. Checks above guarantee no
6697   // overflow here.
6698   APInt Offset = Step * MaxBECount;
6699 
6700   // Minimum value of the final range will match the minimal value of StartRange
6701   // if the expression is increasing and will be decreased by Offset otherwise.
6702   // Maximum value of the final range will match the maximal value of StartRange
6703   // if the expression is decreasing and will be increased by Offset otherwise.
6704   APInt StartLower = StartRange.getLower();
6705   APInt StartUpper = StartRange.getUpper() - 1;
6706   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6707                                    : (StartUpper + std::move(Offset));
6708 
6709   // It's possible that the new minimum/maximum value will fall into the initial
6710   // range (due to wrap around). This means that the expression can take any
6711   // value in this bitwidth, and we have to return full range.
6712   if (StartRange.contains(MovedBoundary))
6713     return ConstantRange::getFull(BitWidth);
6714 
6715   APInt NewLower =
6716       Descending ? std::move(MovedBoundary) : std::move(StartLower);
6717   APInt NewUpper =
6718       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6719   NewUpper += 1;
6720 
6721   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6722   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6723 }
6724 
6725 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6726                                                    const SCEV *Step,
6727                                                    const SCEV *MaxBECount,
6728                                                    unsigned BitWidth) {
6729   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6730          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6731          "Precondition!");
6732 
6733   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6734   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6735 
6736   // First, consider step signed.
6737   ConstantRange StartSRange = getSignedRange(Start);
6738   ConstantRange StepSRange = getSignedRange(Step);
6739 
6740   // If Step can be both positive and negative, we need to find ranges for the
6741   // maximum absolute step values in both directions and union them.
6742   ConstantRange SR =
6743       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6744                                 MaxBECountValue, BitWidth, /* Signed = */ true);
6745   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6746                                               StartSRange, MaxBECountValue,
6747                                               BitWidth, /* Signed = */ true));
6748 
6749   // Next, consider step unsigned.
6750   ConstantRange UR = getRangeForAffineARHelper(
6751       getUnsignedRangeMax(Step), getUnsignedRange(Start),
6752       MaxBECountValue, BitWidth, /* Signed = */ false);
6753 
6754   // Finally, intersect signed and unsigned ranges.
6755   return SR.intersectWith(UR, ConstantRange::Smallest);
6756 }
6757 
6758 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6759     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6760     ScalarEvolution::RangeSignHint SignHint) {
6761   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6762   assert(AddRec->hasNoSelfWrap() &&
6763          "This only works for non-self-wrapping AddRecs!");
6764   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6765   const SCEV *Step = AddRec->getStepRecurrence(*this);
6766   // Only deal with constant step to save compile time.
6767   if (!isa<SCEVConstant>(Step))
6768     return ConstantRange::getFull(BitWidth);
6769   // Let's make sure that we can prove that we do not self-wrap during
6770   // MaxBECount iterations. We need this because MaxBECount is a maximum
6771   // iteration count estimate, and we might infer nw from some exit for which we
6772   // do not know max exit count (or any other side reasoning).
6773   // TODO: Turn into assert at some point.
6774   if (getTypeSizeInBits(MaxBECount->getType()) >
6775       getTypeSizeInBits(AddRec->getType()))
6776     return ConstantRange::getFull(BitWidth);
6777   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6778   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6779   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6780   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6781   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6782                                          MaxItersWithoutWrap))
6783     return ConstantRange::getFull(BitWidth);
6784 
6785   ICmpInst::Predicate LEPred =
6786       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6787   ICmpInst::Predicate GEPred =
6788       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6789   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6790 
6791   // We know that there is no self-wrap. Let's take Start and End values and
6792   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6793   // the iteration. They either lie inside the range [Min(Start, End),
6794   // Max(Start, End)] or outside it:
6795   //
6796   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6797   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6798   //
6799   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6800   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6801   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6802   // Start <= End and step is positive, or Start >= End and step is negative.
6803   const SCEV *Start = AddRec->getStart();
6804   ConstantRange StartRange = getRangeRef(Start, SignHint);
6805   ConstantRange EndRange = getRangeRef(End, SignHint);
6806   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6807   // If they already cover full iteration space, we will know nothing useful
6808   // even if we prove what we want to prove.
6809   if (RangeBetween.isFullSet())
6810     return RangeBetween;
6811   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6812   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6813                                : RangeBetween.isWrappedSet();
6814   if (IsWrappedSet)
6815     return ConstantRange::getFull(BitWidth);
6816 
6817   if (isKnownPositive(Step) &&
6818       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6819     return RangeBetween;
6820   else if (isKnownNegative(Step) &&
6821            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6822     return RangeBetween;
6823   return ConstantRange::getFull(BitWidth);
6824 }
6825 
6826 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6827                                                     const SCEV *Step,
6828                                                     const SCEV *MaxBECount,
6829                                                     unsigned BitWidth) {
6830   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6831   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6832 
6833   struct SelectPattern {
6834     Value *Condition = nullptr;
6835     APInt TrueValue;
6836     APInt FalseValue;
6837 
6838     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6839                            const SCEV *S) {
6840       Optional<unsigned> CastOp;
6841       APInt Offset(BitWidth, 0);
6842 
6843       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6844              "Should be!");
6845 
6846       // Peel off a constant offset:
6847       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6848         // In the future we could consider being smarter here and handle
6849         // {Start+Step,+,Step} too.
6850         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6851           return;
6852 
6853         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6854         S = SA->getOperand(1);
6855       }
6856 
6857       // Peel off a cast operation
6858       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6859         CastOp = SCast->getSCEVType();
6860         S = SCast->getOperand();
6861       }
6862 
6863       using namespace llvm::PatternMatch;
6864 
6865       auto *SU = dyn_cast<SCEVUnknown>(S);
6866       const APInt *TrueVal, *FalseVal;
6867       if (!SU ||
6868           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6869                                           m_APInt(FalseVal)))) {
6870         Condition = nullptr;
6871         return;
6872       }
6873 
6874       TrueValue = *TrueVal;
6875       FalseValue = *FalseVal;
6876 
6877       // Re-apply the cast we peeled off earlier
6878       if (CastOp.hasValue())
6879         switch (*CastOp) {
6880         default:
6881           llvm_unreachable("Unknown SCEV cast type!");
6882 
6883         case scTruncate:
6884           TrueValue = TrueValue.trunc(BitWidth);
6885           FalseValue = FalseValue.trunc(BitWidth);
6886           break;
6887         case scZeroExtend:
6888           TrueValue = TrueValue.zext(BitWidth);
6889           FalseValue = FalseValue.zext(BitWidth);
6890           break;
6891         case scSignExtend:
6892           TrueValue = TrueValue.sext(BitWidth);
6893           FalseValue = FalseValue.sext(BitWidth);
6894           break;
6895         }
6896 
6897       // Re-apply the constant offset we peeled off earlier
6898       TrueValue += Offset;
6899       FalseValue += Offset;
6900     }
6901 
6902     bool isRecognized() { return Condition != nullptr; }
6903   };
6904 
6905   SelectPattern StartPattern(*this, BitWidth, Start);
6906   if (!StartPattern.isRecognized())
6907     return ConstantRange::getFull(BitWidth);
6908 
6909   SelectPattern StepPattern(*this, BitWidth, Step);
6910   if (!StepPattern.isRecognized())
6911     return ConstantRange::getFull(BitWidth);
6912 
6913   if (StartPattern.Condition != StepPattern.Condition) {
6914     // We don't handle this case today; but we could, by considering four
6915     // possibilities below instead of two. I'm not sure if there are cases where
6916     // that will help over what getRange already does, though.
6917     return ConstantRange::getFull(BitWidth);
6918   }
6919 
6920   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6921   // construct arbitrary general SCEV expressions here.  This function is called
6922   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6923   // say) can end up caching a suboptimal value.
6924 
6925   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6926   // C2352 and C2512 (otherwise it isn't needed).
6927 
6928   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6929   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6930   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6931   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6932 
6933   ConstantRange TrueRange =
6934       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6935   ConstantRange FalseRange =
6936       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6937 
6938   return TrueRange.unionWith(FalseRange);
6939 }
6940 
6941 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6942   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6943   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6944 
6945   // Return early if there are no flags to propagate to the SCEV.
6946   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6947   if (BinOp->hasNoUnsignedWrap())
6948     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6949   if (BinOp->hasNoSignedWrap())
6950     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6951   if (Flags == SCEV::FlagAnyWrap)
6952     return SCEV::FlagAnyWrap;
6953 
6954   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6955 }
6956 
6957 const Instruction *
6958 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
6959   if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
6960     return &*AddRec->getLoop()->getHeader()->begin();
6961   if (auto *U = dyn_cast<SCEVUnknown>(S))
6962     if (auto *I = dyn_cast<Instruction>(U->getValue()))
6963       return I;
6964   return nullptr;
6965 }
6966 
6967 /// Fills \p Ops with unique operands of \p S, if it has operands. If not,
6968 /// \p Ops remains unmodified.
6969 static void collectUniqueOps(const SCEV *S,
6970                              SmallVectorImpl<const SCEV *> &Ops) {
6971   SmallPtrSet<const SCEV *, 4> Unique;
6972   auto InsertUnique = [&](const SCEV *S) {
6973     if (Unique.insert(S).second)
6974       Ops.push_back(S);
6975   };
6976   if (auto *S2 = dyn_cast<SCEVCastExpr>(S))
6977     for (auto *Op : S2->operands())
6978       InsertUnique(Op);
6979   else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S))
6980     for (auto *Op : S2->operands())
6981       InsertUnique(Op);
6982   else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S))
6983     for (auto *Op : S2->operands())
6984       InsertUnique(Op);
6985 }
6986 
6987 const Instruction *
6988 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
6989                                        bool &Precise) {
6990   Precise = true;
6991   // Do a bounded search of the def relation of the requested SCEVs.
6992   SmallSet<const SCEV *, 16> Visited;
6993   SmallVector<const SCEV *> Worklist;
6994   auto pushOp = [&](const SCEV *S) {
6995     if (!Visited.insert(S).second)
6996       return;
6997     // Threshold of 30 here is arbitrary.
6998     if (Visited.size() > 30) {
6999       Precise = false;
7000       return;
7001     }
7002     Worklist.push_back(S);
7003   };
7004 
7005   for (auto *S : Ops)
7006     pushOp(S);
7007 
7008   const Instruction *Bound = nullptr;
7009   while (!Worklist.empty()) {
7010     auto *S = Worklist.pop_back_val();
7011     if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7012       if (!Bound || DT.dominates(Bound, DefI))
7013         Bound = DefI;
7014     } else {
7015       SmallVector<const SCEV *, 4> Ops;
7016       collectUniqueOps(S, Ops);
7017       for (auto *Op : Ops)
7018         pushOp(Op);
7019     }
7020   }
7021   return Bound ? Bound : &*F.getEntryBlock().begin();
7022 }
7023 
7024 const Instruction *
7025 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7026   bool Discard;
7027   return getDefiningScopeBound(Ops, Discard);
7028 }
7029 
7030 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7031                                                         const Instruction *B) {
7032   if (A->getParent() == B->getParent() &&
7033       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7034                                                  B->getIterator()))
7035     return true;
7036 
7037   auto *BLoop = LI.getLoopFor(B->getParent());
7038   if (BLoop && BLoop->getHeader() == B->getParent() &&
7039       BLoop->getLoopPreheader() == A->getParent() &&
7040       isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7041                                                  A->getParent()->end()) &&
7042       isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7043                                                  B->getIterator()))
7044     return true;
7045   return false;
7046 }
7047 
7048 
7049 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7050   // Only proceed if we can prove that I does not yield poison.
7051   if (!programUndefinedIfPoison(I))
7052     return false;
7053 
7054   // At this point we know that if I is executed, then it does not wrap
7055   // according to at least one of NSW or NUW. If I is not executed, then we do
7056   // not know if the calculation that I represents would wrap. Multiple
7057   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7058   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7059   // derived from other instructions that map to the same SCEV. We cannot make
7060   // that guarantee for cases where I is not executed. So we need to find a
7061   // upper bound on the defining scope for the SCEV, and prove that I is
7062   // executed every time we enter that scope.  When the bounding scope is a
7063   // loop (the common case), this is equivalent to proving I executes on every
7064   // iteration of that loop.
7065   SmallVector<const SCEV *> SCEVOps;
7066   for (const Use &Op : I->operands()) {
7067     // I could be an extractvalue from a call to an overflow intrinsic.
7068     // TODO: We can do better here in some cases.
7069     if (isSCEVable(Op->getType()))
7070       SCEVOps.push_back(getSCEV(Op));
7071   }
7072   auto *DefI = getDefiningScopeBound(SCEVOps);
7073   return isGuaranteedToTransferExecutionTo(DefI, I);
7074 }
7075 
7076 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7077   // If we know that \c I can never be poison period, then that's enough.
7078   if (isSCEVExprNeverPoison(I))
7079     return true;
7080 
7081   // For an add recurrence specifically, we assume that infinite loops without
7082   // side effects are undefined behavior, and then reason as follows:
7083   //
7084   // If the add recurrence is poison in any iteration, it is poison on all
7085   // future iterations (since incrementing poison yields poison). If the result
7086   // of the add recurrence is fed into the loop latch condition and the loop
7087   // does not contain any throws or exiting blocks other than the latch, we now
7088   // have the ability to "choose" whether the backedge is taken or not (by
7089   // choosing a sufficiently evil value for the poison feeding into the branch)
7090   // for every iteration including and after the one in which \p I first became
7091   // poison.  There are two possibilities (let's call the iteration in which \p
7092   // I first became poison as K):
7093   //
7094   //  1. In the set of iterations including and after K, the loop body executes
7095   //     no side effects.  In this case executing the backege an infinte number
7096   //     of times will yield undefined behavior.
7097   //
7098   //  2. In the set of iterations including and after K, the loop body executes
7099   //     at least one side effect.  In this case, that specific instance of side
7100   //     effect is control dependent on poison, which also yields undefined
7101   //     behavior.
7102 
7103   auto *ExitingBB = L->getExitingBlock();
7104   auto *LatchBB = L->getLoopLatch();
7105   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
7106     return false;
7107 
7108   SmallPtrSet<const Instruction *, 16> Pushed;
7109   SmallVector<const Instruction *, 8> PoisonStack;
7110 
7111   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
7112   // things that are known to be poison under that assumption go on the
7113   // PoisonStack.
7114   Pushed.insert(I);
7115   PoisonStack.push_back(I);
7116 
7117   bool LatchControlDependentOnPoison = false;
7118   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
7119     const Instruction *Poison = PoisonStack.pop_back_val();
7120 
7121     for (auto *PoisonUser : Poison->users()) {
7122       if (propagatesPoison(cast<Operator>(PoisonUser))) {
7123         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
7124           PoisonStack.push_back(cast<Instruction>(PoisonUser));
7125       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
7126         assert(BI->isConditional() && "Only possibility!");
7127         if (BI->getParent() == LatchBB) {
7128           LatchControlDependentOnPoison = true;
7129           break;
7130         }
7131       }
7132     }
7133   }
7134 
7135   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
7136 }
7137 
7138 ScalarEvolution::LoopProperties
7139 ScalarEvolution::getLoopProperties(const Loop *L) {
7140   using LoopProperties = ScalarEvolution::LoopProperties;
7141 
7142   auto Itr = LoopPropertiesCache.find(L);
7143   if (Itr == LoopPropertiesCache.end()) {
7144     auto HasSideEffects = [](Instruction *I) {
7145       if (auto *SI = dyn_cast<StoreInst>(I))
7146         return !SI->isSimple();
7147 
7148       return I->mayThrow() || I->mayWriteToMemory();
7149     };
7150 
7151     LoopProperties LP = {/* HasNoAbnormalExits */ true,
7152                          /*HasNoSideEffects*/ true};
7153 
7154     for (auto *BB : L->getBlocks())
7155       for (auto &I : *BB) {
7156         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7157           LP.HasNoAbnormalExits = false;
7158         if (HasSideEffects(&I))
7159           LP.HasNoSideEffects = false;
7160         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7161           break; // We're already as pessimistic as we can get.
7162       }
7163 
7164     auto InsertPair = LoopPropertiesCache.insert({L, LP});
7165     assert(InsertPair.second && "We just checked!");
7166     Itr = InsertPair.first;
7167   }
7168 
7169   return Itr->second;
7170 }
7171 
7172 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7173   // A mustprogress loop without side effects must be finite.
7174   // TODO: The check used here is very conservative.  It's only *specific*
7175   // side effects which are well defined in infinite loops.
7176   return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7177 }
7178 
7179 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7180   if (!isSCEVable(V->getType()))
7181     return getUnknown(V);
7182 
7183   if (Instruction *I = dyn_cast<Instruction>(V)) {
7184     // Don't attempt to analyze instructions in blocks that aren't
7185     // reachable. Such instructions don't matter, and they aren't required
7186     // to obey basic rules for definitions dominating uses which this
7187     // analysis depends on.
7188     if (!DT.isReachableFromEntry(I->getParent()))
7189       return getUnknown(UndefValue::get(V->getType()));
7190   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7191     return getConstant(CI);
7192   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
7193     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
7194   else if (!isa<ConstantExpr>(V))
7195     return getUnknown(V);
7196 
7197   Operator *U = cast<Operator>(V);
7198   if (auto BO = MatchBinaryOp(U, DT)) {
7199     switch (BO->Opcode) {
7200     case Instruction::Add: {
7201       // The simple thing to do would be to just call getSCEV on both operands
7202       // and call getAddExpr with the result. However if we're looking at a
7203       // bunch of things all added together, this can be quite inefficient,
7204       // because it leads to N-1 getAddExpr calls for N ultimate operands.
7205       // Instead, gather up all the operands and make a single getAddExpr call.
7206       // LLVM IR canonical form means we need only traverse the left operands.
7207       SmallVector<const SCEV *, 4> AddOps;
7208       do {
7209         if (BO->Op) {
7210           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7211             AddOps.push_back(OpSCEV);
7212             break;
7213           }
7214 
7215           // If a NUW or NSW flag can be applied to the SCEV for this
7216           // addition, then compute the SCEV for this addition by itself
7217           // with a separate call to getAddExpr. We need to do that
7218           // instead of pushing the operands of the addition onto AddOps,
7219           // since the flags are only known to apply to this particular
7220           // addition - they may not apply to other additions that can be
7221           // formed with operands from AddOps.
7222           const SCEV *RHS = getSCEV(BO->RHS);
7223           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7224           if (Flags != SCEV::FlagAnyWrap) {
7225             const SCEV *LHS = getSCEV(BO->LHS);
7226             if (BO->Opcode == Instruction::Sub)
7227               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7228             else
7229               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7230             break;
7231           }
7232         }
7233 
7234         if (BO->Opcode == Instruction::Sub)
7235           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7236         else
7237           AddOps.push_back(getSCEV(BO->RHS));
7238 
7239         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7240         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7241                        NewBO->Opcode != Instruction::Sub)) {
7242           AddOps.push_back(getSCEV(BO->LHS));
7243           break;
7244         }
7245         BO = NewBO;
7246       } while (true);
7247 
7248       return getAddExpr(AddOps);
7249     }
7250 
7251     case Instruction::Mul: {
7252       SmallVector<const SCEV *, 4> MulOps;
7253       do {
7254         if (BO->Op) {
7255           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7256             MulOps.push_back(OpSCEV);
7257             break;
7258           }
7259 
7260           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7261           if (Flags != SCEV::FlagAnyWrap) {
7262             MulOps.push_back(
7263                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
7264             break;
7265           }
7266         }
7267 
7268         MulOps.push_back(getSCEV(BO->RHS));
7269         auto NewBO = MatchBinaryOp(BO->LHS, DT);
7270         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7271           MulOps.push_back(getSCEV(BO->LHS));
7272           break;
7273         }
7274         BO = NewBO;
7275       } while (true);
7276 
7277       return getMulExpr(MulOps);
7278     }
7279     case Instruction::UDiv:
7280       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7281     case Instruction::URem:
7282       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7283     case Instruction::Sub: {
7284       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7285       if (BO->Op)
7286         Flags = getNoWrapFlagsFromUB(BO->Op);
7287       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
7288     }
7289     case Instruction::And:
7290       // For an expression like x&255 that merely masks off the high bits,
7291       // use zext(trunc(x)) as the SCEV expression.
7292       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7293         if (CI->isZero())
7294           return getSCEV(BO->RHS);
7295         if (CI->isMinusOne())
7296           return getSCEV(BO->LHS);
7297         const APInt &A = CI->getValue();
7298 
7299         // Instcombine's ShrinkDemandedConstant may strip bits out of
7300         // constants, obscuring what would otherwise be a low-bits mask.
7301         // Use computeKnownBits to compute what ShrinkDemandedConstant
7302         // knew about to reconstruct a low-bits mask value.
7303         unsigned LZ = A.countLeadingZeros();
7304         unsigned TZ = A.countTrailingZeros();
7305         unsigned BitWidth = A.getBitWidth();
7306         KnownBits Known(BitWidth);
7307         computeKnownBits(BO->LHS, Known, getDataLayout(),
7308                          0, &AC, nullptr, &DT);
7309 
7310         APInt EffectiveMask =
7311             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7312         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7313           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7314           const SCEV *LHS = getSCEV(BO->LHS);
7315           const SCEV *ShiftedLHS = nullptr;
7316           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7317             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7318               // For an expression like (x * 8) & 8, simplify the multiply.
7319               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
7320               unsigned GCD = std::min(MulZeros, TZ);
7321               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7322               SmallVector<const SCEV*, 4> MulOps;
7323               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7324               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
7325               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7326               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7327             }
7328           }
7329           if (!ShiftedLHS)
7330             ShiftedLHS = getUDivExpr(LHS, MulCount);
7331           return getMulExpr(
7332               getZeroExtendExpr(
7333                   getTruncateExpr(ShiftedLHS,
7334                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7335                   BO->LHS->getType()),
7336               MulCount);
7337         }
7338       }
7339       // Binary `and` is a bit-wise `umin`.
7340       if (BO->LHS->getType()->isIntegerTy(1))
7341         return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7342       break;
7343 
7344     case Instruction::Or:
7345       // If the RHS of the Or is a constant, we may have something like:
7346       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
7347       // optimizations will transparently handle this case.
7348       //
7349       // In order for this transformation to be safe, the LHS must be of the
7350       // form X*(2^n) and the Or constant must be less than 2^n.
7351       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7352         const SCEV *LHS = getSCEV(BO->LHS);
7353         const APInt &CIVal = CI->getValue();
7354         if (GetMinTrailingZeros(LHS) >=
7355             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
7356           // Build a plain add SCEV.
7357           return getAddExpr(LHS, getSCEV(CI),
7358                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
7359         }
7360       }
7361       // Binary `or` is a bit-wise `umax`.
7362       if (BO->LHS->getType()->isIntegerTy(1))
7363         return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
7364       break;
7365 
7366     case Instruction::Xor:
7367       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7368         // If the RHS of xor is -1, then this is a not operation.
7369         if (CI->isMinusOne())
7370           return getNotSCEV(getSCEV(BO->LHS));
7371 
7372         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7373         // This is a variant of the check for xor with -1, and it handles
7374         // the case where instcombine has trimmed non-demanded bits out
7375         // of an xor with -1.
7376         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7377           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7378             if (LBO->getOpcode() == Instruction::And &&
7379                 LCI->getValue() == CI->getValue())
7380               if (const SCEVZeroExtendExpr *Z =
7381                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7382                 Type *UTy = BO->LHS->getType();
7383                 const SCEV *Z0 = Z->getOperand();
7384                 Type *Z0Ty = Z0->getType();
7385                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7386 
7387                 // If C is a low-bits mask, the zero extend is serving to
7388                 // mask off the high bits. Complement the operand and
7389                 // re-apply the zext.
7390                 if (CI->getValue().isMask(Z0TySize))
7391                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7392 
7393                 // If C is a single bit, it may be in the sign-bit position
7394                 // before the zero-extend. In this case, represent the xor
7395                 // using an add, which is equivalent, and re-apply the zext.
7396                 APInt Trunc = CI->getValue().trunc(Z0TySize);
7397                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7398                     Trunc.isSignMask())
7399                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7400                                            UTy);
7401               }
7402       }
7403       break;
7404 
7405     case Instruction::Shl:
7406       // Turn shift left of a constant amount into a multiply.
7407       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7408         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7409 
7410         // If the shift count is not less than the bitwidth, the result of
7411         // the shift is undefined. Don't try to analyze it, because the
7412         // resolution chosen here may differ from the resolution chosen in
7413         // other parts of the compiler.
7414         if (SA->getValue().uge(BitWidth))
7415           break;
7416 
7417         // We can safely preserve the nuw flag in all cases. It's also safe to
7418         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7419         // requires special handling. It can be preserved as long as we're not
7420         // left shifting by bitwidth - 1.
7421         auto Flags = SCEV::FlagAnyWrap;
7422         if (BO->Op) {
7423           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7424           if ((MulFlags & SCEV::FlagNSW) &&
7425               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7426             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7427           if (MulFlags & SCEV::FlagNUW)
7428             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7429         }
7430 
7431         Constant *X = ConstantInt::get(
7432             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7433         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
7434       }
7435       break;
7436 
7437     case Instruction::AShr: {
7438       // AShr X, C, where C is a constant.
7439       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7440       if (!CI)
7441         break;
7442 
7443       Type *OuterTy = BO->LHS->getType();
7444       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7445       // If the shift count is not less than the bitwidth, the result of
7446       // the shift is undefined. Don't try to analyze it, because the
7447       // resolution chosen here may differ from the resolution chosen in
7448       // other parts of the compiler.
7449       if (CI->getValue().uge(BitWidth))
7450         break;
7451 
7452       if (CI->isZero())
7453         return getSCEV(BO->LHS); // shift by zero --> noop
7454 
7455       uint64_t AShrAmt = CI->getZExtValue();
7456       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7457 
7458       Operator *L = dyn_cast<Operator>(BO->LHS);
7459       if (L && L->getOpcode() == Instruction::Shl) {
7460         // X = Shl A, n
7461         // Y = AShr X, m
7462         // Both n and m are constant.
7463 
7464         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7465         if (L->getOperand(1) == BO->RHS)
7466           // For a two-shift sext-inreg, i.e. n = m,
7467           // use sext(trunc(x)) as the SCEV expression.
7468           return getSignExtendExpr(
7469               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7470 
7471         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7472         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7473           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7474           if (ShlAmt > AShrAmt) {
7475             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7476             // expression. We already checked that ShlAmt < BitWidth, so
7477             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7478             // ShlAmt - AShrAmt < Amt.
7479             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7480                                             ShlAmt - AShrAmt);
7481             return getSignExtendExpr(
7482                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7483                 getConstant(Mul)), OuterTy);
7484           }
7485         }
7486       }
7487       break;
7488     }
7489     }
7490   }
7491 
7492   switch (U->getOpcode()) {
7493   case Instruction::Trunc:
7494     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7495 
7496   case Instruction::ZExt:
7497     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7498 
7499   case Instruction::SExt:
7500     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
7501       // The NSW flag of a subtract does not always survive the conversion to
7502       // A + (-1)*B.  By pushing sign extension onto its operands we are much
7503       // more likely to preserve NSW and allow later AddRec optimisations.
7504       //
7505       // NOTE: This is effectively duplicating this logic from getSignExtend:
7506       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7507       // but by that point the NSW information has potentially been lost.
7508       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7509         Type *Ty = U->getType();
7510         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7511         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7512         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7513       }
7514     }
7515     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7516 
7517   case Instruction::BitCast:
7518     // BitCasts are no-op casts so we just eliminate the cast.
7519     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7520       return getSCEV(U->getOperand(0));
7521     break;
7522 
7523   case Instruction::PtrToInt: {
7524     // Pointer to integer cast is straight-forward, so do model it.
7525     const SCEV *Op = getSCEV(U->getOperand(0));
7526     Type *DstIntTy = U->getType();
7527     // But only if effective SCEV (integer) type is wide enough to represent
7528     // all possible pointer values.
7529     const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7530     if (isa<SCEVCouldNotCompute>(IntOp))
7531       return getUnknown(V);
7532     return IntOp;
7533   }
7534   case Instruction::IntToPtr:
7535     // Just don't deal with inttoptr casts.
7536     return getUnknown(V);
7537 
7538   case Instruction::SDiv:
7539     // If both operands are non-negative, this is just an udiv.
7540     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7541         isKnownNonNegative(getSCEV(U->getOperand(1))))
7542       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7543     break;
7544 
7545   case Instruction::SRem:
7546     // If both operands are non-negative, this is just an urem.
7547     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7548         isKnownNonNegative(getSCEV(U->getOperand(1))))
7549       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7550     break;
7551 
7552   case Instruction::GetElementPtr:
7553     return createNodeForGEP(cast<GEPOperator>(U));
7554 
7555   case Instruction::PHI:
7556     return createNodeForPHI(cast<PHINode>(U));
7557 
7558   case Instruction::Select:
7559     return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
7560                                     U->getOperand(2));
7561 
7562   case Instruction::Call:
7563   case Instruction::Invoke:
7564     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7565       return getSCEV(RV);
7566 
7567     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7568       switch (II->getIntrinsicID()) {
7569       case Intrinsic::abs:
7570         return getAbsExpr(
7571             getSCEV(II->getArgOperand(0)),
7572             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7573       case Intrinsic::umax:
7574         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
7575                            getSCEV(II->getArgOperand(1)));
7576       case Intrinsic::umin:
7577         return getUMinExpr(getSCEV(II->getArgOperand(0)),
7578                            getSCEV(II->getArgOperand(1)));
7579       case Intrinsic::smax:
7580         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
7581                            getSCEV(II->getArgOperand(1)));
7582       case Intrinsic::smin:
7583         return getSMinExpr(getSCEV(II->getArgOperand(0)),
7584                            getSCEV(II->getArgOperand(1)));
7585       case Intrinsic::usub_sat: {
7586         const SCEV *X = getSCEV(II->getArgOperand(0));
7587         const SCEV *Y = getSCEV(II->getArgOperand(1));
7588         const SCEV *ClampedY = getUMinExpr(X, Y);
7589         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
7590       }
7591       case Intrinsic::uadd_sat: {
7592         const SCEV *X = getSCEV(II->getArgOperand(0));
7593         const SCEV *Y = getSCEV(II->getArgOperand(1));
7594         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
7595         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
7596       }
7597       case Intrinsic::start_loop_iterations:
7598         // A start_loop_iterations is just equivalent to the first operand for
7599         // SCEV purposes.
7600         return getSCEV(II->getArgOperand(0));
7601       default:
7602         break;
7603       }
7604     }
7605     break;
7606   }
7607 
7608   return getUnknown(V);
7609 }
7610 
7611 //===----------------------------------------------------------------------===//
7612 //                   Iteration Count Computation Code
7613 //
7614 
7615 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
7616                                                        bool Extend) {
7617   if (isa<SCEVCouldNotCompute>(ExitCount))
7618     return getCouldNotCompute();
7619 
7620   auto *ExitCountType = ExitCount->getType();
7621   assert(ExitCountType->isIntegerTy());
7622 
7623   if (!Extend)
7624     return getAddExpr(ExitCount, getOne(ExitCountType));
7625 
7626   auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
7627                                     1 + ExitCountType->getScalarSizeInBits());
7628   return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
7629                     getOne(WiderType));
7630 }
7631 
7632 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
7633   if (!ExitCount)
7634     return 0;
7635 
7636   ConstantInt *ExitConst = ExitCount->getValue();
7637 
7638   // Guard against huge trip counts.
7639   if (ExitConst->getValue().getActiveBits() > 32)
7640     return 0;
7641 
7642   // In case of integer overflow, this returns 0, which is correct.
7643   return ((unsigned)ExitConst->getZExtValue()) + 1;
7644 }
7645 
7646 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
7647   auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
7648   return getConstantTripCount(ExitCount);
7649 }
7650 
7651 unsigned
7652 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
7653                                            const BasicBlock *ExitingBlock) {
7654   assert(ExitingBlock && "Must pass a non-null exiting block!");
7655   assert(L->isLoopExiting(ExitingBlock) &&
7656          "Exiting block must actually branch out of the loop!");
7657   const SCEVConstant *ExitCount =
7658       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
7659   return getConstantTripCount(ExitCount);
7660 }
7661 
7662 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
7663   const auto *MaxExitCount =
7664       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
7665   return getConstantTripCount(MaxExitCount);
7666 }
7667 
7668 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
7669   // We can't infer from Array in Irregular Loop.
7670   // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
7671   if (!L->isLoopSimplifyForm() || !L->isInnermost())
7672     return getCouldNotCompute();
7673 
7674   // FIXME: To make the scene more typical, we only analysis loops that have
7675   // one exiting block and that block must be the latch. To make it easier to
7676   // capture loops that have memory access and memory access will be executed
7677   // in each iteration.
7678   const BasicBlock *LoopLatch = L->getLoopLatch();
7679   assert(LoopLatch && "See defination of simplify form loop.");
7680   if (L->getExitingBlock() != LoopLatch)
7681     return getCouldNotCompute();
7682 
7683   const DataLayout &DL = getDataLayout();
7684   SmallVector<const SCEV *> InferCountColl;
7685   for (auto *BB : L->getBlocks()) {
7686     // Go here, we can know that Loop is a single exiting and simplified form
7687     // loop. Make sure that infer from Memory Operation in those BBs must be
7688     // executed in loop. First step, we can make sure that max execution time
7689     // of MemAccessBB in loop represents latch max excution time.
7690     // If MemAccessBB does not dom Latch, skip.
7691     //            Entry
7692     //              │
7693     //        ┌─────▼─────┐
7694     //        │Loop Header◄─────┐
7695     //        └──┬──────┬─┘     │
7696     //           │      │       │
7697     //  ┌────────▼──┐ ┌─▼─────┐ │
7698     //  │MemAccessBB│ │OtherBB│ │
7699     //  └────────┬──┘ └─┬─────┘ │
7700     //           │      │       │
7701     //         ┌─▼──────▼─┐     │
7702     //         │Loop Latch├─────┘
7703     //         └────┬─────┘
7704     //              ▼
7705     //             Exit
7706     if (!DT.dominates(BB, LoopLatch))
7707       continue;
7708 
7709     for (Instruction &Inst : *BB) {
7710       // Find Memory Operation Instruction.
7711       auto *GEP = getLoadStorePointerOperand(&Inst);
7712       if (!GEP)
7713         continue;
7714 
7715       auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
7716       // Do not infer from scalar type, eg."ElemSize = sizeof()".
7717       if (!ElemSize)
7718         continue;
7719 
7720       // Use a existing polynomial recurrence on the trip count.
7721       auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
7722       if (!AddRec)
7723         continue;
7724       auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
7725       auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
7726       if (!ArrBase || !Step)
7727         continue;
7728       assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
7729 
7730       // Only handle { %array + step },
7731       // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
7732       if (AddRec->getStart() != ArrBase)
7733         continue;
7734 
7735       // Memory operation pattern which have gaps.
7736       // Or repeat memory opreation.
7737       // And index of GEP wraps arround.
7738       if (Step->getAPInt().getActiveBits() > 32 ||
7739           Step->getAPInt().getZExtValue() !=
7740               ElemSize->getAPInt().getZExtValue() ||
7741           Step->isZero() || Step->getAPInt().isNegative())
7742         continue;
7743 
7744       // Only infer from stack array which has certain size.
7745       // Make sure alloca instruction is not excuted in loop.
7746       AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
7747       if (!AllocateInst || L->contains(AllocateInst->getParent()))
7748         continue;
7749 
7750       // Make sure only handle normal array.
7751       auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
7752       auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
7753       if (!Ty || !ArrSize || !ArrSize->isOne())
7754         continue;
7755 
7756       // FIXME: Since gep indices are silently zext to the indexing type,
7757       // we will have a narrow gep index which wraps around rather than
7758       // increasing strictly, we shoule ensure that step is increasing
7759       // strictly by the loop iteration.
7760       // Now we can infer a max execution time by MemLength/StepLength.
7761       const SCEV *MemSize =
7762           getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
7763       auto *MaxExeCount =
7764           dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
7765       if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
7766         continue;
7767 
7768       // If the loop reaches the maximum number of executions, we can not
7769       // access bytes starting outside the statically allocated size without
7770       // being immediate UB. But it is allowed to enter loop header one more
7771       // time.
7772       auto *InferCount = dyn_cast<SCEVConstant>(
7773           getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
7774       // Discard the maximum number of execution times under 32bits.
7775       if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
7776         continue;
7777 
7778       InferCountColl.push_back(InferCount);
7779     }
7780   }
7781 
7782   if (InferCountColl.size() == 0)
7783     return getCouldNotCompute();
7784 
7785   return getUMinFromMismatchedTypes(InferCountColl);
7786 }
7787 
7788 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
7789   SmallVector<BasicBlock *, 8> ExitingBlocks;
7790   L->getExitingBlocks(ExitingBlocks);
7791 
7792   Optional<unsigned> Res = None;
7793   for (auto *ExitingBB : ExitingBlocks) {
7794     unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
7795     if (!Res)
7796       Res = Multiple;
7797     Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple);
7798   }
7799   return Res.getValueOr(1);
7800 }
7801 
7802 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7803                                                        const SCEV *ExitCount) {
7804   if (ExitCount == getCouldNotCompute())
7805     return 1;
7806 
7807   // Get the trip count
7808   const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
7809 
7810   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
7811   if (!TC)
7812     // Attempt to factor more general cases. Returns the greatest power of
7813     // two divisor. If overflow happens, the trip count expression is still
7814     // divisible by the greatest power of 2 divisor returned.
7815     return 1U << std::min((uint32_t)31,
7816                           GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
7817 
7818   ConstantInt *Result = TC->getValue();
7819 
7820   // Guard against huge trip counts (this requires checking
7821   // for zero to handle the case where the trip count == -1 and the
7822   // addition wraps).
7823   if (!Result || Result->getValue().getActiveBits() > 32 ||
7824       Result->getValue().getActiveBits() == 0)
7825     return 1;
7826 
7827   return (unsigned)Result->getZExtValue();
7828 }
7829 
7830 /// Returns the largest constant divisor of the trip count of this loop as a
7831 /// normal unsigned value, if possible. This means that the actual trip count is
7832 /// always a multiple of the returned value (don't forget the trip count could
7833 /// very well be zero as well!).
7834 ///
7835 /// Returns 1 if the trip count is unknown or not guaranteed to be the
7836 /// multiple of a constant (which is also the case if the trip count is simply
7837 /// constant, use getSmallConstantTripCount for that case), Will also return 1
7838 /// if the trip count is very large (>= 2^32).
7839 ///
7840 /// As explained in the comments for getSmallConstantTripCount, this assumes
7841 /// that control exits the loop via ExitingBlock.
7842 unsigned
7843 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
7844                                               const BasicBlock *ExitingBlock) {
7845   assert(ExitingBlock && "Must pass a non-null exiting block!");
7846   assert(L->isLoopExiting(ExitingBlock) &&
7847          "Exiting block must actually branch out of the loop!");
7848   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
7849   return getSmallConstantTripMultiple(L, ExitCount);
7850 }
7851 
7852 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
7853                                           const BasicBlock *ExitingBlock,
7854                                           ExitCountKind Kind) {
7855   switch (Kind) {
7856   case Exact:
7857   case SymbolicMaximum:
7858     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
7859   case ConstantMaximum:
7860     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
7861   };
7862   llvm_unreachable("Invalid ExitCountKind!");
7863 }
7864 
7865 const SCEV *
7866 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
7867                                                  SmallVector<const SCEVPredicate *, 4> &Preds) {
7868   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
7869 }
7870 
7871 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
7872                                                    ExitCountKind Kind) {
7873   switch (Kind) {
7874   case Exact:
7875     return getBackedgeTakenInfo(L).getExact(L, this);
7876   case ConstantMaximum:
7877     return getBackedgeTakenInfo(L).getConstantMax(this);
7878   case SymbolicMaximum:
7879     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
7880   };
7881   llvm_unreachable("Invalid ExitCountKind!");
7882 }
7883 
7884 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
7885   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
7886 }
7887 
7888 /// Push PHI nodes in the header of the given loop onto the given Worklist.
7889 static void PushLoopPHIs(const Loop *L,
7890                          SmallVectorImpl<Instruction *> &Worklist,
7891                          SmallPtrSetImpl<Instruction *> &Visited) {
7892   BasicBlock *Header = L->getHeader();
7893 
7894   // Push all Loop-header PHIs onto the Worklist stack.
7895   for (PHINode &PN : Header->phis())
7896     if (Visited.insert(&PN).second)
7897       Worklist.push_back(&PN);
7898 }
7899 
7900 const ScalarEvolution::BackedgeTakenInfo &
7901 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
7902   auto &BTI = getBackedgeTakenInfo(L);
7903   if (BTI.hasFullInfo())
7904     return BTI;
7905 
7906   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7907 
7908   if (!Pair.second)
7909     return Pair.first->second;
7910 
7911   BackedgeTakenInfo Result =
7912       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
7913 
7914   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
7915 }
7916 
7917 ScalarEvolution::BackedgeTakenInfo &
7918 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
7919   // Initially insert an invalid entry for this loop. If the insertion
7920   // succeeds, proceed to actually compute a backedge-taken count and
7921   // update the value. The temporary CouldNotCompute value tells SCEV
7922   // code elsewhere that it shouldn't attempt to request a new
7923   // backedge-taken count, which could result in infinite recursion.
7924   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
7925       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
7926   if (!Pair.second)
7927     return Pair.first->second;
7928 
7929   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
7930   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
7931   // must be cleared in this scope.
7932   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
7933 
7934   // In product build, there are no usage of statistic.
7935   (void)NumTripCountsComputed;
7936   (void)NumTripCountsNotComputed;
7937 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
7938   const SCEV *BEExact = Result.getExact(L, this);
7939   if (BEExact != getCouldNotCompute()) {
7940     assert(isLoopInvariant(BEExact, L) &&
7941            isLoopInvariant(Result.getConstantMax(this), L) &&
7942            "Computed backedge-taken count isn't loop invariant for loop!");
7943     ++NumTripCountsComputed;
7944   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
7945              isa<PHINode>(L->getHeader()->begin())) {
7946     // Only count loops that have phi nodes as not being computable.
7947     ++NumTripCountsNotComputed;
7948   }
7949 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
7950 
7951   // Now that we know more about the trip count for this loop, forget any
7952   // existing SCEV values for PHI nodes in this loop since they are only
7953   // conservative estimates made without the benefit of trip count
7954   // information. This invalidation is not necessary for correctness, and is
7955   // only done to produce more precise results.
7956   if (Result.hasAnyInfo()) {
7957     // Invalidate any expression using an addrec in this loop.
7958     SmallVector<const SCEV *, 8> ToForget;
7959     auto LoopUsersIt = LoopUsers.find(L);
7960     if (LoopUsersIt != LoopUsers.end())
7961       append_range(ToForget, LoopUsersIt->second);
7962     forgetMemoizedResults(ToForget);
7963 
7964     // Invalidate constant-evolved loop header phis.
7965     for (PHINode &PN : L->getHeader()->phis())
7966       ConstantEvolutionLoopExitValue.erase(&PN);
7967   }
7968 
7969   // Re-lookup the insert position, since the call to
7970   // computeBackedgeTakenCount above could result in a
7971   // recusive call to getBackedgeTakenInfo (on a different
7972   // loop), which would invalidate the iterator computed
7973   // earlier.
7974   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7975 }
7976 
7977 void ScalarEvolution::forgetAllLoops() {
7978   // This method is intended to forget all info about loops. It should
7979   // invalidate caches as if the following happened:
7980   // - The trip counts of all loops have changed arbitrarily
7981   // - Every llvm::Value has been updated in place to produce a different
7982   // result.
7983   BackedgeTakenCounts.clear();
7984   PredicatedBackedgeTakenCounts.clear();
7985   BECountUsers.clear();
7986   LoopPropertiesCache.clear();
7987   ConstantEvolutionLoopExitValue.clear();
7988   ValueExprMap.clear();
7989   ValuesAtScopes.clear();
7990   ValuesAtScopesUsers.clear();
7991   LoopDispositions.clear();
7992   BlockDispositions.clear();
7993   UnsignedRanges.clear();
7994   SignedRanges.clear();
7995   ExprValueMap.clear();
7996   HasRecMap.clear();
7997   MinTrailingZerosCache.clear();
7998   PredicatedSCEVRewrites.clear();
7999 }
8000 
8001 void ScalarEvolution::forgetLoop(const Loop *L) {
8002   SmallVector<const Loop *, 16> LoopWorklist(1, L);
8003   SmallVector<Instruction *, 32> Worklist;
8004   SmallPtrSet<Instruction *, 16> Visited;
8005   SmallVector<const SCEV *, 16> ToForget;
8006 
8007   // Iterate over all the loops and sub-loops to drop SCEV information.
8008   while (!LoopWorklist.empty()) {
8009     auto *CurrL = LoopWorklist.pop_back_val();
8010 
8011     // Drop any stored trip count value.
8012     forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8013     forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8014 
8015     // Drop information about predicated SCEV rewrites for this loop.
8016     for (auto I = PredicatedSCEVRewrites.begin();
8017          I != PredicatedSCEVRewrites.end();) {
8018       std::pair<const SCEV *, const Loop *> Entry = I->first;
8019       if (Entry.second == CurrL)
8020         PredicatedSCEVRewrites.erase(I++);
8021       else
8022         ++I;
8023     }
8024 
8025     auto LoopUsersItr = LoopUsers.find(CurrL);
8026     if (LoopUsersItr != LoopUsers.end()) {
8027       ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8028                 LoopUsersItr->second.end());
8029     }
8030 
8031     // Drop information about expressions based on loop-header PHIs.
8032     PushLoopPHIs(CurrL, Worklist, Visited);
8033 
8034     while (!Worklist.empty()) {
8035       Instruction *I = Worklist.pop_back_val();
8036 
8037       ValueExprMapType::iterator It =
8038           ValueExprMap.find_as(static_cast<Value *>(I));
8039       if (It != ValueExprMap.end()) {
8040         eraseValueFromMap(It->first);
8041         ToForget.push_back(It->second);
8042         if (PHINode *PN = dyn_cast<PHINode>(I))
8043           ConstantEvolutionLoopExitValue.erase(PN);
8044       }
8045 
8046       PushDefUseChildren(I, Worklist, Visited);
8047     }
8048 
8049     LoopPropertiesCache.erase(CurrL);
8050     // Forget all contained loops too, to avoid dangling entries in the
8051     // ValuesAtScopes map.
8052     LoopWorklist.append(CurrL->begin(), CurrL->end());
8053   }
8054   forgetMemoizedResults(ToForget);
8055 }
8056 
8057 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8058   while (Loop *Parent = L->getParentLoop())
8059     L = Parent;
8060   forgetLoop(L);
8061 }
8062 
8063 void ScalarEvolution::forgetValue(Value *V) {
8064   Instruction *I = dyn_cast<Instruction>(V);
8065   if (!I) return;
8066 
8067   // Drop information about expressions based on loop-header PHIs.
8068   SmallVector<Instruction *, 16> Worklist;
8069   SmallPtrSet<Instruction *, 8> Visited;
8070   SmallVector<const SCEV *, 8> ToForget;
8071   Worklist.push_back(I);
8072   Visited.insert(I);
8073 
8074   while (!Worklist.empty()) {
8075     I = Worklist.pop_back_val();
8076     ValueExprMapType::iterator It =
8077       ValueExprMap.find_as(static_cast<Value *>(I));
8078     if (It != ValueExprMap.end()) {
8079       eraseValueFromMap(It->first);
8080       ToForget.push_back(It->second);
8081       if (PHINode *PN = dyn_cast<PHINode>(I))
8082         ConstantEvolutionLoopExitValue.erase(PN);
8083     }
8084 
8085     PushDefUseChildren(I, Worklist, Visited);
8086   }
8087   forgetMemoizedResults(ToForget);
8088 }
8089 
8090 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
8091   LoopDispositions.clear();
8092 }
8093 
8094 /// Get the exact loop backedge taken count considering all loop exits. A
8095 /// computable result can only be returned for loops with all exiting blocks
8096 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8097 /// is never skipped. This is a valid assumption as long as the loop exits via
8098 /// that test. For precise results, it is the caller's responsibility to specify
8099 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8100 const SCEV *
8101 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8102                                              SmallVector<const SCEVPredicate *, 4> *Preds) const {
8103   // If any exits were not computable, the loop is not computable.
8104   if (!isComplete() || ExitNotTaken.empty())
8105     return SE->getCouldNotCompute();
8106 
8107   const BasicBlock *Latch = L->getLoopLatch();
8108   // All exiting blocks we have collected must dominate the only backedge.
8109   if (!Latch)
8110     return SE->getCouldNotCompute();
8111 
8112   // All exiting blocks we have gathered dominate loop's latch, so exact trip
8113   // count is simply a minimum out of all these calculated exit counts.
8114   SmallVector<const SCEV *, 2> Ops;
8115   for (auto &ENT : ExitNotTaken) {
8116     const SCEV *BECount = ENT.ExactNotTaken;
8117     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8118     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8119            "We should only have known counts for exiting blocks that dominate "
8120            "latch!");
8121 
8122     Ops.push_back(BECount);
8123 
8124     if (Preds)
8125       for (auto *P : ENT.Predicates)
8126         Preds->push_back(P);
8127 
8128     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8129            "Predicate should be always true!");
8130   }
8131 
8132   return SE->getUMinFromMismatchedTypes(Ops);
8133 }
8134 
8135 /// Get the exact not taken count for this loop exit.
8136 const SCEV *
8137 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8138                                              ScalarEvolution *SE) const {
8139   for (auto &ENT : ExitNotTaken)
8140     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8141       return ENT.ExactNotTaken;
8142 
8143   return SE->getCouldNotCompute();
8144 }
8145 
8146 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8147     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8148   for (auto &ENT : ExitNotTaken)
8149     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8150       return ENT.MaxNotTaken;
8151 
8152   return SE->getCouldNotCompute();
8153 }
8154 
8155 /// getConstantMax - Get the constant max backedge taken count for the loop.
8156 const SCEV *
8157 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8158   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8159     return !ENT.hasAlwaysTruePredicate();
8160   };
8161 
8162   if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8163     return SE->getCouldNotCompute();
8164 
8165   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8166           isa<SCEVConstant>(getConstantMax())) &&
8167          "No point in having a non-constant max backedge taken count!");
8168   return getConstantMax();
8169 }
8170 
8171 const SCEV *
8172 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8173                                                    ScalarEvolution *SE) {
8174   if (!SymbolicMax)
8175     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8176   return SymbolicMax;
8177 }
8178 
8179 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8180     ScalarEvolution *SE) const {
8181   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8182     return !ENT.hasAlwaysTruePredicate();
8183   };
8184   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8185 }
8186 
8187 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8188     : ExitLimit(E, E, false, None) {
8189 }
8190 
8191 ScalarEvolution::ExitLimit::ExitLimit(
8192     const SCEV *E, const SCEV *M, bool MaxOrZero,
8193     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8194     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
8195   // If we prove the max count is zero, so is the symbolic bound.  This happens
8196   // in practice due to differences in a) how context sensitive we've chosen
8197   // to be and b) how we reason about bounds impied by UB.
8198   if (MaxNotTaken->isZero())
8199     ExactNotTaken = MaxNotTaken;
8200 
8201   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8202           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
8203          "Exact is not allowed to be less precise than Max");
8204   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
8205           isa<SCEVConstant>(MaxNotTaken)) &&
8206          "No point in having a non-constant max backedge taken count!");
8207   for (auto *PredSet : PredSetList)
8208     for (auto *P : *PredSet)
8209       addPredicate(P);
8210   assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8211          "Backedge count should be int");
8212   assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) &&
8213          "Max backedge count should be int");
8214 }
8215 
8216 ScalarEvolution::ExitLimit::ExitLimit(
8217     const SCEV *E, const SCEV *M, bool MaxOrZero,
8218     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8219     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
8220 }
8221 
8222 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
8223                                       bool MaxOrZero)
8224     : ExitLimit(E, M, MaxOrZero, None) {
8225 }
8226 
8227 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8228 /// computable exit into a persistent ExitNotTakenInfo array.
8229 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8230     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8231     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8232     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8233   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8234 
8235   ExitNotTaken.reserve(ExitCounts.size());
8236   std::transform(
8237       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
8238       [&](const EdgeExitInfo &EEI) {
8239         BasicBlock *ExitBB = EEI.first;
8240         const ExitLimit &EL = EEI.second;
8241         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
8242                                 EL.Predicates);
8243       });
8244   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8245           isa<SCEVConstant>(ConstantMax)) &&
8246          "No point in having a non-constant max backedge taken count!");
8247 }
8248 
8249 /// Compute the number of times the backedge of the specified loop will execute.
8250 ScalarEvolution::BackedgeTakenInfo
8251 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8252                                            bool AllowPredicates) {
8253   SmallVector<BasicBlock *, 8> ExitingBlocks;
8254   L->getExitingBlocks(ExitingBlocks);
8255 
8256   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8257 
8258   SmallVector<EdgeExitInfo, 4> ExitCounts;
8259   bool CouldComputeBECount = true;
8260   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8261   const SCEV *MustExitMaxBECount = nullptr;
8262   const SCEV *MayExitMaxBECount = nullptr;
8263   bool MustExitMaxOrZero = false;
8264 
8265   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8266   // and compute maxBECount.
8267   // Do a union of all the predicates here.
8268   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8269     BasicBlock *ExitBB = ExitingBlocks[i];
8270 
8271     // We canonicalize untaken exits to br (constant), ignore them so that
8272     // proving an exit untaken doesn't negatively impact our ability to reason
8273     // about the loop as whole.
8274     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8275       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8276         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8277         if (ExitIfTrue == CI->isZero())
8278           continue;
8279       }
8280 
8281     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8282 
8283     assert((AllowPredicates || EL.Predicates.empty()) &&
8284            "Predicated exit limit when predicates are not allowed!");
8285 
8286     // 1. For each exit that can be computed, add an entry to ExitCounts.
8287     // CouldComputeBECount is true only if all exits can be computed.
8288     if (EL.ExactNotTaken == getCouldNotCompute())
8289       // We couldn't compute an exact value for this exit, so
8290       // we won't be able to compute an exact value for the loop.
8291       CouldComputeBECount = false;
8292     else
8293       ExitCounts.emplace_back(ExitBB, EL);
8294 
8295     // 2. Derive the loop's MaxBECount from each exit's max number of
8296     // non-exiting iterations. Partition the loop exits into two kinds:
8297     // LoopMustExits and LoopMayExits.
8298     //
8299     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8300     // is a LoopMayExit.  If any computable LoopMustExit is found, then
8301     // MaxBECount is the minimum EL.MaxNotTaken of computable
8302     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8303     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
8304     // computable EL.MaxNotTaken.
8305     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
8306         DT.dominates(ExitBB, Latch)) {
8307       if (!MustExitMaxBECount) {
8308         MustExitMaxBECount = EL.MaxNotTaken;
8309         MustExitMaxOrZero = EL.MaxOrZero;
8310       } else {
8311         MustExitMaxBECount =
8312             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
8313       }
8314     } else if (MayExitMaxBECount != getCouldNotCompute()) {
8315       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
8316         MayExitMaxBECount = EL.MaxNotTaken;
8317       else {
8318         MayExitMaxBECount =
8319             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
8320       }
8321     }
8322   }
8323   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8324     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8325   // The loop backedge will be taken the maximum or zero times if there's
8326   // a single exit that must be taken the maximum or zero times.
8327   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8328 
8329   // Remember which SCEVs are used in exit limits for invalidation purposes.
8330   // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken
8331   // and MaxBECount, which must be SCEVConstant.
8332   for (const auto &Pair : ExitCounts)
8333     if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8334       BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8335   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8336                            MaxBECount, MaxOrZero);
8337 }
8338 
8339 ScalarEvolution::ExitLimit
8340 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8341                                       bool AllowPredicates) {
8342   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8343   // If our exiting block does not dominate the latch, then its connection with
8344   // loop's exit limit may be far from trivial.
8345   const BasicBlock *Latch = L->getLoopLatch();
8346   if (!Latch || !DT.dominates(ExitingBlock, Latch))
8347     return getCouldNotCompute();
8348 
8349   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8350   Instruction *Term = ExitingBlock->getTerminator();
8351   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8352     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8353     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8354     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8355            "It should have one successor in loop and one exit block!");
8356     // Proceed to the next level to examine the exit condition expression.
8357     return computeExitLimitFromCond(
8358         L, BI->getCondition(), ExitIfTrue,
8359         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8360   }
8361 
8362   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8363     // For switch, make sure that there is a single exit from the loop.
8364     BasicBlock *Exit = nullptr;
8365     for (auto *SBB : successors(ExitingBlock))
8366       if (!L->contains(SBB)) {
8367         if (Exit) // Multiple exit successors.
8368           return getCouldNotCompute();
8369         Exit = SBB;
8370       }
8371     assert(Exit && "Exiting block must have at least one exit");
8372     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8373                                                 /*ControlsExit=*/IsOnlyExit);
8374   }
8375 
8376   return getCouldNotCompute();
8377 }
8378 
8379 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8380     const Loop *L, Value *ExitCond, bool ExitIfTrue,
8381     bool ControlsExit, bool AllowPredicates) {
8382   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8383   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8384                                         ControlsExit, AllowPredicates);
8385 }
8386 
8387 Optional<ScalarEvolution::ExitLimit>
8388 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8389                                       bool ExitIfTrue, bool ControlsExit,
8390                                       bool AllowPredicates) {
8391   (void)this->L;
8392   (void)this->ExitIfTrue;
8393   (void)this->AllowPredicates;
8394 
8395   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8396          this->AllowPredicates == AllowPredicates &&
8397          "Variance in assumed invariant key components!");
8398   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8399   if (Itr == TripCountMap.end())
8400     return None;
8401   return Itr->second;
8402 }
8403 
8404 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8405                                              bool ExitIfTrue,
8406                                              bool ControlsExit,
8407                                              bool AllowPredicates,
8408                                              const ExitLimit &EL) {
8409   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8410          this->AllowPredicates == AllowPredicates &&
8411          "Variance in assumed invariant key components!");
8412 
8413   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8414   assert(InsertResult.second && "Expected successful insertion!");
8415   (void)InsertResult;
8416   (void)ExitIfTrue;
8417 }
8418 
8419 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8420     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8421     bool ControlsExit, bool AllowPredicates) {
8422 
8423   if (auto MaybeEL =
8424           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8425     return *MaybeEL;
8426 
8427   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8428                                               ControlsExit, AllowPredicates);
8429   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8430   return EL;
8431 }
8432 
8433 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8434     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8435     bool ControlsExit, bool AllowPredicates) {
8436   // Handle BinOp conditions (And, Or).
8437   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8438           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8439     return *LimitFromBinOp;
8440 
8441   // With an icmp, it may be feasible to compute an exact backedge-taken count.
8442   // Proceed to the next level to examine the icmp.
8443   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8444     ExitLimit EL =
8445         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8446     if (EL.hasFullInfo() || !AllowPredicates)
8447       return EL;
8448 
8449     // Try again, but use SCEV predicates this time.
8450     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8451                                     /*AllowPredicates=*/true);
8452   }
8453 
8454   // Check for a constant condition. These are normally stripped out by
8455   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8456   // preserve the CFG and is temporarily leaving constant conditions
8457   // in place.
8458   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8459     if (ExitIfTrue == !CI->getZExtValue())
8460       // The backedge is always taken.
8461       return getCouldNotCompute();
8462     else
8463       // The backedge is never taken.
8464       return getZero(CI->getType());
8465   }
8466 
8467   // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8468   // with a constant step, we can form an equivalent icmp predicate and figure
8469   // out how many iterations will be taken before we exit.
8470   const WithOverflowInst *WO;
8471   const APInt *C;
8472   if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8473       match(WO->getRHS(), m_APInt(C))) {
8474     ConstantRange NWR =
8475       ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8476                                            WO->getNoWrapKind());
8477     CmpInst::Predicate Pred;
8478     APInt NewRHSC, Offset;
8479     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8480     if (!ExitIfTrue)
8481       Pred = ICmpInst::getInversePredicate(Pred);
8482     auto *LHS = getSCEV(WO->getLHS());
8483     if (Offset != 0)
8484       LHS = getAddExpr(LHS, getConstant(Offset));
8485     auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8486                                        ControlsExit, AllowPredicates);
8487     if (EL.hasAnyInfo()) return EL;
8488   }
8489 
8490   // If it's not an integer or pointer comparison then compute it the hard way.
8491   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8492 }
8493 
8494 Optional<ScalarEvolution::ExitLimit>
8495 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8496     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8497     bool ControlsExit, bool AllowPredicates) {
8498   // Check if the controlling expression for this loop is an And or Or.
8499   Value *Op0, *Op1;
8500   bool IsAnd = false;
8501   if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8502     IsAnd = true;
8503   else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8504     IsAnd = false;
8505   else
8506     return None;
8507 
8508   // EitherMayExit is true in these two cases:
8509   //   br (and Op0 Op1), loop, exit
8510   //   br (or  Op0 Op1), exit, loop
8511   bool EitherMayExit = IsAnd ^ ExitIfTrue;
8512   ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
8513                                                  ControlsExit && !EitherMayExit,
8514                                                  AllowPredicates);
8515   ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
8516                                                  ControlsExit && !EitherMayExit,
8517                                                  AllowPredicates);
8518 
8519   // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8520   const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8521   if (isa<ConstantInt>(Op1))
8522     return Op1 == NeutralElement ? EL0 : EL1;
8523   if (isa<ConstantInt>(Op0))
8524     return Op0 == NeutralElement ? EL1 : EL0;
8525 
8526   const SCEV *BECount = getCouldNotCompute();
8527   const SCEV *MaxBECount = getCouldNotCompute();
8528   if (EitherMayExit) {
8529     // Both conditions must be same for the loop to continue executing.
8530     // Choose the less conservative count.
8531     if (EL0.ExactNotTaken != getCouldNotCompute() &&
8532         EL1.ExactNotTaken != getCouldNotCompute()) {
8533       BECount = getUMinFromMismatchedTypes(
8534           EL0.ExactNotTaken, EL1.ExactNotTaken,
8535           /*Sequential=*/!isa<BinaryOperator>(ExitCond));
8536 
8537       // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form,
8538       // it should have been simplified to zero (see the condition (3) above)
8539       assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() ||
8540              BECount->isZero());
8541     }
8542     if (EL0.MaxNotTaken == getCouldNotCompute())
8543       MaxBECount = EL1.MaxNotTaken;
8544     else if (EL1.MaxNotTaken == getCouldNotCompute())
8545       MaxBECount = EL0.MaxNotTaken;
8546     else
8547       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
8548   } else {
8549     // Both conditions must be same at the same time for the loop to exit.
8550     // For now, be conservative.
8551     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8552       BECount = EL0.ExactNotTaken;
8553   }
8554 
8555   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8556   // to be more aggressive when computing BECount than when computing
8557   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
8558   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
8559   // to not.
8560   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
8561       !isa<SCEVCouldNotCompute>(BECount))
8562     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
8563 
8564   return ExitLimit(BECount, MaxBECount, false,
8565                    { &EL0.Predicates, &EL1.Predicates });
8566 }
8567 
8568 ScalarEvolution::ExitLimit
8569 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8570                                           ICmpInst *ExitCond,
8571                                           bool ExitIfTrue,
8572                                           bool ControlsExit,
8573                                           bool AllowPredicates) {
8574   // If the condition was exit on true, convert the condition to exit on false
8575   ICmpInst::Predicate Pred;
8576   if (!ExitIfTrue)
8577     Pred = ExitCond->getPredicate();
8578   else
8579     Pred = ExitCond->getInversePredicate();
8580   const ICmpInst::Predicate OriginalPred = Pred;
8581 
8582   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8583   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8584 
8585   ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
8586                                           AllowPredicates);
8587   if (EL.hasAnyInfo()) return EL;
8588 
8589   auto *ExhaustiveCount =
8590       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8591 
8592   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8593     return ExhaustiveCount;
8594 
8595   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8596                                       ExitCond->getOperand(1), L, OriginalPred);
8597 }
8598 ScalarEvolution::ExitLimit
8599 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
8600                                           ICmpInst::Predicate Pred,
8601                                           const SCEV *LHS, const SCEV *RHS,
8602                                           bool ControlsExit,
8603                                           bool AllowPredicates) {
8604 
8605   // Try to evaluate any dependencies out of the loop.
8606   LHS = getSCEVAtScope(LHS, L);
8607   RHS = getSCEVAtScope(RHS, L);
8608 
8609   // At this point, we would like to compute how many iterations of the
8610   // loop the predicate will return true for these inputs.
8611   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
8612     // If there is a loop-invariant, force it into the RHS.
8613     std::swap(LHS, RHS);
8614     Pred = ICmpInst::getSwappedPredicate(Pred);
8615   }
8616 
8617   bool ControllingFiniteLoop =
8618       ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
8619   // Simplify the operands before analyzing them.
8620   (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
8621                              (EnableFiniteLoopControl ? ControllingFiniteLoop
8622                                                      : false));
8623 
8624   // If we have a comparison of a chrec against a constant, try to use value
8625   // ranges to answer this query.
8626   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
8627     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
8628       if (AddRec->getLoop() == L) {
8629         // Form the constant range.
8630         ConstantRange CompRange =
8631             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
8632 
8633         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
8634         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
8635       }
8636 
8637   // If this loop must exit based on this condition (or execute undefined
8638   // behaviour), and we can prove the test sequence produced must repeat
8639   // the same values on self-wrap of the IV, then we can infer that IV
8640   // doesn't self wrap because if it did, we'd have an infinite (undefined)
8641   // loop.
8642   if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
8643     // TODO: We can peel off any functions which are invertible *in L*.  Loop
8644     // invariant terms are effectively constants for our purposes here.
8645     auto *InnerLHS = LHS;
8646     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
8647       InnerLHS = ZExt->getOperand();
8648     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
8649       auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
8650       if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
8651           StrideC && StrideC->getAPInt().isPowerOf2()) {
8652         auto Flags = AR->getNoWrapFlags();
8653         Flags = setFlags(Flags, SCEV::FlagNW);
8654         SmallVector<const SCEV*> Operands{AR->operands()};
8655         Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
8656         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
8657       }
8658     }
8659   }
8660 
8661   switch (Pred) {
8662   case ICmpInst::ICMP_NE: {                     // while (X != Y)
8663     // Convert to: while (X-Y != 0)
8664     if (LHS->getType()->isPointerTy()) {
8665       LHS = getLosslessPtrToIntExpr(LHS);
8666       if (isa<SCEVCouldNotCompute>(LHS))
8667         return LHS;
8668     }
8669     if (RHS->getType()->isPointerTy()) {
8670       RHS = getLosslessPtrToIntExpr(RHS);
8671       if (isa<SCEVCouldNotCompute>(RHS))
8672         return RHS;
8673     }
8674     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
8675                                 AllowPredicates);
8676     if (EL.hasAnyInfo()) return EL;
8677     break;
8678   }
8679   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
8680     // Convert to: while (X-Y == 0)
8681     if (LHS->getType()->isPointerTy()) {
8682       LHS = getLosslessPtrToIntExpr(LHS);
8683       if (isa<SCEVCouldNotCompute>(LHS))
8684         return LHS;
8685     }
8686     if (RHS->getType()->isPointerTy()) {
8687       RHS = getLosslessPtrToIntExpr(RHS);
8688       if (isa<SCEVCouldNotCompute>(RHS))
8689         return RHS;
8690     }
8691     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
8692     if (EL.hasAnyInfo()) return EL;
8693     break;
8694   }
8695   case ICmpInst::ICMP_SLT:
8696   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
8697     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
8698     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
8699                                     AllowPredicates);
8700     if (EL.hasAnyInfo()) return EL;
8701     break;
8702   }
8703   case ICmpInst::ICMP_SGT:
8704   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
8705     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
8706     ExitLimit EL =
8707         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
8708                             AllowPredicates);
8709     if (EL.hasAnyInfo()) return EL;
8710     break;
8711   }
8712   default:
8713     break;
8714   }
8715 
8716   return getCouldNotCompute();
8717 }
8718 
8719 ScalarEvolution::ExitLimit
8720 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
8721                                                       SwitchInst *Switch,
8722                                                       BasicBlock *ExitingBlock,
8723                                                       bool ControlsExit) {
8724   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
8725 
8726   // Give up if the exit is the default dest of a switch.
8727   if (Switch->getDefaultDest() == ExitingBlock)
8728     return getCouldNotCompute();
8729 
8730   assert(L->contains(Switch->getDefaultDest()) &&
8731          "Default case must not exit the loop!");
8732   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
8733   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
8734 
8735   // while (X != Y) --> while (X-Y != 0)
8736   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
8737   if (EL.hasAnyInfo())
8738     return EL;
8739 
8740   return getCouldNotCompute();
8741 }
8742 
8743 static ConstantInt *
8744 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
8745                                 ScalarEvolution &SE) {
8746   const SCEV *InVal = SE.getConstant(C);
8747   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
8748   assert(isa<SCEVConstant>(Val) &&
8749          "Evaluation of SCEV at constant didn't fold correctly?");
8750   return cast<SCEVConstant>(Val)->getValue();
8751 }
8752 
8753 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
8754     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
8755   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
8756   if (!RHS)
8757     return getCouldNotCompute();
8758 
8759   const BasicBlock *Latch = L->getLoopLatch();
8760   if (!Latch)
8761     return getCouldNotCompute();
8762 
8763   const BasicBlock *Predecessor = L->getLoopPredecessor();
8764   if (!Predecessor)
8765     return getCouldNotCompute();
8766 
8767   // Return true if V is of the form "LHS `shift_op` <positive constant>".
8768   // Return LHS in OutLHS and shift_opt in OutOpCode.
8769   auto MatchPositiveShift =
8770       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
8771 
8772     using namespace PatternMatch;
8773 
8774     ConstantInt *ShiftAmt;
8775     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8776       OutOpCode = Instruction::LShr;
8777     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8778       OutOpCode = Instruction::AShr;
8779     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
8780       OutOpCode = Instruction::Shl;
8781     else
8782       return false;
8783 
8784     return ShiftAmt->getValue().isStrictlyPositive();
8785   };
8786 
8787   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
8788   //
8789   // loop:
8790   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
8791   //   %iv.shifted = lshr i32 %iv, <positive constant>
8792   //
8793   // Return true on a successful match.  Return the corresponding PHI node (%iv
8794   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
8795   auto MatchShiftRecurrence =
8796       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
8797     Optional<Instruction::BinaryOps> PostShiftOpCode;
8798 
8799     {
8800       Instruction::BinaryOps OpC;
8801       Value *V;
8802 
8803       // If we encounter a shift instruction, "peel off" the shift operation,
8804       // and remember that we did so.  Later when we inspect %iv's backedge
8805       // value, we will make sure that the backedge value uses the same
8806       // operation.
8807       //
8808       // Note: the peeled shift operation does not have to be the same
8809       // instruction as the one feeding into the PHI's backedge value.  We only
8810       // really care about it being the same *kind* of shift instruction --
8811       // that's all that is required for our later inferences to hold.
8812       if (MatchPositiveShift(LHS, V, OpC)) {
8813         PostShiftOpCode = OpC;
8814         LHS = V;
8815       }
8816     }
8817 
8818     PNOut = dyn_cast<PHINode>(LHS);
8819     if (!PNOut || PNOut->getParent() != L->getHeader())
8820       return false;
8821 
8822     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
8823     Value *OpLHS;
8824 
8825     return
8826         // The backedge value for the PHI node must be a shift by a positive
8827         // amount
8828         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
8829 
8830         // of the PHI node itself
8831         OpLHS == PNOut &&
8832 
8833         // and the kind of shift should be match the kind of shift we peeled
8834         // off, if any.
8835         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
8836   };
8837 
8838   PHINode *PN;
8839   Instruction::BinaryOps OpCode;
8840   if (!MatchShiftRecurrence(LHS, PN, OpCode))
8841     return getCouldNotCompute();
8842 
8843   const DataLayout &DL = getDataLayout();
8844 
8845   // The key rationale for this optimization is that for some kinds of shift
8846   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
8847   // within a finite number of iterations.  If the condition guarding the
8848   // backedge (in the sense that the backedge is taken if the condition is true)
8849   // is false for the value the shift recurrence stabilizes to, then we know
8850   // that the backedge is taken only a finite number of times.
8851 
8852   ConstantInt *StableValue = nullptr;
8853   switch (OpCode) {
8854   default:
8855     llvm_unreachable("Impossible case!");
8856 
8857   case Instruction::AShr: {
8858     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
8859     // bitwidth(K) iterations.
8860     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
8861     KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
8862                                        Predecessor->getTerminator(), &DT);
8863     auto *Ty = cast<IntegerType>(RHS->getType());
8864     if (Known.isNonNegative())
8865       StableValue = ConstantInt::get(Ty, 0);
8866     else if (Known.isNegative())
8867       StableValue = ConstantInt::get(Ty, -1, true);
8868     else
8869       return getCouldNotCompute();
8870 
8871     break;
8872   }
8873   case Instruction::LShr:
8874   case Instruction::Shl:
8875     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
8876     // stabilize to 0 in at most bitwidth(K) iterations.
8877     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
8878     break;
8879   }
8880 
8881   auto *Result =
8882       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
8883   assert(Result->getType()->isIntegerTy(1) &&
8884          "Otherwise cannot be an operand to a branch instruction");
8885 
8886   if (Result->isZeroValue()) {
8887     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8888     const SCEV *UpperBound =
8889         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
8890     return ExitLimit(getCouldNotCompute(), UpperBound, false);
8891   }
8892 
8893   return getCouldNotCompute();
8894 }
8895 
8896 /// Return true if we can constant fold an instruction of the specified type,
8897 /// assuming that all operands were constants.
8898 static bool CanConstantFold(const Instruction *I) {
8899   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8900       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8901       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8902     return true;
8903 
8904   if (const CallInst *CI = dyn_cast<CallInst>(I))
8905     if (const Function *F = CI->getCalledFunction())
8906       return canConstantFoldCallTo(CI, F);
8907   return false;
8908 }
8909 
8910 /// Determine whether this instruction can constant evolve within this loop
8911 /// assuming its operands can all constant evolve.
8912 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8913   // An instruction outside of the loop can't be derived from a loop PHI.
8914   if (!L->contains(I)) return false;
8915 
8916   if (isa<PHINode>(I)) {
8917     // We don't currently keep track of the control flow needed to evaluate
8918     // PHIs, so we cannot handle PHIs inside of loops.
8919     return L->getHeader() == I->getParent();
8920   }
8921 
8922   // If we won't be able to constant fold this expression even if the operands
8923   // are constants, bail early.
8924   return CanConstantFold(I);
8925 }
8926 
8927 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8928 /// recursing through each instruction operand until reaching a loop header phi.
8929 static PHINode *
8930 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8931                                DenseMap<Instruction *, PHINode *> &PHIMap,
8932                                unsigned Depth) {
8933   if (Depth > MaxConstantEvolvingDepth)
8934     return nullptr;
8935 
8936   // Otherwise, we can evaluate this instruction if all of its operands are
8937   // constant or derived from a PHI node themselves.
8938   PHINode *PHI = nullptr;
8939   for (Value *Op : UseInst->operands()) {
8940     if (isa<Constant>(Op)) continue;
8941 
8942     Instruction *OpInst = dyn_cast<Instruction>(Op);
8943     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8944 
8945     PHINode *P = dyn_cast<PHINode>(OpInst);
8946     if (!P)
8947       // If this operand is already visited, reuse the prior result.
8948       // We may have P != PHI if this is the deepest point at which the
8949       // inconsistent paths meet.
8950       P = PHIMap.lookup(OpInst);
8951     if (!P) {
8952       // Recurse and memoize the results, whether a phi is found or not.
8953       // This recursive call invalidates pointers into PHIMap.
8954       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8955       PHIMap[OpInst] = P;
8956     }
8957     if (!P)
8958       return nullptr;  // Not evolving from PHI
8959     if (PHI && PHI != P)
8960       return nullptr;  // Evolving from multiple different PHIs.
8961     PHI = P;
8962   }
8963   // This is a expression evolving from a constant PHI!
8964   return PHI;
8965 }
8966 
8967 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8968 /// in the loop that V is derived from.  We allow arbitrary operations along the
8969 /// way, but the operands of an operation must either be constants or a value
8970 /// derived from a constant PHI.  If this expression does not fit with these
8971 /// constraints, return null.
8972 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8973   Instruction *I = dyn_cast<Instruction>(V);
8974   if (!I || !canConstantEvolve(I, L)) return nullptr;
8975 
8976   if (PHINode *PN = dyn_cast<PHINode>(I))
8977     return PN;
8978 
8979   // Record non-constant instructions contained by the loop.
8980   DenseMap<Instruction *, PHINode *> PHIMap;
8981   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8982 }
8983 
8984 /// EvaluateExpression - Given an expression that passes the
8985 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8986 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8987 /// reason, return null.
8988 static Constant *EvaluateExpression(Value *V, const Loop *L,
8989                                     DenseMap<Instruction *, Constant *> &Vals,
8990                                     const DataLayout &DL,
8991                                     const TargetLibraryInfo *TLI) {
8992   // Convenient constant check, but redundant for recursive calls.
8993   if (Constant *C = dyn_cast<Constant>(V)) return C;
8994   Instruction *I = dyn_cast<Instruction>(V);
8995   if (!I) return nullptr;
8996 
8997   if (Constant *C = Vals.lookup(I)) return C;
8998 
8999   // An instruction inside the loop depends on a value outside the loop that we
9000   // weren't given a mapping for, or a value such as a call inside the loop.
9001   if (!canConstantEvolve(I, L)) return nullptr;
9002 
9003   // An unmapped PHI can be due to a branch or another loop inside this loop,
9004   // or due to this not being the initial iteration through a loop where we
9005   // couldn't compute the evolution of this particular PHI last time.
9006   if (isa<PHINode>(I)) return nullptr;
9007 
9008   std::vector<Constant*> Operands(I->getNumOperands());
9009 
9010   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9011     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9012     if (!Operand) {
9013       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9014       if (!Operands[i]) return nullptr;
9015       continue;
9016     }
9017     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9018     Vals[Operand] = C;
9019     if (!C) return nullptr;
9020     Operands[i] = C;
9021   }
9022 
9023   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9024     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9025                                            Operands[1], DL, TLI);
9026   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9027     if (!LI->isVolatile())
9028       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
9029   }
9030   return ConstantFoldInstOperands(I, Operands, DL, TLI);
9031 }
9032 
9033 
9034 // If every incoming value to PN except the one for BB is a specific Constant,
9035 // return that, else return nullptr.
9036 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9037   Constant *IncomingVal = nullptr;
9038 
9039   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9040     if (PN->getIncomingBlock(i) == BB)
9041       continue;
9042 
9043     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9044     if (!CurrentVal)
9045       return nullptr;
9046 
9047     if (IncomingVal != CurrentVal) {
9048       if (IncomingVal)
9049         return nullptr;
9050       IncomingVal = CurrentVal;
9051     }
9052   }
9053 
9054   return IncomingVal;
9055 }
9056 
9057 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9058 /// in the header of its containing loop, we know the loop executes a
9059 /// constant number of times, and the PHI node is just a recurrence
9060 /// involving constants, fold it.
9061 Constant *
9062 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9063                                                    const APInt &BEs,
9064                                                    const Loop *L) {
9065   auto I = ConstantEvolutionLoopExitValue.find(PN);
9066   if (I != ConstantEvolutionLoopExitValue.end())
9067     return I->second;
9068 
9069   if (BEs.ugt(MaxBruteForceIterations))
9070     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
9071 
9072   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9073 
9074   DenseMap<Instruction *, Constant *> CurrentIterVals;
9075   BasicBlock *Header = L->getHeader();
9076   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9077 
9078   BasicBlock *Latch = L->getLoopLatch();
9079   if (!Latch)
9080     return nullptr;
9081 
9082   for (PHINode &PHI : Header->phis()) {
9083     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9084       CurrentIterVals[&PHI] = StartCST;
9085   }
9086   if (!CurrentIterVals.count(PN))
9087     return RetVal = nullptr;
9088 
9089   Value *BEValue = PN->getIncomingValueForBlock(Latch);
9090 
9091   // Execute the loop symbolically to determine the exit value.
9092   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9093          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9094 
9095   unsigned NumIterations = BEs.getZExtValue(); // must be in range
9096   unsigned IterationNum = 0;
9097   const DataLayout &DL = getDataLayout();
9098   for (; ; ++IterationNum) {
9099     if (IterationNum == NumIterations)
9100       return RetVal = CurrentIterVals[PN];  // Got exit value!
9101 
9102     // Compute the value of the PHIs for the next iteration.
9103     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9104     DenseMap<Instruction *, Constant *> NextIterVals;
9105     Constant *NextPHI =
9106         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9107     if (!NextPHI)
9108       return nullptr;        // Couldn't evaluate!
9109     NextIterVals[PN] = NextPHI;
9110 
9111     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9112 
9113     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
9114     // cease to be able to evaluate one of them or if they stop evolving,
9115     // because that doesn't necessarily prevent us from computing PN.
9116     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9117     for (const auto &I : CurrentIterVals) {
9118       PHINode *PHI = dyn_cast<PHINode>(I.first);
9119       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9120       PHIsToCompute.emplace_back(PHI, I.second);
9121     }
9122     // We use two distinct loops because EvaluateExpression may invalidate any
9123     // iterators into CurrentIterVals.
9124     for (const auto &I : PHIsToCompute) {
9125       PHINode *PHI = I.first;
9126       Constant *&NextPHI = NextIterVals[PHI];
9127       if (!NextPHI) {   // Not already computed.
9128         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9129         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9130       }
9131       if (NextPHI != I.second)
9132         StoppedEvolving = false;
9133     }
9134 
9135     // If all entries in CurrentIterVals == NextIterVals then we can stop
9136     // iterating, the loop can't continue to change.
9137     if (StoppedEvolving)
9138       return RetVal = CurrentIterVals[PN];
9139 
9140     CurrentIterVals.swap(NextIterVals);
9141   }
9142 }
9143 
9144 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9145                                                           Value *Cond,
9146                                                           bool ExitWhen) {
9147   PHINode *PN = getConstantEvolvingPHI(Cond, L);
9148   if (!PN) return getCouldNotCompute();
9149 
9150   // If the loop is canonicalized, the PHI will have exactly two entries.
9151   // That's the only form we support here.
9152   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9153 
9154   DenseMap<Instruction *, Constant *> CurrentIterVals;
9155   BasicBlock *Header = L->getHeader();
9156   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9157 
9158   BasicBlock *Latch = L->getLoopLatch();
9159   assert(Latch && "Should follow from NumIncomingValues == 2!");
9160 
9161   for (PHINode &PHI : Header->phis()) {
9162     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9163       CurrentIterVals[&PHI] = StartCST;
9164   }
9165   if (!CurrentIterVals.count(PN))
9166     return getCouldNotCompute();
9167 
9168   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
9169   // the loop symbolically to determine when the condition gets a value of
9170   // "ExitWhen".
9171   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
9172   const DataLayout &DL = getDataLayout();
9173   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9174     auto *CondVal = dyn_cast_or_null<ConstantInt>(
9175         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9176 
9177     // Couldn't symbolically evaluate.
9178     if (!CondVal) return getCouldNotCompute();
9179 
9180     if (CondVal->getValue() == uint64_t(ExitWhen)) {
9181       ++NumBruteForceTripCountsComputed;
9182       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9183     }
9184 
9185     // Update all the PHI nodes for the next iteration.
9186     DenseMap<Instruction *, Constant *> NextIterVals;
9187 
9188     // Create a list of which PHIs we need to compute. We want to do this before
9189     // calling EvaluateExpression on them because that may invalidate iterators
9190     // into CurrentIterVals.
9191     SmallVector<PHINode *, 8> PHIsToCompute;
9192     for (const auto &I : CurrentIterVals) {
9193       PHINode *PHI = dyn_cast<PHINode>(I.first);
9194       if (!PHI || PHI->getParent() != Header) continue;
9195       PHIsToCompute.push_back(PHI);
9196     }
9197     for (PHINode *PHI : PHIsToCompute) {
9198       Constant *&NextPHI = NextIterVals[PHI];
9199       if (NextPHI) continue;    // Already computed!
9200 
9201       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9202       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9203     }
9204     CurrentIterVals.swap(NextIterVals);
9205   }
9206 
9207   // Too many iterations were needed to evaluate.
9208   return getCouldNotCompute();
9209 }
9210 
9211 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9212   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9213       ValuesAtScopes[V];
9214   // Check to see if we've folded this expression at this loop before.
9215   for (auto &LS : Values)
9216     if (LS.first == L)
9217       return LS.second ? LS.second : V;
9218 
9219   Values.emplace_back(L, nullptr);
9220 
9221   // Otherwise compute it.
9222   const SCEV *C = computeSCEVAtScope(V, L);
9223   for (auto &LS : reverse(ValuesAtScopes[V]))
9224     if (LS.first == L) {
9225       LS.second = C;
9226       if (!isa<SCEVConstant>(C))
9227         ValuesAtScopesUsers[C].push_back({L, V});
9228       break;
9229     }
9230   return C;
9231 }
9232 
9233 /// This builds up a Constant using the ConstantExpr interface.  That way, we
9234 /// will return Constants for objects which aren't represented by a
9235 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9236 /// Returns NULL if the SCEV isn't representable as a Constant.
9237 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9238   switch (V->getSCEVType()) {
9239   case scCouldNotCompute:
9240   case scAddRecExpr:
9241     return nullptr;
9242   case scConstant:
9243     return cast<SCEVConstant>(V)->getValue();
9244   case scUnknown:
9245     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9246   case scSignExtend: {
9247     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9248     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9249       return ConstantExpr::getSExt(CastOp, SS->getType());
9250     return nullptr;
9251   }
9252   case scZeroExtend: {
9253     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9254     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9255       return ConstantExpr::getZExt(CastOp, SZ->getType());
9256     return nullptr;
9257   }
9258   case scPtrToInt: {
9259     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9260     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9261       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9262 
9263     return nullptr;
9264   }
9265   case scTruncate: {
9266     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9267     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9268       return ConstantExpr::getTrunc(CastOp, ST->getType());
9269     return nullptr;
9270   }
9271   case scAddExpr: {
9272     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9273     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
9274       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
9275         unsigned AS = PTy->getAddressSpace();
9276         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9277         C = ConstantExpr::getBitCast(C, DestPtrTy);
9278       }
9279       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
9280         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
9281         if (!C2)
9282           return nullptr;
9283 
9284         // First pointer!
9285         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
9286           unsigned AS = C2->getType()->getPointerAddressSpace();
9287           std::swap(C, C2);
9288           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
9289           // The offsets have been converted to bytes.  We can add bytes to an
9290           // i8* by GEP with the byte count in the first index.
9291           C = ConstantExpr::getBitCast(C, DestPtrTy);
9292         }
9293 
9294         // Don't bother trying to sum two pointers. We probably can't
9295         // statically compute a load that results from it anyway.
9296         if (C2->getType()->isPointerTy())
9297           return nullptr;
9298 
9299         if (C->getType()->isPointerTy()) {
9300           C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9301                                              C, C2);
9302         } else {
9303           C = ConstantExpr::getAdd(C, C2);
9304         }
9305       }
9306       return C;
9307     }
9308     return nullptr;
9309   }
9310   case scMulExpr: {
9311     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9312     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
9313       // Don't bother with pointers at all.
9314       if (C->getType()->isPointerTy())
9315         return nullptr;
9316       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
9317         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
9318         if (!C2 || C2->getType()->isPointerTy())
9319           return nullptr;
9320         C = ConstantExpr::getMul(C, C2);
9321       }
9322       return C;
9323     }
9324     return nullptr;
9325   }
9326   case scUDivExpr: {
9327     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
9328     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
9329       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
9330         if (LHS->getType() == RHS->getType())
9331           return ConstantExpr::getUDiv(LHS, RHS);
9332     return nullptr;
9333   }
9334   case scSMaxExpr:
9335   case scUMaxExpr:
9336   case scSMinExpr:
9337   case scUMinExpr:
9338   case scSequentialUMinExpr:
9339     return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9340   }
9341   llvm_unreachable("Unknown SCEV kind!");
9342 }
9343 
9344 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9345   if (isa<SCEVConstant>(V)) return V;
9346 
9347   // If this instruction is evolved from a constant-evolving PHI, compute the
9348   // exit value from the loop without using SCEVs.
9349   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
9350     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
9351       if (PHINode *PN = dyn_cast<PHINode>(I)) {
9352         const Loop *CurrLoop = this->LI[I->getParent()];
9353         // Looking for loop exit value.
9354         if (CurrLoop && CurrLoop->getParentLoop() == L &&
9355             PN->getParent() == CurrLoop->getHeader()) {
9356           // Okay, there is no closed form solution for the PHI node.  Check
9357           // to see if the loop that contains it has a known backedge-taken
9358           // count.  If so, we may be able to force computation of the exit
9359           // value.
9360           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9361           // This trivial case can show up in some degenerate cases where
9362           // the incoming IR has not yet been fully simplified.
9363           if (BackedgeTakenCount->isZero()) {
9364             Value *InitValue = nullptr;
9365             bool MultipleInitValues = false;
9366             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9367               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9368                 if (!InitValue)
9369                   InitValue = PN->getIncomingValue(i);
9370                 else if (InitValue != PN->getIncomingValue(i)) {
9371                   MultipleInitValues = true;
9372                   break;
9373                 }
9374               }
9375             }
9376             if (!MultipleInitValues && InitValue)
9377               return getSCEV(InitValue);
9378           }
9379           // Do we have a loop invariant value flowing around the backedge
9380           // for a loop which must execute the backedge?
9381           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9382               isKnownPositive(BackedgeTakenCount) &&
9383               PN->getNumIncomingValues() == 2) {
9384 
9385             unsigned InLoopPred =
9386                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9387             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9388             if (CurrLoop->isLoopInvariant(BackedgeVal))
9389               return getSCEV(BackedgeVal);
9390           }
9391           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9392             // Okay, we know how many times the containing loop executes.  If
9393             // this is a constant evolving PHI node, get the final value at
9394             // the specified iteration number.
9395             Constant *RV = getConstantEvolutionLoopExitValue(
9396                 PN, BTCC->getAPInt(), CurrLoop);
9397             if (RV) return getSCEV(RV);
9398           }
9399         }
9400 
9401         // If there is a single-input Phi, evaluate it at our scope. If we can
9402         // prove that this replacement does not break LCSSA form, use new value.
9403         if (PN->getNumOperands() == 1) {
9404           const SCEV *Input = getSCEV(PN->getOperand(0));
9405           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
9406           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
9407           // for the simplest case just support constants.
9408           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
9409         }
9410       }
9411 
9412       // Okay, this is an expression that we cannot symbolically evaluate
9413       // into a SCEV.  Check to see if it's possible to symbolically evaluate
9414       // the arguments into constants, and if so, try to constant propagate the
9415       // result.  This is particularly useful for computing loop exit values.
9416       if (CanConstantFold(I)) {
9417         SmallVector<Constant *, 4> Operands;
9418         bool MadeImprovement = false;
9419         for (Value *Op : I->operands()) {
9420           if (Constant *C = dyn_cast<Constant>(Op)) {
9421             Operands.push_back(C);
9422             continue;
9423           }
9424 
9425           // If any of the operands is non-constant and if they are
9426           // non-integer and non-pointer, don't even try to analyze them
9427           // with scev techniques.
9428           if (!isSCEVable(Op->getType()))
9429             return V;
9430 
9431           const SCEV *OrigV = getSCEV(Op);
9432           const SCEV *OpV = getSCEVAtScope(OrigV, L);
9433           MadeImprovement |= OrigV != OpV;
9434 
9435           Constant *C = BuildConstantFromSCEV(OpV);
9436           if (!C) return V;
9437           if (C->getType() != Op->getType())
9438             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
9439                                                               Op->getType(),
9440                                                               false),
9441                                       C, Op->getType());
9442           Operands.push_back(C);
9443         }
9444 
9445         // Check to see if getSCEVAtScope actually made an improvement.
9446         if (MadeImprovement) {
9447           Constant *C = nullptr;
9448           const DataLayout &DL = getDataLayout();
9449           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
9450             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
9451                                                 Operands[1], DL, &TLI);
9452           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
9453             if (!Load->isVolatile())
9454               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
9455                                                DL);
9456           } else
9457             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9458           if (!C) return V;
9459           return getSCEV(C);
9460         }
9461       }
9462     }
9463 
9464     // This is some other type of SCEVUnknown, just return it.
9465     return V;
9466   }
9467 
9468   if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) {
9469     const auto *Comm = cast<SCEVNAryExpr>(V);
9470     // Avoid performing the look-up in the common case where the specified
9471     // expression has no loop-variant portions.
9472     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
9473       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9474       if (OpAtScope != Comm->getOperand(i)) {
9475         // Okay, at least one of these operands is loop variant but might be
9476         // foldable.  Build a new instance of the folded commutative expression.
9477         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
9478                                             Comm->op_begin()+i);
9479         NewOps.push_back(OpAtScope);
9480 
9481         for (++i; i != e; ++i) {
9482           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
9483           NewOps.push_back(OpAtScope);
9484         }
9485         if (isa<SCEVAddExpr>(Comm))
9486           return getAddExpr(NewOps, Comm->getNoWrapFlags());
9487         if (isa<SCEVMulExpr>(Comm))
9488           return getMulExpr(NewOps, Comm->getNoWrapFlags());
9489         if (isa<SCEVMinMaxExpr>(Comm))
9490           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
9491         if (isa<SCEVSequentialMinMaxExpr>(Comm))
9492           return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps);
9493         llvm_unreachable("Unknown commutative / sequential min/max SCEV type!");
9494       }
9495     }
9496     // If we got here, all operands are loop invariant.
9497     return Comm;
9498   }
9499 
9500   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
9501     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
9502     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
9503     if (LHS == Div->getLHS() && RHS == Div->getRHS())
9504       return Div;   // must be loop invariant
9505     return getUDivExpr(LHS, RHS);
9506   }
9507 
9508   // If this is a loop recurrence for a loop that does not contain L, then we
9509   // are dealing with the final value computed by the loop.
9510   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
9511     // First, attempt to evaluate each operand.
9512     // Avoid performing the look-up in the common case where the specified
9513     // expression has no loop-variant portions.
9514     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9515       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9516       if (OpAtScope == AddRec->getOperand(i))
9517         continue;
9518 
9519       // Okay, at least one of these operands is loop variant but might be
9520       // foldable.  Build a new instance of the folded commutative expression.
9521       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
9522                                           AddRec->op_begin()+i);
9523       NewOps.push_back(OpAtScope);
9524       for (++i; i != e; ++i)
9525         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9526 
9527       const SCEV *FoldedRec =
9528         getAddRecExpr(NewOps, AddRec->getLoop(),
9529                       AddRec->getNoWrapFlags(SCEV::FlagNW));
9530       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9531       // The addrec may be folded to a nonrecurrence, for example, if the
9532       // induction variable is multiplied by zero after constant folding. Go
9533       // ahead and return the folded value.
9534       if (!AddRec)
9535         return FoldedRec;
9536       break;
9537     }
9538 
9539     // If the scope is outside the addrec's loop, evaluate it by using the
9540     // loop exit value of the addrec.
9541     if (!AddRec->getLoop()->contains(L)) {
9542       // To evaluate this recurrence, we need to know how many times the AddRec
9543       // loop iterates.  Compute this now.
9544       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9545       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
9546 
9547       // Then, evaluate the AddRec.
9548       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9549     }
9550 
9551     return AddRec;
9552   }
9553 
9554   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
9555     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
9556     if (Op == Cast->getOperand())
9557       return Cast;  // must be loop invariant
9558     return getCastExpr(Cast->getSCEVType(), Op, Cast->getType());
9559   }
9560 
9561   llvm_unreachable("Unknown SCEV type!");
9562 }
9563 
9564 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9565   return getSCEVAtScope(getSCEV(V), L);
9566 }
9567 
9568 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9569   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9570     return stripInjectiveFunctions(ZExt->getOperand());
9571   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9572     return stripInjectiveFunctions(SExt->getOperand());
9573   return S;
9574 }
9575 
9576 /// Finds the minimum unsigned root of the following equation:
9577 ///
9578 ///     A * X = B (mod N)
9579 ///
9580 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9581 /// A and B isn't important.
9582 ///
9583 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9584 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9585                                                ScalarEvolution &SE) {
9586   uint32_t BW = A.getBitWidth();
9587   assert(BW == SE.getTypeSizeInBits(B->getType()));
9588   assert(A != 0 && "A must be non-zero.");
9589 
9590   // 1. D = gcd(A, N)
9591   //
9592   // The gcd of A and N may have only one prime factor: 2. The number of
9593   // trailing zeros in A is its multiplicity
9594   uint32_t Mult2 = A.countTrailingZeros();
9595   // D = 2^Mult2
9596 
9597   // 2. Check if B is divisible by D.
9598   //
9599   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9600   // is not less than multiplicity of this prime factor for D.
9601   if (SE.GetMinTrailingZeros(B) < Mult2)
9602     return SE.getCouldNotCompute();
9603 
9604   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9605   // modulo (N / D).
9606   //
9607   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9608   // (N / D) in general. The inverse itself always fits into BW bits, though,
9609   // so we immediately truncate it.
9610   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
9611   APInt Mod(BW + 1, 0);
9612   Mod.setBit(BW - Mult2);  // Mod = N / D
9613   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
9614 
9615   // 4. Compute the minimum unsigned root of the equation:
9616   // I * (B / D) mod (N / D)
9617   // To simplify the computation, we factor out the divide by D:
9618   // (I * B mod N) / D
9619   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
9620   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
9621 }
9622 
9623 /// For a given quadratic addrec, generate coefficients of the corresponding
9624 /// quadratic equation, multiplied by a common value to ensure that they are
9625 /// integers.
9626 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
9627 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
9628 /// were multiplied by, and BitWidth is the bit width of the original addrec
9629 /// coefficients.
9630 /// This function returns None if the addrec coefficients are not compile-
9631 /// time constants.
9632 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
9633 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
9634   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
9635   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
9636   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
9637   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
9638   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
9639                     << *AddRec << '\n');
9640 
9641   // We currently can only solve this if the coefficients are constants.
9642   if (!LC || !MC || !NC) {
9643     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
9644     return None;
9645   }
9646 
9647   APInt L = LC->getAPInt();
9648   APInt M = MC->getAPInt();
9649   APInt N = NC->getAPInt();
9650   assert(!N.isZero() && "This is not a quadratic addrec");
9651 
9652   unsigned BitWidth = LC->getAPInt().getBitWidth();
9653   unsigned NewWidth = BitWidth + 1;
9654   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
9655                     << BitWidth << '\n');
9656   // The sign-extension (as opposed to a zero-extension) here matches the
9657   // extension used in SolveQuadraticEquationWrap (with the same motivation).
9658   N = N.sext(NewWidth);
9659   M = M.sext(NewWidth);
9660   L = L.sext(NewWidth);
9661 
9662   // The increments are M, M+N, M+2N, ..., so the accumulated values are
9663   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
9664   //   L+M, L+2M+N, L+3M+3N, ...
9665   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
9666   //
9667   // The equation Acc = 0 is then
9668   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
9669   // In a quadratic form it becomes:
9670   //   N n^2 + (2M-N) n + 2L = 0.
9671 
9672   APInt A = N;
9673   APInt B = 2 * M - A;
9674   APInt C = 2 * L;
9675   APInt T = APInt(NewWidth, 2);
9676   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
9677                     << "x + " << C << ", coeff bw: " << NewWidth
9678                     << ", multiplied by " << T << '\n');
9679   return std::make_tuple(A, B, C, T, BitWidth);
9680 }
9681 
9682 /// Helper function to compare optional APInts:
9683 /// (a) if X and Y both exist, return min(X, Y),
9684 /// (b) if neither X nor Y exist, return None,
9685 /// (c) if exactly one of X and Y exists, return that value.
9686 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
9687   if (X.hasValue() && Y.hasValue()) {
9688     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
9689     APInt XW = X->sextOrSelf(W);
9690     APInt YW = Y->sextOrSelf(W);
9691     return XW.slt(YW) ? *X : *Y;
9692   }
9693   if (!X.hasValue() && !Y.hasValue())
9694     return None;
9695   return X.hasValue() ? *X : *Y;
9696 }
9697 
9698 /// Helper function to truncate an optional APInt to a given BitWidth.
9699 /// When solving addrec-related equations, it is preferable to return a value
9700 /// that has the same bit width as the original addrec's coefficients. If the
9701 /// solution fits in the original bit width, truncate it (except for i1).
9702 /// Returning a value of a different bit width may inhibit some optimizations.
9703 ///
9704 /// In general, a solution to a quadratic equation generated from an addrec
9705 /// may require BW+1 bits, where BW is the bit width of the addrec's
9706 /// coefficients. The reason is that the coefficients of the quadratic
9707 /// equation are BW+1 bits wide (to avoid truncation when converting from
9708 /// the addrec to the equation).
9709 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
9710   if (!X.hasValue())
9711     return None;
9712   unsigned W = X->getBitWidth();
9713   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
9714     return X->trunc(BitWidth);
9715   return X;
9716 }
9717 
9718 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
9719 /// iterations. The values L, M, N are assumed to be signed, and they
9720 /// should all have the same bit widths.
9721 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
9722 /// where BW is the bit width of the addrec's coefficients.
9723 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
9724 /// returned as such, otherwise the bit width of the returned value may
9725 /// be greater than BW.
9726 ///
9727 /// This function returns None if
9728 /// (a) the addrec coefficients are not constant, or
9729 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
9730 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
9731 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
9732 static Optional<APInt>
9733 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
9734   APInt A, B, C, M;
9735   unsigned BitWidth;
9736   auto T = GetQuadraticEquation(AddRec);
9737   if (!T.hasValue())
9738     return None;
9739 
9740   std::tie(A, B, C, M, BitWidth) = *T;
9741   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
9742   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
9743   if (!X.hasValue())
9744     return None;
9745 
9746   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
9747   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
9748   if (!V->isZero())
9749     return None;
9750 
9751   return TruncIfPossible(X, BitWidth);
9752 }
9753 
9754 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
9755 /// iterations. The values M, N are assumed to be signed, and they
9756 /// should all have the same bit widths.
9757 /// Find the least n such that c(n) does not belong to the given range,
9758 /// while c(n-1) does.
9759 ///
9760 /// This function returns None if
9761 /// (a) the addrec coefficients are not constant, or
9762 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
9763 ///     bounds of the range.
9764 static Optional<APInt>
9765 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
9766                           const ConstantRange &Range, ScalarEvolution &SE) {
9767   assert(AddRec->getOperand(0)->isZero() &&
9768          "Starting value of addrec should be 0");
9769   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
9770                     << Range << ", addrec " << *AddRec << '\n');
9771   // This case is handled in getNumIterationsInRange. Here we can assume that
9772   // we start in the range.
9773   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
9774          "Addrec's initial value should be in range");
9775 
9776   APInt A, B, C, M;
9777   unsigned BitWidth;
9778   auto T = GetQuadraticEquation(AddRec);
9779   if (!T.hasValue())
9780     return None;
9781 
9782   // Be careful about the return value: there can be two reasons for not
9783   // returning an actual number. First, if no solutions to the equations
9784   // were found, and second, if the solutions don't leave the given range.
9785   // The first case means that the actual solution is "unknown", the second
9786   // means that it's known, but not valid. If the solution is unknown, we
9787   // cannot make any conclusions.
9788   // Return a pair: the optional solution and a flag indicating if the
9789   // solution was found.
9790   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
9791     // Solve for signed overflow and unsigned overflow, pick the lower
9792     // solution.
9793     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
9794                       << Bound << " (before multiplying by " << M << ")\n");
9795     Bound *= M; // The quadratic equation multiplier.
9796 
9797     Optional<APInt> SO = None;
9798     if (BitWidth > 1) {
9799       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9800                            "signed overflow\n");
9801       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
9802     }
9803     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
9804                          "unsigned overflow\n");
9805     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
9806                                                               BitWidth+1);
9807 
9808     auto LeavesRange = [&] (const APInt &X) {
9809       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
9810       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
9811       if (Range.contains(V0->getValue()))
9812         return false;
9813       // X should be at least 1, so X-1 is non-negative.
9814       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
9815       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
9816       if (Range.contains(V1->getValue()))
9817         return true;
9818       return false;
9819     };
9820 
9821     // If SolveQuadraticEquationWrap returns None, it means that there can
9822     // be a solution, but the function failed to find it. We cannot treat it
9823     // as "no solution".
9824     if (!SO.hasValue() || !UO.hasValue())
9825       return { None, false };
9826 
9827     // Check the smaller value first to see if it leaves the range.
9828     // At this point, both SO and UO must have values.
9829     Optional<APInt> Min = MinOptional(SO, UO);
9830     if (LeavesRange(*Min))
9831       return { Min, true };
9832     Optional<APInt> Max = Min == SO ? UO : SO;
9833     if (LeavesRange(*Max))
9834       return { Max, true };
9835 
9836     // Solutions were found, but were eliminated, hence the "true".
9837     return { None, true };
9838   };
9839 
9840   std::tie(A, B, C, M, BitWidth) = *T;
9841   // Lower bound is inclusive, subtract 1 to represent the exiting value.
9842   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
9843   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
9844   auto SL = SolveForBoundary(Lower);
9845   auto SU = SolveForBoundary(Upper);
9846   // If any of the solutions was unknown, no meaninigful conclusions can
9847   // be made.
9848   if (!SL.second || !SU.second)
9849     return None;
9850 
9851   // Claim: The correct solution is not some value between Min and Max.
9852   //
9853   // Justification: Assuming that Min and Max are different values, one of
9854   // them is when the first signed overflow happens, the other is when the
9855   // first unsigned overflow happens. Crossing the range boundary is only
9856   // possible via an overflow (treating 0 as a special case of it, modeling
9857   // an overflow as crossing k*2^W for some k).
9858   //
9859   // The interesting case here is when Min was eliminated as an invalid
9860   // solution, but Max was not. The argument is that if there was another
9861   // overflow between Min and Max, it would also have been eliminated if
9862   // it was considered.
9863   //
9864   // For a given boundary, it is possible to have two overflows of the same
9865   // type (signed/unsigned) without having the other type in between: this
9866   // can happen when the vertex of the parabola is between the iterations
9867   // corresponding to the overflows. This is only possible when the two
9868   // overflows cross k*2^W for the same k. In such case, if the second one
9869   // left the range (and was the first one to do so), the first overflow
9870   // would have to enter the range, which would mean that either we had left
9871   // the range before or that we started outside of it. Both of these cases
9872   // are contradictions.
9873   //
9874   // Claim: In the case where SolveForBoundary returns None, the correct
9875   // solution is not some value between the Max for this boundary and the
9876   // Min of the other boundary.
9877   //
9878   // Justification: Assume that we had such Max_A and Min_B corresponding
9879   // to range boundaries A and B and such that Max_A < Min_B. If there was
9880   // a solution between Max_A and Min_B, it would have to be caused by an
9881   // overflow corresponding to either A or B. It cannot correspond to B,
9882   // since Min_B is the first occurrence of such an overflow. If it
9883   // corresponded to A, it would have to be either a signed or an unsigned
9884   // overflow that is larger than both eliminated overflows for A. But
9885   // between the eliminated overflows and this overflow, the values would
9886   // cover the entire value space, thus crossing the other boundary, which
9887   // is a contradiction.
9888 
9889   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9890 }
9891 
9892 ScalarEvolution::ExitLimit
9893 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9894                               bool AllowPredicates) {
9895 
9896   // This is only used for loops with a "x != y" exit test. The exit condition
9897   // is now expressed as a single expression, V = x-y. So the exit test is
9898   // effectively V != 0.  We know and take advantage of the fact that this
9899   // expression only being used in a comparison by zero context.
9900 
9901   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9902   // If the value is a constant
9903   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9904     // If the value is already zero, the branch will execute zero times.
9905     if (C->getValue()->isZero()) return C;
9906     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9907   }
9908 
9909   const SCEVAddRecExpr *AddRec =
9910       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9911 
9912   if (!AddRec && AllowPredicates)
9913     // Try to make this an AddRec using runtime tests, in the first X
9914     // iterations of this loop, where X is the SCEV expression found by the
9915     // algorithm below.
9916     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9917 
9918   if (!AddRec || AddRec->getLoop() != L)
9919     return getCouldNotCompute();
9920 
9921   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9922   // the quadratic equation to solve it.
9923   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9924     // We can only use this value if the chrec ends up with an exact zero
9925     // value at this index.  When solving for "X*X != 5", for example, we
9926     // should not accept a root of 2.
9927     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9928       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9929       return ExitLimit(R, R, false, Predicates);
9930     }
9931     return getCouldNotCompute();
9932   }
9933 
9934   // Otherwise we can only handle this if it is affine.
9935   if (!AddRec->isAffine())
9936     return getCouldNotCompute();
9937 
9938   // If this is an affine expression, the execution count of this branch is
9939   // the minimum unsigned root of the following equation:
9940   //
9941   //     Start + Step*N = 0 (mod 2^BW)
9942   //
9943   // equivalent to:
9944   //
9945   //             Step*N = -Start (mod 2^BW)
9946   //
9947   // where BW is the common bit width of Start and Step.
9948 
9949   // Get the initial value for the loop.
9950   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9951   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9952 
9953   // For now we handle only constant steps.
9954   //
9955   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9956   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9957   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9958   // We have not yet seen any such cases.
9959   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9960   if (!StepC || StepC->getValue()->isZero())
9961     return getCouldNotCompute();
9962 
9963   // For positive steps (counting up until unsigned overflow):
9964   //   N = -Start/Step (as unsigned)
9965   // For negative steps (counting down to zero):
9966   //   N = Start/-Step
9967   // First compute the unsigned distance from zero in the direction of Step.
9968   bool CountDown = StepC->getAPInt().isNegative();
9969   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9970 
9971   // Handle unitary steps, which cannot wraparound.
9972   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9973   //   N = Distance (as unsigned)
9974   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9975     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9976     MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
9977 
9978     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9979     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9980     // case, and see if we can improve the bound.
9981     //
9982     // Explicitly handling this here is necessary because getUnsignedRange
9983     // isn't context-sensitive; it doesn't know that we only care about the
9984     // range inside the loop.
9985     const SCEV *Zero = getZero(Distance->getType());
9986     const SCEV *One = getOne(Distance->getType());
9987     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9988     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9989       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9990       // as "unsigned_max(Distance + 1) - 1".
9991       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9992       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9993     }
9994     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9995   }
9996 
9997   // If the condition controls loop exit (the loop exits only if the expression
9998   // is true) and the addition is no-wrap we can use unsigned divide to
9999   // compute the backedge count.  In this case, the step may not divide the
10000   // distance, but we don't care because if the condition is "missed" the loop
10001   // will have undefined behavior due to wrapping.
10002   if (ControlsExit && AddRec->hasNoSelfWrap() &&
10003       loopHasNoAbnormalExits(AddRec->getLoop())) {
10004     const SCEV *Exact =
10005         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10006     const SCEV *Max = getCouldNotCompute();
10007     if (Exact != getCouldNotCompute()) {
10008       APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10009       Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10010     }
10011     return ExitLimit(Exact, Max, false, Predicates);
10012   }
10013 
10014   // Solve the general equation.
10015   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10016                                                getNegativeSCEV(Start), *this);
10017 
10018   const SCEV *M = E;
10019   if (E != getCouldNotCompute()) {
10020     APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10021     M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10022   }
10023   return ExitLimit(E, M, false, Predicates);
10024 }
10025 
10026 ScalarEvolution::ExitLimit
10027 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10028   // Loops that look like: while (X == 0) are very strange indeed.  We don't
10029   // handle them yet except for the trivial case.  This could be expanded in the
10030   // future as needed.
10031 
10032   // If the value is a constant, check to see if it is known to be non-zero
10033   // already.  If so, the backedge will execute zero times.
10034   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10035     if (!C->getValue()->isZero())
10036       return getZero(C->getType());
10037     return getCouldNotCompute();  // Otherwise it will loop infinitely.
10038   }
10039 
10040   // We could implement others, but I really doubt anyone writes loops like
10041   // this, and if they did, they would already be constant folded.
10042   return getCouldNotCompute();
10043 }
10044 
10045 std::pair<const BasicBlock *, const BasicBlock *>
10046 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10047     const {
10048   // If the block has a unique predecessor, then there is no path from the
10049   // predecessor to the block that does not go through the direct edge
10050   // from the predecessor to the block.
10051   if (const BasicBlock *Pred = BB->getSinglePredecessor())
10052     return {Pred, BB};
10053 
10054   // A loop's header is defined to be a block that dominates the loop.
10055   // If the header has a unique predecessor outside the loop, it must be
10056   // a block that has exactly one successor that can reach the loop.
10057   if (const Loop *L = LI.getLoopFor(BB))
10058     return {L->getLoopPredecessor(), L->getHeader()};
10059 
10060   return {nullptr, nullptr};
10061 }
10062 
10063 /// SCEV structural equivalence is usually sufficient for testing whether two
10064 /// expressions are equal, however for the purposes of looking for a condition
10065 /// guarding a loop, it can be useful to be a little more general, since a
10066 /// front-end may have replicated the controlling expression.
10067 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10068   // Quick check to see if they are the same SCEV.
10069   if (A == B) return true;
10070 
10071   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10072     // Not all instructions that are "identical" compute the same value.  For
10073     // instance, two distinct alloca instructions allocating the same type are
10074     // identical and do not read memory; but compute distinct values.
10075     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10076   };
10077 
10078   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10079   // two different instructions with the same value. Check for this case.
10080   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10081     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10082       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10083         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10084           if (ComputesEqualValues(AI, BI))
10085             return true;
10086 
10087   // Otherwise assume they may have a different value.
10088   return false;
10089 }
10090 
10091 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10092                                            const SCEV *&LHS, const SCEV *&RHS,
10093                                            unsigned Depth,
10094                                            bool ControllingFiniteLoop) {
10095   bool Changed = false;
10096   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10097   // '0 != 0'.
10098   auto TrivialCase = [&](bool TriviallyTrue) {
10099     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10100     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10101     return true;
10102   };
10103   // If we hit the max recursion limit bail out.
10104   if (Depth >= 3)
10105     return false;
10106 
10107   // Canonicalize a constant to the right side.
10108   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10109     // Check for both operands constant.
10110     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10111       if (ConstantExpr::getICmp(Pred,
10112                                 LHSC->getValue(),
10113                                 RHSC->getValue())->isNullValue())
10114         return TrivialCase(false);
10115       else
10116         return TrivialCase(true);
10117     }
10118     // Otherwise swap the operands to put the constant on the right.
10119     std::swap(LHS, RHS);
10120     Pred = ICmpInst::getSwappedPredicate(Pred);
10121     Changed = true;
10122   }
10123 
10124   // If we're comparing an addrec with a value which is loop-invariant in the
10125   // addrec's loop, put the addrec on the left. Also make a dominance check,
10126   // as both operands could be addrecs loop-invariant in each other's loop.
10127   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10128     const Loop *L = AR->getLoop();
10129     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10130       std::swap(LHS, RHS);
10131       Pred = ICmpInst::getSwappedPredicate(Pred);
10132       Changed = true;
10133     }
10134   }
10135 
10136   // If there's a constant operand, canonicalize comparisons with boundary
10137   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10138   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10139     const APInt &RA = RC->getAPInt();
10140 
10141     bool SimplifiedByConstantRange = false;
10142 
10143     if (!ICmpInst::isEquality(Pred)) {
10144       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10145       if (ExactCR.isFullSet())
10146         return TrivialCase(true);
10147       else if (ExactCR.isEmptySet())
10148         return TrivialCase(false);
10149 
10150       APInt NewRHS;
10151       CmpInst::Predicate NewPred;
10152       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10153           ICmpInst::isEquality(NewPred)) {
10154         // We were able to convert an inequality to an equality.
10155         Pred = NewPred;
10156         RHS = getConstant(NewRHS);
10157         Changed = SimplifiedByConstantRange = true;
10158       }
10159     }
10160 
10161     if (!SimplifiedByConstantRange) {
10162       switch (Pred) {
10163       default:
10164         break;
10165       case ICmpInst::ICMP_EQ:
10166       case ICmpInst::ICMP_NE:
10167         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10168         if (!RA)
10169           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10170             if (const SCEVMulExpr *ME =
10171                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10172               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10173                   ME->getOperand(0)->isAllOnesValue()) {
10174                 RHS = AE->getOperand(1);
10175                 LHS = ME->getOperand(1);
10176                 Changed = true;
10177               }
10178         break;
10179 
10180 
10181         // The "Should have been caught earlier!" messages refer to the fact
10182         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10183         // should have fired on the corresponding cases, and canonicalized the
10184         // check to trivial case.
10185 
10186       case ICmpInst::ICMP_UGE:
10187         assert(!RA.isMinValue() && "Should have been caught earlier!");
10188         Pred = ICmpInst::ICMP_UGT;
10189         RHS = getConstant(RA - 1);
10190         Changed = true;
10191         break;
10192       case ICmpInst::ICMP_ULE:
10193         assert(!RA.isMaxValue() && "Should have been caught earlier!");
10194         Pred = ICmpInst::ICMP_ULT;
10195         RHS = getConstant(RA + 1);
10196         Changed = true;
10197         break;
10198       case ICmpInst::ICMP_SGE:
10199         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10200         Pred = ICmpInst::ICMP_SGT;
10201         RHS = getConstant(RA - 1);
10202         Changed = true;
10203         break;
10204       case ICmpInst::ICMP_SLE:
10205         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10206         Pred = ICmpInst::ICMP_SLT;
10207         RHS = getConstant(RA + 1);
10208         Changed = true;
10209         break;
10210       }
10211     }
10212   }
10213 
10214   // Check for obvious equality.
10215   if (HasSameValue(LHS, RHS)) {
10216     if (ICmpInst::isTrueWhenEqual(Pred))
10217       return TrivialCase(true);
10218     if (ICmpInst::isFalseWhenEqual(Pred))
10219       return TrivialCase(false);
10220   }
10221 
10222   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10223   // adding or subtracting 1 from one of the operands. This can be done for
10224   // one of two reasons:
10225   // 1) The range of the RHS does not include the (signed/unsigned) boundaries
10226   // 2) The loop is finite, with this comparison controlling the exit. Since the
10227   // loop is finite, the bound cannot include the corresponding boundary
10228   // (otherwise it would loop forever).
10229   switch (Pred) {
10230   case ICmpInst::ICMP_SLE:
10231     if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
10232       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10233                        SCEV::FlagNSW);
10234       Pred = ICmpInst::ICMP_SLT;
10235       Changed = true;
10236     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10237       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10238                        SCEV::FlagNSW);
10239       Pred = ICmpInst::ICMP_SLT;
10240       Changed = true;
10241     }
10242     break;
10243   case ICmpInst::ICMP_SGE:
10244     if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
10245       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10246                        SCEV::FlagNSW);
10247       Pred = ICmpInst::ICMP_SGT;
10248       Changed = true;
10249     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10250       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10251                        SCEV::FlagNSW);
10252       Pred = ICmpInst::ICMP_SGT;
10253       Changed = true;
10254     }
10255     break;
10256   case ICmpInst::ICMP_ULE:
10257     if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
10258       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10259                        SCEV::FlagNUW);
10260       Pred = ICmpInst::ICMP_ULT;
10261       Changed = true;
10262     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10263       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10264       Pred = ICmpInst::ICMP_ULT;
10265       Changed = true;
10266     }
10267     break;
10268   case ICmpInst::ICMP_UGE:
10269     if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
10270       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10271       Pred = ICmpInst::ICMP_UGT;
10272       Changed = true;
10273     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10274       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10275                        SCEV::FlagNUW);
10276       Pred = ICmpInst::ICMP_UGT;
10277       Changed = true;
10278     }
10279     break;
10280   default:
10281     break;
10282   }
10283 
10284   // TODO: More simplifications are possible here.
10285 
10286   // Recursively simplify until we either hit a recursion limit or nothing
10287   // changes.
10288   if (Changed)
10289     return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
10290                                 ControllingFiniteLoop);
10291 
10292   return Changed;
10293 }
10294 
10295 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10296   return getSignedRangeMax(S).isNegative();
10297 }
10298 
10299 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10300   return getSignedRangeMin(S).isStrictlyPositive();
10301 }
10302 
10303 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10304   return !getSignedRangeMin(S).isNegative();
10305 }
10306 
10307 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10308   return !getSignedRangeMax(S).isStrictlyPositive();
10309 }
10310 
10311 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10312   return getUnsignedRangeMin(S) != 0;
10313 }
10314 
10315 std::pair<const SCEV *, const SCEV *>
10316 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10317   // Compute SCEV on entry of loop L.
10318   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10319   if (Start == getCouldNotCompute())
10320     return { Start, Start };
10321   // Compute post increment SCEV for loop L.
10322   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10323   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10324   return { Start, PostInc };
10325 }
10326 
10327 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10328                                           const SCEV *LHS, const SCEV *RHS) {
10329   // First collect all loops.
10330   SmallPtrSet<const Loop *, 8> LoopsUsed;
10331   getUsedLoops(LHS, LoopsUsed);
10332   getUsedLoops(RHS, LoopsUsed);
10333 
10334   if (LoopsUsed.empty())
10335     return false;
10336 
10337   // Domination relationship must be a linear order on collected loops.
10338 #ifndef NDEBUG
10339   for (auto *L1 : LoopsUsed)
10340     for (auto *L2 : LoopsUsed)
10341       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10342               DT.dominates(L2->getHeader(), L1->getHeader())) &&
10343              "Domination relationship is not a linear order");
10344 #endif
10345 
10346   const Loop *MDL =
10347       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10348                         [&](const Loop *L1, const Loop *L2) {
10349          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10350        });
10351 
10352   // Get init and post increment value for LHS.
10353   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10354   // if LHS contains unknown non-invariant SCEV then bail out.
10355   if (SplitLHS.first == getCouldNotCompute())
10356     return false;
10357   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10358   // Get init and post increment value for RHS.
10359   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10360   // if RHS contains unknown non-invariant SCEV then bail out.
10361   if (SplitRHS.first == getCouldNotCompute())
10362     return false;
10363   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10364   // It is possible that init SCEV contains an invariant load but it does
10365   // not dominate MDL and is not available at MDL loop entry, so we should
10366   // check it here.
10367   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10368       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10369     return false;
10370 
10371   // It seems backedge guard check is faster than entry one so in some cases
10372   // it can speed up whole estimation by short circuit
10373   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10374                                      SplitRHS.second) &&
10375          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10376 }
10377 
10378 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10379                                        const SCEV *LHS, const SCEV *RHS) {
10380   // Canonicalize the inputs first.
10381   (void)SimplifyICmpOperands(Pred, LHS, RHS);
10382 
10383   if (isKnownViaInduction(Pred, LHS, RHS))
10384     return true;
10385 
10386   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10387     return true;
10388 
10389   // Otherwise see what can be done with some simple reasoning.
10390   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10391 }
10392 
10393 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10394                                                   const SCEV *LHS,
10395                                                   const SCEV *RHS) {
10396   if (isKnownPredicate(Pred, LHS, RHS))
10397     return true;
10398   else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10399     return false;
10400   return None;
10401 }
10402 
10403 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10404                                          const SCEV *LHS, const SCEV *RHS,
10405                                          const Instruction *CtxI) {
10406   // TODO: Analyze guards and assumes from Context's block.
10407   return isKnownPredicate(Pred, LHS, RHS) ||
10408          isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10409 }
10410 
10411 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred,
10412                                                     const SCEV *LHS,
10413                                                     const SCEV *RHS,
10414                                                     const Instruction *CtxI) {
10415   Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10416   if (KnownWithoutContext)
10417     return KnownWithoutContext;
10418 
10419   if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10420     return true;
10421   else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10422                                           ICmpInst::getInversePredicate(Pred),
10423                                           LHS, RHS))
10424     return false;
10425   return None;
10426 }
10427 
10428 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10429                                               const SCEVAddRecExpr *LHS,
10430                                               const SCEV *RHS) {
10431   const Loop *L = LHS->getLoop();
10432   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10433          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10434 }
10435 
10436 Optional<ScalarEvolution::MonotonicPredicateType>
10437 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10438                                            ICmpInst::Predicate Pred) {
10439   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10440 
10441 #ifndef NDEBUG
10442   // Verify an invariant: inverting the predicate should turn a monotonically
10443   // increasing change to a monotonically decreasing one, and vice versa.
10444   if (Result) {
10445     auto ResultSwapped =
10446         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10447 
10448     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
10449     assert(ResultSwapped.getValue() != Result.getValue() &&
10450            "monotonicity should flip as we flip the predicate");
10451   }
10452 #endif
10453 
10454   return Result;
10455 }
10456 
10457 Optional<ScalarEvolution::MonotonicPredicateType>
10458 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10459                                                ICmpInst::Predicate Pred) {
10460   // A zero step value for LHS means the induction variable is essentially a
10461   // loop invariant value. We don't really depend on the predicate actually
10462   // flipping from false to true (for increasing predicates, and the other way
10463   // around for decreasing predicates), all we care about is that *if* the
10464   // predicate changes then it only changes from false to true.
10465   //
10466   // A zero step value in itself is not very useful, but there may be places
10467   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10468   // as general as possible.
10469 
10470   // Only handle LE/LT/GE/GT predicates.
10471   if (!ICmpInst::isRelational(Pred))
10472     return None;
10473 
10474   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10475   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10476          "Should be greater or less!");
10477 
10478   // Check that AR does not wrap.
10479   if (ICmpInst::isUnsigned(Pred)) {
10480     if (!LHS->hasNoUnsignedWrap())
10481       return None;
10482     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10483   } else {
10484     assert(ICmpInst::isSigned(Pred) &&
10485            "Relational predicate is either signed or unsigned!");
10486     if (!LHS->hasNoSignedWrap())
10487       return None;
10488 
10489     const SCEV *Step = LHS->getStepRecurrence(*this);
10490 
10491     if (isKnownNonNegative(Step))
10492       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10493 
10494     if (isKnownNonPositive(Step))
10495       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10496 
10497     return None;
10498   }
10499 }
10500 
10501 Optional<ScalarEvolution::LoopInvariantPredicate>
10502 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10503                                            const SCEV *LHS, const SCEV *RHS,
10504                                            const Loop *L) {
10505 
10506   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10507   if (!isLoopInvariant(RHS, L)) {
10508     if (!isLoopInvariant(LHS, L))
10509       return None;
10510 
10511     std::swap(LHS, RHS);
10512     Pred = ICmpInst::getSwappedPredicate(Pred);
10513   }
10514 
10515   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10516   if (!ArLHS || ArLHS->getLoop() != L)
10517     return None;
10518 
10519   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10520   if (!MonotonicType)
10521     return None;
10522   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10523   // true as the loop iterates, and the backedge is control dependent on
10524   // "ArLHS `Pred` RHS" == true then we can reason as follows:
10525   //
10526   //   * if the predicate was false in the first iteration then the predicate
10527   //     is never evaluated again, since the loop exits without taking the
10528   //     backedge.
10529   //   * if the predicate was true in the first iteration then it will
10530   //     continue to be true for all future iterations since it is
10531   //     monotonically increasing.
10532   //
10533   // For both the above possibilities, we can replace the loop varying
10534   // predicate with its value on the first iteration of the loop (which is
10535   // loop invariant).
10536   //
10537   // A similar reasoning applies for a monotonically decreasing predicate, by
10538   // replacing true with false and false with true in the above two bullets.
10539   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10540   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10541 
10542   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10543     return None;
10544 
10545   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
10546 }
10547 
10548 Optional<ScalarEvolution::LoopInvariantPredicate>
10549 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10550     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10551     const Instruction *CtxI, const SCEV *MaxIter) {
10552   // Try to prove the following set of facts:
10553   // - The predicate is monotonic in the iteration space.
10554   // - If the check does not fail on the 1st iteration:
10555   //   - No overflow will happen during first MaxIter iterations;
10556   //   - It will not fail on the MaxIter'th iteration.
10557   // If the check does fail on the 1st iteration, we leave the loop and no
10558   // other checks matter.
10559 
10560   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10561   if (!isLoopInvariant(RHS, L)) {
10562     if (!isLoopInvariant(LHS, L))
10563       return None;
10564 
10565     std::swap(LHS, RHS);
10566     Pred = ICmpInst::getSwappedPredicate(Pred);
10567   }
10568 
10569   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
10570   if (!AR || AR->getLoop() != L)
10571     return None;
10572 
10573   // The predicate must be relational (i.e. <, <=, >=, >).
10574   if (!ICmpInst::isRelational(Pred))
10575     return None;
10576 
10577   // TODO: Support steps other than +/- 1.
10578   const SCEV *Step = AR->getStepRecurrence(*this);
10579   auto *One = getOne(Step->getType());
10580   auto *MinusOne = getNegativeSCEV(One);
10581   if (Step != One && Step != MinusOne)
10582     return None;
10583 
10584   // Type mismatch here means that MaxIter is potentially larger than max
10585   // unsigned value in start type, which mean we cannot prove no wrap for the
10586   // indvar.
10587   if (AR->getType() != MaxIter->getType())
10588     return None;
10589 
10590   // Value of IV on suggested last iteration.
10591   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
10592   // Does it still meet the requirement?
10593   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
10594     return None;
10595   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
10596   // not exceed max unsigned value of this type), this effectively proves
10597   // that there is no wrap during the iteration. To prove that there is no
10598   // signed/unsigned wrap, we need to check that
10599   // Start <= Last for step = 1 or Start >= Last for step = -1.
10600   ICmpInst::Predicate NoOverflowPred =
10601       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
10602   if (Step == MinusOne)
10603     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
10604   const SCEV *Start = AR->getStart();
10605   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
10606     return None;
10607 
10608   // Everything is fine.
10609   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
10610 }
10611 
10612 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
10613     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
10614   if (HasSameValue(LHS, RHS))
10615     return ICmpInst::isTrueWhenEqual(Pred);
10616 
10617   // This code is split out from isKnownPredicate because it is called from
10618   // within isLoopEntryGuardedByCond.
10619 
10620   auto CheckRanges = [&](const ConstantRange &RangeLHS,
10621                          const ConstantRange &RangeRHS) {
10622     return RangeLHS.icmp(Pred, RangeRHS);
10623   };
10624 
10625   // The check at the top of the function catches the case where the values are
10626   // known to be equal.
10627   if (Pred == CmpInst::ICMP_EQ)
10628     return false;
10629 
10630   if (Pred == CmpInst::ICMP_NE) {
10631     if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
10632         CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)))
10633       return true;
10634     auto *Diff = getMinusSCEV(LHS, RHS);
10635     return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
10636   }
10637 
10638   if (CmpInst::isSigned(Pred))
10639     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
10640 
10641   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
10642 }
10643 
10644 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
10645                                                     const SCEV *LHS,
10646                                                     const SCEV *RHS) {
10647   // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
10648   // C1 and C2 are constant integers. If either X or Y are not add expressions,
10649   // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
10650   // OutC1 and OutC2.
10651   auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
10652                                       APInt &OutC1, APInt &OutC2,
10653                                       SCEV::NoWrapFlags ExpectedFlags) {
10654     const SCEV *XNonConstOp, *XConstOp;
10655     const SCEV *YNonConstOp, *YConstOp;
10656     SCEV::NoWrapFlags XFlagsPresent;
10657     SCEV::NoWrapFlags YFlagsPresent;
10658 
10659     if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
10660       XConstOp = getZero(X->getType());
10661       XNonConstOp = X;
10662       XFlagsPresent = ExpectedFlags;
10663     }
10664     if (!isa<SCEVConstant>(XConstOp) ||
10665         (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
10666       return false;
10667 
10668     if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
10669       YConstOp = getZero(Y->getType());
10670       YNonConstOp = Y;
10671       YFlagsPresent = ExpectedFlags;
10672     }
10673 
10674     if (!isa<SCEVConstant>(YConstOp) ||
10675         (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
10676       return false;
10677 
10678     if (YNonConstOp != XNonConstOp)
10679       return false;
10680 
10681     OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
10682     OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
10683 
10684     return true;
10685   };
10686 
10687   APInt C1;
10688   APInt C2;
10689 
10690   switch (Pred) {
10691   default:
10692     break;
10693 
10694   case ICmpInst::ICMP_SGE:
10695     std::swap(LHS, RHS);
10696     LLVM_FALLTHROUGH;
10697   case ICmpInst::ICMP_SLE:
10698     // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
10699     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
10700       return true;
10701 
10702     break;
10703 
10704   case ICmpInst::ICMP_SGT:
10705     std::swap(LHS, RHS);
10706     LLVM_FALLTHROUGH;
10707   case ICmpInst::ICMP_SLT:
10708     // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
10709     if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
10710       return true;
10711 
10712     break;
10713 
10714   case ICmpInst::ICMP_UGE:
10715     std::swap(LHS, RHS);
10716     LLVM_FALLTHROUGH;
10717   case ICmpInst::ICMP_ULE:
10718     // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
10719     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
10720       return true;
10721 
10722     break;
10723 
10724   case ICmpInst::ICMP_UGT:
10725     std::swap(LHS, RHS);
10726     LLVM_FALLTHROUGH;
10727   case ICmpInst::ICMP_ULT:
10728     // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
10729     if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
10730       return true;
10731     break;
10732   }
10733 
10734   return false;
10735 }
10736 
10737 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
10738                                                    const SCEV *LHS,
10739                                                    const SCEV *RHS) {
10740   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
10741     return false;
10742 
10743   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
10744   // the stack can result in exponential time complexity.
10745   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
10746 
10747   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
10748   //
10749   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
10750   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
10751   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
10752   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
10753   // use isKnownPredicate later if needed.
10754   return isKnownNonNegative(RHS) &&
10755          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
10756          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
10757 }
10758 
10759 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
10760                                         ICmpInst::Predicate Pred,
10761                                         const SCEV *LHS, const SCEV *RHS) {
10762   // No need to even try if we know the module has no guards.
10763   if (!HasGuards)
10764     return false;
10765 
10766   return any_of(*BB, [&](const Instruction &I) {
10767     using namespace llvm::PatternMatch;
10768 
10769     Value *Condition;
10770     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
10771                          m_Value(Condition))) &&
10772            isImpliedCond(Pred, LHS, RHS, Condition, false);
10773   });
10774 }
10775 
10776 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
10777 /// protected by a conditional between LHS and RHS.  This is used to
10778 /// to eliminate casts.
10779 bool
10780 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
10781                                              ICmpInst::Predicate Pred,
10782                                              const SCEV *LHS, const SCEV *RHS) {
10783   // Interpret a null as meaning no loop, where there is obviously no guard
10784   // (interprocedural conditions notwithstanding).
10785   if (!L) return true;
10786 
10787   if (VerifyIR)
10788     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
10789            "This cannot be done on broken IR!");
10790 
10791 
10792   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
10793     return true;
10794 
10795   BasicBlock *Latch = L->getLoopLatch();
10796   if (!Latch)
10797     return false;
10798 
10799   BranchInst *LoopContinuePredicate =
10800     dyn_cast<BranchInst>(Latch->getTerminator());
10801   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
10802       isImpliedCond(Pred, LHS, RHS,
10803                     LoopContinuePredicate->getCondition(),
10804                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
10805     return true;
10806 
10807   // We don't want more than one activation of the following loops on the stack
10808   // -- that can lead to O(n!) time complexity.
10809   if (WalkingBEDominatingConds)
10810     return false;
10811 
10812   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
10813 
10814   // See if we can exploit a trip count to prove the predicate.
10815   const auto &BETakenInfo = getBackedgeTakenInfo(L);
10816   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
10817   if (LatchBECount != getCouldNotCompute()) {
10818     // We know that Latch branches back to the loop header exactly
10819     // LatchBECount times.  This means the backdege condition at Latch is
10820     // equivalent to  "{0,+,1} u< LatchBECount".
10821     Type *Ty = LatchBECount->getType();
10822     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
10823     const SCEV *LoopCounter =
10824       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
10825     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
10826                       LatchBECount))
10827       return true;
10828   }
10829 
10830   // Check conditions due to any @llvm.assume intrinsics.
10831   for (auto &AssumeVH : AC.assumptions()) {
10832     if (!AssumeVH)
10833       continue;
10834     auto *CI = cast<CallInst>(AssumeVH);
10835     if (!DT.dominates(CI, Latch->getTerminator()))
10836       continue;
10837 
10838     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
10839       return true;
10840   }
10841 
10842   // If the loop is not reachable from the entry block, we risk running into an
10843   // infinite loop as we walk up into the dom tree.  These loops do not matter
10844   // anyway, so we just return a conservative answer when we see them.
10845   if (!DT.isReachableFromEntry(L->getHeader()))
10846     return false;
10847 
10848   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
10849     return true;
10850 
10851   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
10852        DTN != HeaderDTN; DTN = DTN->getIDom()) {
10853     assert(DTN && "should reach the loop header before reaching the root!");
10854 
10855     BasicBlock *BB = DTN->getBlock();
10856     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
10857       return true;
10858 
10859     BasicBlock *PBB = BB->getSinglePredecessor();
10860     if (!PBB)
10861       continue;
10862 
10863     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
10864     if (!ContinuePredicate || !ContinuePredicate->isConditional())
10865       continue;
10866 
10867     Value *Condition = ContinuePredicate->getCondition();
10868 
10869     // If we have an edge `E` within the loop body that dominates the only
10870     // latch, the condition guarding `E` also guards the backedge.  This
10871     // reasoning works only for loops with a single latch.
10872 
10873     BasicBlockEdge DominatingEdge(PBB, BB);
10874     if (DominatingEdge.isSingleEdge()) {
10875       // We're constructively (and conservatively) enumerating edges within the
10876       // loop body that dominate the latch.  The dominator tree better agree
10877       // with us on this:
10878       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
10879 
10880       if (isImpliedCond(Pred, LHS, RHS, Condition,
10881                         BB != ContinuePredicate->getSuccessor(0)))
10882         return true;
10883     }
10884   }
10885 
10886   return false;
10887 }
10888 
10889 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
10890                                                      ICmpInst::Predicate Pred,
10891                                                      const SCEV *LHS,
10892                                                      const SCEV *RHS) {
10893   if (VerifyIR)
10894     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
10895            "This cannot be done on broken IR!");
10896 
10897   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
10898   // the facts (a >= b && a != b) separately. A typical situation is when the
10899   // non-strict comparison is known from ranges and non-equality is known from
10900   // dominating predicates. If we are proving strict comparison, we always try
10901   // to prove non-equality and non-strict comparison separately.
10902   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
10903   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
10904   bool ProvedNonStrictComparison = false;
10905   bool ProvedNonEquality = false;
10906 
10907   auto SplitAndProve =
10908     [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
10909     if (!ProvedNonStrictComparison)
10910       ProvedNonStrictComparison = Fn(NonStrictPredicate);
10911     if (!ProvedNonEquality)
10912       ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
10913     if (ProvedNonStrictComparison && ProvedNonEquality)
10914       return true;
10915     return false;
10916   };
10917 
10918   if (ProvingStrictComparison) {
10919     auto ProofFn = [&](ICmpInst::Predicate P) {
10920       return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
10921     };
10922     if (SplitAndProve(ProofFn))
10923       return true;
10924   }
10925 
10926   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
10927   auto ProveViaGuard = [&](const BasicBlock *Block) {
10928     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
10929       return true;
10930     if (ProvingStrictComparison) {
10931       auto ProofFn = [&](ICmpInst::Predicate P) {
10932         return isImpliedViaGuard(Block, P, LHS, RHS);
10933       };
10934       if (SplitAndProve(ProofFn))
10935         return true;
10936     }
10937     return false;
10938   };
10939 
10940   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10941   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10942     const Instruction *CtxI = &BB->front();
10943     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
10944       return true;
10945     if (ProvingStrictComparison) {
10946       auto ProofFn = [&](ICmpInst::Predicate P) {
10947         return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
10948       };
10949       if (SplitAndProve(ProofFn))
10950         return true;
10951     }
10952     return false;
10953   };
10954 
10955   // Starting at the block's predecessor, climb up the predecessor chain, as long
10956   // as there are predecessors that can be found that have unique successors
10957   // leading to the original block.
10958   const Loop *ContainingLoop = LI.getLoopFor(BB);
10959   const BasicBlock *PredBB;
10960   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10961     PredBB = ContainingLoop->getLoopPredecessor();
10962   else
10963     PredBB = BB->getSinglePredecessor();
10964   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10965        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10966     if (ProveViaGuard(Pair.first))
10967       return true;
10968 
10969     const BranchInst *LoopEntryPredicate =
10970         dyn_cast<BranchInst>(Pair.first->getTerminator());
10971     if (!LoopEntryPredicate ||
10972         LoopEntryPredicate->isUnconditional())
10973       continue;
10974 
10975     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10976                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10977       return true;
10978   }
10979 
10980   // Check conditions due to any @llvm.assume intrinsics.
10981   for (auto &AssumeVH : AC.assumptions()) {
10982     if (!AssumeVH)
10983       continue;
10984     auto *CI = cast<CallInst>(AssumeVH);
10985     if (!DT.dominates(CI, BB))
10986       continue;
10987 
10988     if (ProveViaCond(CI->getArgOperand(0), false))
10989       return true;
10990   }
10991 
10992   return false;
10993 }
10994 
10995 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10996                                                ICmpInst::Predicate Pred,
10997                                                const SCEV *LHS,
10998                                                const SCEV *RHS) {
10999   // Interpret a null as meaning no loop, where there is obviously no guard
11000   // (interprocedural conditions notwithstanding).
11001   if (!L)
11002     return false;
11003 
11004   // Both LHS and RHS must be available at loop entry.
11005   assert(isAvailableAtLoopEntry(LHS, L) &&
11006          "LHS is not available at Loop Entry");
11007   assert(isAvailableAtLoopEntry(RHS, L) &&
11008          "RHS is not available at Loop Entry");
11009 
11010   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11011     return true;
11012 
11013   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11014 }
11015 
11016 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11017                                     const SCEV *RHS,
11018                                     const Value *FoundCondValue, bool Inverse,
11019                                     const Instruction *CtxI) {
11020   // False conditions implies anything. Do not bother analyzing it further.
11021   if (FoundCondValue ==
11022       ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11023     return true;
11024 
11025   if (!PendingLoopPredicates.insert(FoundCondValue).second)
11026     return false;
11027 
11028   auto ClearOnExit =
11029       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11030 
11031   // Recursively handle And and Or conditions.
11032   const Value *Op0, *Op1;
11033   if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11034     if (!Inverse)
11035       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11036              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11037   } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11038     if (Inverse)
11039       return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11040              isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11041   }
11042 
11043   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11044   if (!ICI) return false;
11045 
11046   // Now that we found a conditional branch that dominates the loop or controls
11047   // the loop latch. Check to see if it is the comparison we are looking for.
11048   ICmpInst::Predicate FoundPred;
11049   if (Inverse)
11050     FoundPred = ICI->getInversePredicate();
11051   else
11052     FoundPred = ICI->getPredicate();
11053 
11054   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11055   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11056 
11057   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11058 }
11059 
11060 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11061                                     const SCEV *RHS,
11062                                     ICmpInst::Predicate FoundPred,
11063                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
11064                                     const Instruction *CtxI) {
11065   // Balance the types.
11066   if (getTypeSizeInBits(LHS->getType()) <
11067       getTypeSizeInBits(FoundLHS->getType())) {
11068     // For unsigned and equality predicates, try to prove that both found
11069     // operands fit into narrow unsigned range. If so, try to prove facts in
11070     // narrow types.
11071     if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11072         !FoundRHS->getType()->isPointerTy()) {
11073       auto *NarrowType = LHS->getType();
11074       auto *WideType = FoundLHS->getType();
11075       auto BitWidth = getTypeSizeInBits(NarrowType);
11076       const SCEV *MaxValue = getZeroExtendExpr(
11077           getConstant(APInt::getMaxValue(BitWidth)), WideType);
11078       if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11079                                           MaxValue) &&
11080           isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11081                                           MaxValue)) {
11082         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11083         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11084         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11085                                        TruncFoundRHS, CtxI))
11086           return true;
11087       }
11088     }
11089 
11090     if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11091       return false;
11092     if (CmpInst::isSigned(Pred)) {
11093       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11094       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11095     } else {
11096       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11097       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11098     }
11099   } else if (getTypeSizeInBits(LHS->getType()) >
11100       getTypeSizeInBits(FoundLHS->getType())) {
11101     if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11102       return false;
11103     if (CmpInst::isSigned(FoundPred)) {
11104       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11105       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11106     } else {
11107       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11108       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11109     }
11110   }
11111   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11112                                     FoundRHS, CtxI);
11113 }
11114 
11115 bool ScalarEvolution::isImpliedCondBalancedTypes(
11116     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11117     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11118     const Instruction *CtxI) {
11119   assert(getTypeSizeInBits(LHS->getType()) ==
11120              getTypeSizeInBits(FoundLHS->getType()) &&
11121          "Types should be balanced!");
11122   // Canonicalize the query to match the way instcombine will have
11123   // canonicalized the comparison.
11124   if (SimplifyICmpOperands(Pred, LHS, RHS))
11125     if (LHS == RHS)
11126       return CmpInst::isTrueWhenEqual(Pred);
11127   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11128     if (FoundLHS == FoundRHS)
11129       return CmpInst::isFalseWhenEqual(FoundPred);
11130 
11131   // Check to see if we can make the LHS or RHS match.
11132   if (LHS == FoundRHS || RHS == FoundLHS) {
11133     if (isa<SCEVConstant>(RHS)) {
11134       std::swap(FoundLHS, FoundRHS);
11135       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11136     } else {
11137       std::swap(LHS, RHS);
11138       Pred = ICmpInst::getSwappedPredicate(Pred);
11139     }
11140   }
11141 
11142   // Check whether the found predicate is the same as the desired predicate.
11143   if (FoundPred == Pred)
11144     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11145 
11146   // Check whether swapping the found predicate makes it the same as the
11147   // desired predicate.
11148   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11149     // We can write the implication
11150     // 0.  LHS Pred      RHS  <-   FoundLHS SwapPred  FoundRHS
11151     // using one of the following ways:
11152     // 1.  LHS Pred      RHS  <-   FoundRHS Pred      FoundLHS
11153     // 2.  RHS SwapPred  LHS  <-   FoundLHS SwapPred  FoundRHS
11154     // 3.  LHS Pred      RHS  <-  ~FoundLHS Pred     ~FoundRHS
11155     // 4. ~LHS SwapPred ~RHS  <-   FoundLHS SwapPred  FoundRHS
11156     // Forms 1. and 2. require swapping the operands of one condition. Don't
11157     // do this if it would break canonical constant/addrec ordering.
11158     if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11159       return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11160                                    CtxI);
11161     if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11162       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11163 
11164     // There's no clear preference between forms 3. and 4., try both.  Avoid
11165     // forming getNotSCEV of pointer values as the resulting subtract is
11166     // not legal.
11167     if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11168         isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11169                               FoundLHS, FoundRHS, CtxI))
11170       return true;
11171 
11172     if (!FoundLHS->getType()->isPointerTy() &&
11173         !FoundRHS->getType()->isPointerTy() &&
11174         isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11175                               getNotSCEV(FoundRHS), CtxI))
11176       return true;
11177 
11178     return false;
11179   }
11180 
11181   auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11182                                    CmpInst::Predicate P2) {
11183     assert(P1 != P2 && "Handled earlier!");
11184     return CmpInst::isRelational(P2) &&
11185            P1 == CmpInst::getFlippedSignednessPredicate(P2);
11186   };
11187   if (IsSignFlippedPredicate(Pred, FoundPred)) {
11188     // Unsigned comparison is the same as signed comparison when both the
11189     // operands are non-negative or negative.
11190     if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11191         (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11192       return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11193     // Create local copies that we can freely swap and canonicalize our
11194     // conditions to "le/lt".
11195     ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11196     const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11197                *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11198     if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11199       CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11200       CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11201       std::swap(CanonicalLHS, CanonicalRHS);
11202       std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11203     }
11204     assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11205            "Must be!");
11206     assert((ICmpInst::isLT(CanonicalFoundPred) ||
11207             ICmpInst::isLE(CanonicalFoundPred)) &&
11208            "Must be!");
11209     if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11210       // Use implication:
11211       // x <u y && y >=s 0 --> x <s y.
11212       // If we can prove the left part, the right part is also proven.
11213       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11214                                    CanonicalRHS, CanonicalFoundLHS,
11215                                    CanonicalFoundRHS);
11216     if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11217       // Use implication:
11218       // x <s y && y <s 0 --> x <u y.
11219       // If we can prove the left part, the right part is also proven.
11220       return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11221                                    CanonicalRHS, CanonicalFoundLHS,
11222                                    CanonicalFoundRHS);
11223   }
11224 
11225   // Check if we can make progress by sharpening ranges.
11226   if (FoundPred == ICmpInst::ICMP_NE &&
11227       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11228 
11229     const SCEVConstant *C = nullptr;
11230     const SCEV *V = nullptr;
11231 
11232     if (isa<SCEVConstant>(FoundLHS)) {
11233       C = cast<SCEVConstant>(FoundLHS);
11234       V = FoundRHS;
11235     } else {
11236       C = cast<SCEVConstant>(FoundRHS);
11237       V = FoundLHS;
11238     }
11239 
11240     // The guarding predicate tells us that C != V. If the known range
11241     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
11242     // range we consider has to correspond to same signedness as the
11243     // predicate we're interested in folding.
11244 
11245     APInt Min = ICmpInst::isSigned(Pred) ?
11246         getSignedRangeMin(V) : getUnsignedRangeMin(V);
11247 
11248     if (Min == C->getAPInt()) {
11249       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11250       // This is true even if (Min + 1) wraps around -- in case of
11251       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11252 
11253       APInt SharperMin = Min + 1;
11254 
11255       switch (Pred) {
11256         case ICmpInst::ICMP_SGE:
11257         case ICmpInst::ICMP_UGE:
11258           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
11259           // RHS, we're done.
11260           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11261                                     CtxI))
11262             return true;
11263           LLVM_FALLTHROUGH;
11264 
11265         case ICmpInst::ICMP_SGT:
11266         case ICmpInst::ICMP_UGT:
11267           // We know from the range information that (V `Pred` Min ||
11268           // V == Min).  We know from the guarding condition that !(V
11269           // == Min).  This gives us
11270           //
11271           //       V `Pred` Min || V == Min && !(V == Min)
11272           //   =>  V `Pred` Min
11273           //
11274           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11275 
11276           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11277             return true;
11278           break;
11279 
11280         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11281         case ICmpInst::ICMP_SLE:
11282         case ICmpInst::ICMP_ULE:
11283           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11284                                     LHS, V, getConstant(SharperMin), CtxI))
11285             return true;
11286           LLVM_FALLTHROUGH;
11287 
11288         case ICmpInst::ICMP_SLT:
11289         case ICmpInst::ICMP_ULT:
11290           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11291                                     LHS, V, getConstant(Min), CtxI))
11292             return true;
11293           break;
11294 
11295         default:
11296           // No change
11297           break;
11298       }
11299     }
11300   }
11301 
11302   // Check whether the actual condition is beyond sufficient.
11303   if (FoundPred == ICmpInst::ICMP_EQ)
11304     if (ICmpInst::isTrueWhenEqual(Pred))
11305       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11306         return true;
11307   if (Pred == ICmpInst::ICMP_NE)
11308     if (!ICmpInst::isTrueWhenEqual(FoundPred))
11309       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11310         return true;
11311 
11312   // Otherwise assume the worst.
11313   return false;
11314 }
11315 
11316 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11317                                      const SCEV *&L, const SCEV *&R,
11318                                      SCEV::NoWrapFlags &Flags) {
11319   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11320   if (!AE || AE->getNumOperands() != 2)
11321     return false;
11322 
11323   L = AE->getOperand(0);
11324   R = AE->getOperand(1);
11325   Flags = AE->getNoWrapFlags();
11326   return true;
11327 }
11328 
11329 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
11330                                                            const SCEV *Less) {
11331   // We avoid subtracting expressions here because this function is usually
11332   // fairly deep in the call stack (i.e. is called many times).
11333 
11334   // X - X = 0.
11335   if (More == Less)
11336     return APInt(getTypeSizeInBits(More->getType()), 0);
11337 
11338   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11339     const auto *LAR = cast<SCEVAddRecExpr>(Less);
11340     const auto *MAR = cast<SCEVAddRecExpr>(More);
11341 
11342     if (LAR->getLoop() != MAR->getLoop())
11343       return None;
11344 
11345     // We look at affine expressions only; not for correctness but to keep
11346     // getStepRecurrence cheap.
11347     if (!LAR->isAffine() || !MAR->isAffine())
11348       return None;
11349 
11350     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11351       return None;
11352 
11353     Less = LAR->getStart();
11354     More = MAR->getStart();
11355 
11356     // fall through
11357   }
11358 
11359   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11360     const auto &M = cast<SCEVConstant>(More)->getAPInt();
11361     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11362     return M - L;
11363   }
11364 
11365   SCEV::NoWrapFlags Flags;
11366   const SCEV *LLess = nullptr, *RLess = nullptr;
11367   const SCEV *LMore = nullptr, *RMore = nullptr;
11368   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11369   // Compare (X + C1) vs X.
11370   if (splitBinaryAdd(Less, LLess, RLess, Flags))
11371     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11372       if (RLess == More)
11373         return -(C1->getAPInt());
11374 
11375   // Compare X vs (X + C2).
11376   if (splitBinaryAdd(More, LMore, RMore, Flags))
11377     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11378       if (RMore == Less)
11379         return C2->getAPInt();
11380 
11381   // Compare (X + C1) vs (X + C2).
11382   if (C1 && C2 && RLess == RMore)
11383     return C2->getAPInt() - C1->getAPInt();
11384 
11385   return None;
11386 }
11387 
11388 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11389     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11390     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11391   // Try to recognize the following pattern:
11392   //
11393   //   FoundRHS = ...
11394   // ...
11395   // loop:
11396   //   FoundLHS = {Start,+,W}
11397   // context_bb: // Basic block from the same loop
11398   //   known(Pred, FoundLHS, FoundRHS)
11399   //
11400   // If some predicate is known in the context of a loop, it is also known on
11401   // each iteration of this loop, including the first iteration. Therefore, in
11402   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11403   // prove the original pred using this fact.
11404   if (!CtxI)
11405     return false;
11406   const BasicBlock *ContextBB = CtxI->getParent();
11407   // Make sure AR varies in the context block.
11408   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11409     const Loop *L = AR->getLoop();
11410     // Make sure that context belongs to the loop and executes on 1st iteration
11411     // (if it ever executes at all).
11412     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11413       return false;
11414     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11415       return false;
11416     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11417   }
11418 
11419   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11420     const Loop *L = AR->getLoop();
11421     // Make sure that context belongs to the loop and executes on 1st iteration
11422     // (if it ever executes at all).
11423     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11424       return false;
11425     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11426       return false;
11427     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11428   }
11429 
11430   return false;
11431 }
11432 
11433 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11434     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11435     const SCEV *FoundLHS, const SCEV *FoundRHS) {
11436   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11437     return false;
11438 
11439   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11440   if (!AddRecLHS)
11441     return false;
11442 
11443   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11444   if (!AddRecFoundLHS)
11445     return false;
11446 
11447   // We'd like to let SCEV reason about control dependencies, so we constrain
11448   // both the inequalities to be about add recurrences on the same loop.  This
11449   // way we can use isLoopEntryGuardedByCond later.
11450 
11451   const Loop *L = AddRecFoundLHS->getLoop();
11452   if (L != AddRecLHS->getLoop())
11453     return false;
11454 
11455   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
11456   //
11457   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11458   //                                                                  ... (2)
11459   //
11460   // Informal proof for (2), assuming (1) [*]:
11461   //
11462   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11463   //
11464   // Then
11465   //
11466   //       FoundLHS s< FoundRHS s< INT_MIN - C
11467   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
11468   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11469   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
11470   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11471   // <=>  FoundLHS + C s< FoundRHS + C
11472   //
11473   // [*]: (1) can be proved by ruling out overflow.
11474   //
11475   // [**]: This can be proved by analyzing all the four possibilities:
11476   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11477   //    (A s>= 0, B s>= 0).
11478   //
11479   // Note:
11480   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11481   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
11482   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
11483   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
11484   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11485   // C)".
11486 
11487   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11488   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11489   if (!LDiff || !RDiff || *LDiff != *RDiff)
11490     return false;
11491 
11492   if (LDiff->isMinValue())
11493     return true;
11494 
11495   APInt FoundRHSLimit;
11496 
11497   if (Pred == CmpInst::ICMP_ULT) {
11498     FoundRHSLimit = -(*RDiff);
11499   } else {
11500     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11501     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11502   }
11503 
11504   // Try to prove (1) or (2), as needed.
11505   return isAvailableAtLoopEntry(FoundRHS, L) &&
11506          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11507                                   getConstant(FoundRHSLimit));
11508 }
11509 
11510 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11511                                         const SCEV *LHS, const SCEV *RHS,
11512                                         const SCEV *FoundLHS,
11513                                         const SCEV *FoundRHS, unsigned Depth) {
11514   const PHINode *LPhi = nullptr, *RPhi = nullptr;
11515 
11516   auto ClearOnExit = make_scope_exit([&]() {
11517     if (LPhi) {
11518       bool Erased = PendingMerges.erase(LPhi);
11519       assert(Erased && "Failed to erase LPhi!");
11520       (void)Erased;
11521     }
11522     if (RPhi) {
11523       bool Erased = PendingMerges.erase(RPhi);
11524       assert(Erased && "Failed to erase RPhi!");
11525       (void)Erased;
11526     }
11527   });
11528 
11529   // Find respective Phis and check that they are not being pending.
11530   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11531     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11532       if (!PendingMerges.insert(Phi).second)
11533         return false;
11534       LPhi = Phi;
11535     }
11536   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11537     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11538       // If we detect a loop of Phi nodes being processed by this method, for
11539       // example:
11540       //
11541       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11542       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11543       //
11544       // we don't want to deal with a case that complex, so return conservative
11545       // answer false.
11546       if (!PendingMerges.insert(Phi).second)
11547         return false;
11548       RPhi = Phi;
11549     }
11550 
11551   // If none of LHS, RHS is a Phi, nothing to do here.
11552   if (!LPhi && !RPhi)
11553     return false;
11554 
11555   // If there is a SCEVUnknown Phi we are interested in, make it left.
11556   if (!LPhi) {
11557     std::swap(LHS, RHS);
11558     std::swap(FoundLHS, FoundRHS);
11559     std::swap(LPhi, RPhi);
11560     Pred = ICmpInst::getSwappedPredicate(Pred);
11561   }
11562 
11563   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
11564   const BasicBlock *LBB = LPhi->getParent();
11565   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11566 
11567   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
11568     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
11569            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
11570            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
11571   };
11572 
11573   if (RPhi && RPhi->getParent() == LBB) {
11574     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
11575     // If we compare two Phis from the same block, and for each entry block
11576     // the predicate is true for incoming values from this block, then the
11577     // predicate is also true for the Phis.
11578     for (const BasicBlock *IncBB : predecessors(LBB)) {
11579       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11580       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
11581       if (!ProvedEasily(L, R))
11582         return false;
11583     }
11584   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
11585     // Case two: RHS is also a Phi from the same basic block, and it is an
11586     // AddRec. It means that there is a loop which has both AddRec and Unknown
11587     // PHIs, for it we can compare incoming values of AddRec from above the loop
11588     // and latch with their respective incoming values of LPhi.
11589     // TODO: Generalize to handle loops with many inputs in a header.
11590     if (LPhi->getNumIncomingValues() != 2) return false;
11591 
11592     auto *RLoop = RAR->getLoop();
11593     auto *Predecessor = RLoop->getLoopPredecessor();
11594     assert(Predecessor && "Loop with AddRec with no predecessor?");
11595     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
11596     if (!ProvedEasily(L1, RAR->getStart()))
11597       return false;
11598     auto *Latch = RLoop->getLoopLatch();
11599     assert(Latch && "Loop with AddRec with no latch?");
11600     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
11601     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
11602       return false;
11603   } else {
11604     // In all other cases go over inputs of LHS and compare each of them to RHS,
11605     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
11606     // At this point RHS is either a non-Phi, or it is a Phi from some block
11607     // different from LBB.
11608     for (const BasicBlock *IncBB : predecessors(LBB)) {
11609       // Check that RHS is available in this block.
11610       if (!dominates(RHS, IncBB))
11611         return false;
11612       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
11613       // Make sure L does not refer to a value from a potentially previous
11614       // iteration of a loop.
11615       if (!properlyDominates(L, IncBB))
11616         return false;
11617       if (!ProvedEasily(L, RHS))
11618         return false;
11619     }
11620   }
11621   return true;
11622 }
11623 
11624 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
11625                                                     const SCEV *LHS,
11626                                                     const SCEV *RHS,
11627                                                     const SCEV *FoundLHS,
11628                                                     const SCEV *FoundRHS) {
11629   // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue).  First, make
11630   // sure that we are dealing with same LHS.
11631   if (RHS == FoundRHS) {
11632     std::swap(LHS, RHS);
11633     std::swap(FoundLHS, FoundRHS);
11634     Pred = ICmpInst::getSwappedPredicate(Pred);
11635   }
11636   if (LHS != FoundLHS)
11637     return false;
11638 
11639   auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
11640   if (!SUFoundRHS)
11641     return false;
11642 
11643   Value *Shiftee, *ShiftValue;
11644 
11645   using namespace PatternMatch;
11646   if (match(SUFoundRHS->getValue(),
11647             m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
11648     auto *ShifteeS = getSCEV(Shiftee);
11649     // Prove one of the following:
11650     // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
11651     // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
11652     // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11653     //   ---> LHS <s RHS
11654     // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
11655     //   ---> LHS <=s RHS
11656     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
11657       return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
11658     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
11659       if (isKnownNonNegative(ShifteeS))
11660         return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
11661   }
11662 
11663   return false;
11664 }
11665 
11666 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
11667                                             const SCEV *LHS, const SCEV *RHS,
11668                                             const SCEV *FoundLHS,
11669                                             const SCEV *FoundRHS,
11670                                             const Instruction *CtxI) {
11671   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
11672     return true;
11673 
11674   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
11675     return true;
11676 
11677   if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
11678     return true;
11679 
11680   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
11681                                           CtxI))
11682     return true;
11683 
11684   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
11685                                      FoundLHS, FoundRHS);
11686 }
11687 
11688 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
11689 template <typename MinMaxExprType>
11690 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
11691                                  const SCEV *Candidate) {
11692   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
11693   if (!MinMaxExpr)
11694     return false;
11695 
11696   return is_contained(MinMaxExpr->operands(), Candidate);
11697 }
11698 
11699 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
11700                                            ICmpInst::Predicate Pred,
11701                                            const SCEV *LHS, const SCEV *RHS) {
11702   // If both sides are affine addrecs for the same loop, with equal
11703   // steps, and we know the recurrences don't wrap, then we only
11704   // need to check the predicate on the starting values.
11705 
11706   if (!ICmpInst::isRelational(Pred))
11707     return false;
11708 
11709   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
11710   if (!LAR)
11711     return false;
11712   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
11713   if (!RAR)
11714     return false;
11715   if (LAR->getLoop() != RAR->getLoop())
11716     return false;
11717   if (!LAR->isAffine() || !RAR->isAffine())
11718     return false;
11719 
11720   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
11721     return false;
11722 
11723   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
11724                          SCEV::FlagNSW : SCEV::FlagNUW;
11725   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
11726     return false;
11727 
11728   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
11729 }
11730 
11731 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
11732 /// expression?
11733 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
11734                                         ICmpInst::Predicate Pred,
11735                                         const SCEV *LHS, const SCEV *RHS) {
11736   switch (Pred) {
11737   default:
11738     return false;
11739 
11740   case ICmpInst::ICMP_SGE:
11741     std::swap(LHS, RHS);
11742     LLVM_FALLTHROUGH;
11743   case ICmpInst::ICMP_SLE:
11744     return
11745         // min(A, ...) <= A
11746         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
11747         // A <= max(A, ...)
11748         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
11749 
11750   case ICmpInst::ICMP_UGE:
11751     std::swap(LHS, RHS);
11752     LLVM_FALLTHROUGH;
11753   case ICmpInst::ICMP_ULE:
11754     return
11755         // min(A, ...) <= A
11756         // FIXME: what about umin_seq?
11757         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
11758         // A <= max(A, ...)
11759         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
11760   }
11761 
11762   llvm_unreachable("covered switch fell through?!");
11763 }
11764 
11765 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
11766                                              const SCEV *LHS, const SCEV *RHS,
11767                                              const SCEV *FoundLHS,
11768                                              const SCEV *FoundRHS,
11769                                              unsigned Depth) {
11770   assert(getTypeSizeInBits(LHS->getType()) ==
11771              getTypeSizeInBits(RHS->getType()) &&
11772          "LHS and RHS have different sizes?");
11773   assert(getTypeSizeInBits(FoundLHS->getType()) ==
11774              getTypeSizeInBits(FoundRHS->getType()) &&
11775          "FoundLHS and FoundRHS have different sizes?");
11776   // We want to avoid hurting the compile time with analysis of too big trees.
11777   if (Depth > MaxSCEVOperationsImplicationDepth)
11778     return false;
11779 
11780   // We only want to work with GT comparison so far.
11781   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
11782     Pred = CmpInst::getSwappedPredicate(Pred);
11783     std::swap(LHS, RHS);
11784     std::swap(FoundLHS, FoundRHS);
11785   }
11786 
11787   // For unsigned, try to reduce it to corresponding signed comparison.
11788   if (Pred == ICmpInst::ICMP_UGT)
11789     // We can replace unsigned predicate with its signed counterpart if all
11790     // involved values are non-negative.
11791     // TODO: We could have better support for unsigned.
11792     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
11793       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
11794       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
11795       // use this fact to prove that LHS and RHS are non-negative.
11796       const SCEV *MinusOne = getMinusOne(LHS->getType());
11797       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
11798                                 FoundRHS) &&
11799           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
11800                                 FoundRHS))
11801         Pred = ICmpInst::ICMP_SGT;
11802     }
11803 
11804   if (Pred != ICmpInst::ICMP_SGT)
11805     return false;
11806 
11807   auto GetOpFromSExt = [&](const SCEV *S) {
11808     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
11809       return Ext->getOperand();
11810     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
11811     // the constant in some cases.
11812     return S;
11813   };
11814 
11815   // Acquire values from extensions.
11816   auto *OrigLHS = LHS;
11817   auto *OrigFoundLHS = FoundLHS;
11818   LHS = GetOpFromSExt(LHS);
11819   FoundLHS = GetOpFromSExt(FoundLHS);
11820 
11821   // Is the SGT predicate can be proved trivially or using the found context.
11822   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
11823     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
11824            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
11825                                   FoundRHS, Depth + 1);
11826   };
11827 
11828   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
11829     // We want to avoid creation of any new non-constant SCEV. Since we are
11830     // going to compare the operands to RHS, we should be certain that we don't
11831     // need any size extensions for this. So let's decline all cases when the
11832     // sizes of types of LHS and RHS do not match.
11833     // TODO: Maybe try to get RHS from sext to catch more cases?
11834     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
11835       return false;
11836 
11837     // Should not overflow.
11838     if (!LHSAddExpr->hasNoSignedWrap())
11839       return false;
11840 
11841     auto *LL = LHSAddExpr->getOperand(0);
11842     auto *LR = LHSAddExpr->getOperand(1);
11843     auto *MinusOne = getMinusOne(RHS->getType());
11844 
11845     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
11846     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
11847       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
11848     };
11849     // Try to prove the following rule:
11850     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
11851     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
11852     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
11853       return true;
11854   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
11855     Value *LL, *LR;
11856     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
11857 
11858     using namespace llvm::PatternMatch;
11859 
11860     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
11861       // Rules for division.
11862       // We are going to perform some comparisons with Denominator and its
11863       // derivative expressions. In general case, creating a SCEV for it may
11864       // lead to a complex analysis of the entire graph, and in particular it
11865       // can request trip count recalculation for the same loop. This would
11866       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
11867       // this, we only want to create SCEVs that are constants in this section.
11868       // So we bail if Denominator is not a constant.
11869       if (!isa<ConstantInt>(LR))
11870         return false;
11871 
11872       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
11873 
11874       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
11875       // then a SCEV for the numerator already exists and matches with FoundLHS.
11876       auto *Numerator = getExistingSCEV(LL);
11877       if (!Numerator || Numerator->getType() != FoundLHS->getType())
11878         return false;
11879 
11880       // Make sure that the numerator matches with FoundLHS and the denominator
11881       // is positive.
11882       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
11883         return false;
11884 
11885       auto *DTy = Denominator->getType();
11886       auto *FRHSTy = FoundRHS->getType();
11887       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
11888         // One of types is a pointer and another one is not. We cannot extend
11889         // them properly to a wider type, so let us just reject this case.
11890         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
11891         // to avoid this check.
11892         return false;
11893 
11894       // Given that:
11895       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
11896       auto *WTy = getWiderType(DTy, FRHSTy);
11897       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
11898       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
11899 
11900       // Try to prove the following rule:
11901       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
11902       // For example, given that FoundLHS > 2. It means that FoundLHS is at
11903       // least 3. If we divide it by Denominator < 4, we will have at least 1.
11904       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
11905       if (isKnownNonPositive(RHS) &&
11906           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
11907         return true;
11908 
11909       // Try to prove the following rule:
11910       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
11911       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
11912       // If we divide it by Denominator > 2, then:
11913       // 1. If FoundLHS is negative, then the result is 0.
11914       // 2. If FoundLHS is non-negative, then the result is non-negative.
11915       // Anyways, the result is non-negative.
11916       auto *MinusOne = getMinusOne(WTy);
11917       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
11918       if (isKnownNegative(RHS) &&
11919           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
11920         return true;
11921     }
11922   }
11923 
11924   // If our expression contained SCEVUnknown Phis, and we split it down and now
11925   // need to prove something for them, try to prove the predicate for every
11926   // possible incoming values of those Phis.
11927   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
11928     return true;
11929 
11930   return false;
11931 }
11932 
11933 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
11934                                         const SCEV *LHS, const SCEV *RHS) {
11935   // zext x u<= sext x, sext x s<= zext x
11936   switch (Pred) {
11937   case ICmpInst::ICMP_SGE:
11938     std::swap(LHS, RHS);
11939     LLVM_FALLTHROUGH;
11940   case ICmpInst::ICMP_SLE: {
11941     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
11942     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
11943     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
11944     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11945       return true;
11946     break;
11947   }
11948   case ICmpInst::ICMP_UGE:
11949     std::swap(LHS, RHS);
11950     LLVM_FALLTHROUGH;
11951   case ICmpInst::ICMP_ULE: {
11952     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
11953     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
11954     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
11955     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
11956       return true;
11957     break;
11958   }
11959   default:
11960     break;
11961   };
11962   return false;
11963 }
11964 
11965 bool
11966 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
11967                                            const SCEV *LHS, const SCEV *RHS) {
11968   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
11969          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
11970          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
11971          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
11972          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
11973 }
11974 
11975 bool
11976 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
11977                                              const SCEV *LHS, const SCEV *RHS,
11978                                              const SCEV *FoundLHS,
11979                                              const SCEV *FoundRHS) {
11980   switch (Pred) {
11981   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
11982   case ICmpInst::ICMP_EQ:
11983   case ICmpInst::ICMP_NE:
11984     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
11985       return true;
11986     break;
11987   case ICmpInst::ICMP_SLT:
11988   case ICmpInst::ICMP_SLE:
11989     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
11990         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
11991       return true;
11992     break;
11993   case ICmpInst::ICMP_SGT:
11994   case ICmpInst::ICMP_SGE:
11995     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
11996         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
11997       return true;
11998     break;
11999   case ICmpInst::ICMP_ULT:
12000   case ICmpInst::ICMP_ULE:
12001     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12002         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12003       return true;
12004     break;
12005   case ICmpInst::ICMP_UGT:
12006   case ICmpInst::ICMP_UGE:
12007     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12008         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12009       return true;
12010     break;
12011   }
12012 
12013   // Maybe it can be proved via operations?
12014   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12015     return true;
12016 
12017   return false;
12018 }
12019 
12020 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12021                                                      const SCEV *LHS,
12022                                                      const SCEV *RHS,
12023                                                      const SCEV *FoundLHS,
12024                                                      const SCEV *FoundRHS) {
12025   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12026     // The restriction on `FoundRHS` be lifted easily -- it exists only to
12027     // reduce the compile time impact of this optimization.
12028     return false;
12029 
12030   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12031   if (!Addend)
12032     return false;
12033 
12034   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12035 
12036   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12037   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12038   ConstantRange FoundLHSRange =
12039       ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12040 
12041   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12042   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12043 
12044   // We can also compute the range of values for `LHS` that satisfy the
12045   // consequent, "`LHS` `Pred` `RHS`":
12046   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12047   // The antecedent implies the consequent if every value of `LHS` that
12048   // satisfies the antecedent also satisfies the consequent.
12049   return LHSRange.icmp(Pred, ConstRHS);
12050 }
12051 
12052 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12053                                         bool IsSigned) {
12054   assert(isKnownPositive(Stride) && "Positive stride expected!");
12055 
12056   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12057   const SCEV *One = getOne(Stride->getType());
12058 
12059   if (IsSigned) {
12060     APInt MaxRHS = getSignedRangeMax(RHS);
12061     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12062     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12063 
12064     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12065     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12066   }
12067 
12068   APInt MaxRHS = getUnsignedRangeMax(RHS);
12069   APInt MaxValue = APInt::getMaxValue(BitWidth);
12070   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12071 
12072   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12073   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12074 }
12075 
12076 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12077                                         bool IsSigned) {
12078 
12079   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12080   const SCEV *One = getOne(Stride->getType());
12081 
12082   if (IsSigned) {
12083     APInt MinRHS = getSignedRangeMin(RHS);
12084     APInt MinValue = APInt::getSignedMinValue(BitWidth);
12085     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12086 
12087     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12088     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12089   }
12090 
12091   APInt MinRHS = getUnsignedRangeMin(RHS);
12092   APInt MinValue = APInt::getMinValue(BitWidth);
12093   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12094 
12095   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12096   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12097 }
12098 
12099 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12100   // umin(N, 1) + floor((N - umin(N, 1)) / D)
12101   // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12102   // expression fixes the case of N=0.
12103   const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12104   const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12105   return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12106 }
12107 
12108 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12109                                                     const SCEV *Stride,
12110                                                     const SCEV *End,
12111                                                     unsigned BitWidth,
12112                                                     bool IsSigned) {
12113   // The logic in this function assumes we can represent a positive stride.
12114   // If we can't, the backedge-taken count must be zero.
12115   if (IsSigned && BitWidth == 1)
12116     return getZero(Stride->getType());
12117 
12118   // This code has only been closely audited for negative strides in the
12119   // unsigned comparison case, it may be correct for signed comparison, but
12120   // that needs to be established.
12121   assert((!IsSigned || !isKnownNonPositive(Stride)) &&
12122          "Stride is expected strictly positive for signed case!");
12123 
12124   // Calculate the maximum backedge count based on the range of values
12125   // permitted by Start, End, and Stride.
12126   APInt MinStart =
12127       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12128 
12129   APInt MinStride =
12130       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12131 
12132   // We assume either the stride is positive, or the backedge-taken count
12133   // is zero. So force StrideForMaxBECount to be at least one.
12134   APInt One(BitWidth, 1);
12135   APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12136                                        : APIntOps::umax(One, MinStride);
12137 
12138   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12139                             : APInt::getMaxValue(BitWidth);
12140   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12141 
12142   // Although End can be a MAX expression we estimate MaxEnd considering only
12143   // the case End = RHS of the loop termination condition. This is safe because
12144   // in the other case (End - Start) is zero, leading to a zero maximum backedge
12145   // taken count.
12146   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12147                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12148 
12149   // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12150   MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12151                     : APIntOps::umax(MaxEnd, MinStart);
12152 
12153   return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12154                          getConstant(StrideForMaxBECount) /* Step */);
12155 }
12156 
12157 ScalarEvolution::ExitLimit
12158 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12159                                   const Loop *L, bool IsSigned,
12160                                   bool ControlsExit, bool AllowPredicates) {
12161   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12162 
12163   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12164   bool PredicatedIV = false;
12165 
12166   auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12167     // Can we prove this loop *must* be UB if overflow of IV occurs?
12168     // Reasoning goes as follows:
12169     // * Suppose the IV did self wrap.
12170     // * If Stride evenly divides the iteration space, then once wrap
12171     //   occurs, the loop must revisit the same values.
12172     // * We know that RHS is invariant, and that none of those values
12173     //   caused this exit to be taken previously.  Thus, this exit is
12174     //   dynamically dead.
12175     // * If this is the sole exit, then a dead exit implies the loop
12176     //   must be infinite if there are no abnormal exits.
12177     // * If the loop were infinite, then it must either not be mustprogress
12178     //   or have side effects. Otherwise, it must be UB.
12179     // * It can't (by assumption), be UB so we have contradicted our
12180     //   premise and can conclude the IV did not in fact self-wrap.
12181     if (!isLoopInvariant(RHS, L))
12182       return false;
12183 
12184     auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12185     if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12186       return false;
12187 
12188     if (!ControlsExit || !loopHasNoAbnormalExits(L))
12189       return false;
12190 
12191     return loopIsFiniteByAssumption(L);
12192   };
12193 
12194   if (!IV) {
12195     if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12196       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12197       if (AR && AR->getLoop() == L && AR->isAffine()) {
12198         auto canProveNUW = [&]() {
12199           if (!isLoopInvariant(RHS, L))
12200             return false;
12201 
12202           if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12203             // We need the sequence defined by AR to strictly increase in the
12204             // unsigned integer domain for the logic below to hold.
12205             return false;
12206 
12207           const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12208           const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12209           // If RHS <=u Limit, then there must exist a value V in the sequence
12210           // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12211           // V <=u UINT_MAX.  Thus, we must exit the loop before unsigned
12212           // overflow occurs.  This limit also implies that a signed comparison
12213           // (in the wide bitwidth) is equivalent to an unsigned comparison as
12214           // the high bits on both sides must be zero.
12215           APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12216           APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12217           Limit = Limit.zext(OuterBitWidth);
12218           return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12219         };
12220         auto Flags = AR->getNoWrapFlags();
12221         if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12222           Flags = setFlags(Flags, SCEV::FlagNUW);
12223 
12224         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12225         if (AR->hasNoUnsignedWrap()) {
12226           // Emulate what getZeroExtendExpr would have done during construction
12227           // if we'd been able to infer the fact just above at that time.
12228           const SCEV *Step = AR->getStepRecurrence(*this);
12229           Type *Ty = ZExt->getType();
12230           auto *S = getAddRecExpr(
12231             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12232             getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12233           IV = dyn_cast<SCEVAddRecExpr>(S);
12234         }
12235       }
12236     }
12237   }
12238 
12239 
12240   if (!IV && AllowPredicates) {
12241     // Try to make this an AddRec using runtime tests, in the first X
12242     // iterations of this loop, where X is the SCEV expression found by the
12243     // algorithm below.
12244     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12245     PredicatedIV = true;
12246   }
12247 
12248   // Avoid weird loops
12249   if (!IV || IV->getLoop() != L || !IV->isAffine())
12250     return getCouldNotCompute();
12251 
12252   // A precondition of this method is that the condition being analyzed
12253   // reaches an exiting branch which dominates the latch.  Given that, we can
12254   // assume that an increment which violates the nowrap specification and
12255   // produces poison must cause undefined behavior when the resulting poison
12256   // value is branched upon and thus we can conclude that the backedge is
12257   // taken no more often than would be required to produce that poison value.
12258   // Note that a well defined loop can exit on the iteration which violates
12259   // the nowrap specification if there is another exit (either explicit or
12260   // implicit/exceptional) which causes the loop to execute before the
12261   // exiting instruction we're analyzing would trigger UB.
12262   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12263   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12264   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12265 
12266   const SCEV *Stride = IV->getStepRecurrence(*this);
12267 
12268   bool PositiveStride = isKnownPositive(Stride);
12269 
12270   // Avoid negative or zero stride values.
12271   if (!PositiveStride) {
12272     // We can compute the correct backedge taken count for loops with unknown
12273     // strides if we can prove that the loop is not an infinite loop with side
12274     // effects. Here's the loop structure we are trying to handle -
12275     //
12276     // i = start
12277     // do {
12278     //   A[i] = i;
12279     //   i += s;
12280     // } while (i < end);
12281     //
12282     // The backedge taken count for such loops is evaluated as -
12283     // (max(end, start + stride) - start - 1) /u stride
12284     //
12285     // The additional preconditions that we need to check to prove correctness
12286     // of the above formula is as follows -
12287     //
12288     // a) IV is either nuw or nsw depending upon signedness (indicated by the
12289     //    NoWrap flag).
12290     // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12291     //    no side effects within the loop)
12292     // c) loop has a single static exit (with no abnormal exits)
12293     //
12294     // Precondition a) implies that if the stride is negative, this is a single
12295     // trip loop. The backedge taken count formula reduces to zero in this case.
12296     //
12297     // Precondition b) and c) combine to imply that if rhs is invariant in L,
12298     // then a zero stride means the backedge can't be taken without executing
12299     // undefined behavior.
12300     //
12301     // The positive stride case is the same as isKnownPositive(Stride) returning
12302     // true (original behavior of the function).
12303     //
12304     if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12305         !loopHasNoAbnormalExits(L))
12306       return getCouldNotCompute();
12307 
12308     // This bailout is protecting the logic in computeMaxBECountForLT which
12309     // has not yet been sufficiently auditted or tested with negative strides.
12310     // We used to filter out all known-non-positive cases here, we're in the
12311     // process of being less restrictive bit by bit.
12312     if (IsSigned && isKnownNonPositive(Stride))
12313       return getCouldNotCompute();
12314 
12315     if (!isKnownNonZero(Stride)) {
12316       // If we have a step of zero, and RHS isn't invariant in L, we don't know
12317       // if it might eventually be greater than start and if so, on which
12318       // iteration.  We can't even produce a useful upper bound.
12319       if (!isLoopInvariant(RHS, L))
12320         return getCouldNotCompute();
12321 
12322       // We allow a potentially zero stride, but we need to divide by stride
12323       // below.  Since the loop can't be infinite and this check must control
12324       // the sole exit, we can infer the exit must be taken on the first
12325       // iteration (e.g. backedge count = 0) if the stride is zero.  Given that,
12326       // we know the numerator in the divides below must be zero, so we can
12327       // pick an arbitrary non-zero value for the denominator (e.g. stride)
12328       // and produce the right result.
12329       // FIXME: Handle the case where Stride is poison?
12330       auto wouldZeroStrideBeUB = [&]() {
12331         // Proof by contradiction.  Suppose the stride were zero.  If we can
12332         // prove that the backedge *is* taken on the first iteration, then since
12333         // we know this condition controls the sole exit, we must have an
12334         // infinite loop.  We can't have a (well defined) infinite loop per
12335         // check just above.
12336         // Note: The (Start - Stride) term is used to get the start' term from
12337         // (start' + stride,+,stride). Remember that we only care about the
12338         // result of this expression when stride == 0 at runtime.
12339         auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12340         return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12341       };
12342       if (!wouldZeroStrideBeUB()) {
12343         Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12344       }
12345     }
12346   } else if (!Stride->isOne() && !NoWrap) {
12347     auto isUBOnWrap = [&]() {
12348       // From no-self-wrap, we need to then prove no-(un)signed-wrap.  This
12349       // follows trivially from the fact that every (un)signed-wrapped, but
12350       // not self-wrapped value must be LT than the last value before
12351       // (un)signed wrap.  Since we know that last value didn't exit, nor
12352       // will any smaller one.
12353       return canAssumeNoSelfWrap(IV);
12354     };
12355 
12356     // Avoid proven overflow cases: this will ensure that the backedge taken
12357     // count will not generate any unsigned overflow. Relaxed no-overflow
12358     // conditions exploit NoWrapFlags, allowing to optimize in presence of
12359     // undefined behaviors like the case of C language.
12360     if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12361       return getCouldNotCompute();
12362   }
12363 
12364   // On all paths just preceeding, we established the following invariant:
12365   //   IV can be assumed not to overflow up to and including the exiting
12366   //   iteration.  We proved this in one of two ways:
12367   //   1) We can show overflow doesn't occur before the exiting iteration
12368   //      1a) canIVOverflowOnLT, and b) step of one
12369   //   2) We can show that if overflow occurs, the loop must execute UB
12370   //      before any possible exit.
12371   // Note that we have not yet proved RHS invariant (in general).
12372 
12373   const SCEV *Start = IV->getStart();
12374 
12375   // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12376   // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12377   // Use integer-typed versions for actual computation; we can't subtract
12378   // pointers in general.
12379   const SCEV *OrigStart = Start;
12380   const SCEV *OrigRHS = RHS;
12381   if (Start->getType()->isPointerTy()) {
12382     Start = getLosslessPtrToIntExpr(Start);
12383     if (isa<SCEVCouldNotCompute>(Start))
12384       return Start;
12385   }
12386   if (RHS->getType()->isPointerTy()) {
12387     RHS = getLosslessPtrToIntExpr(RHS);
12388     if (isa<SCEVCouldNotCompute>(RHS))
12389       return RHS;
12390   }
12391 
12392   // When the RHS is not invariant, we do not know the end bound of the loop and
12393   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12394   // calculate the MaxBECount, given the start, stride and max value for the end
12395   // bound of the loop (RHS), and the fact that IV does not overflow (which is
12396   // checked above).
12397   if (!isLoopInvariant(RHS, L)) {
12398     const SCEV *MaxBECount = computeMaxBECountForLT(
12399         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12400     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12401                      false /*MaxOrZero*/, Predicates);
12402   }
12403 
12404   // We use the expression (max(End,Start)-Start)/Stride to describe the
12405   // backedge count, as if the backedge is taken at least once max(End,Start)
12406   // is End and so the result is as above, and if not max(End,Start) is Start
12407   // so we get a backedge count of zero.
12408   const SCEV *BECount = nullptr;
12409   auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12410   assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12411   assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12412   assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12413   // Can we prove (max(RHS,Start) > Start - Stride?
12414   if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12415       isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12416     // In this case, we can use a refined formula for computing backedge taken
12417     // count.  The general formula remains:
12418     //   "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12419     // We want to use the alternate formula:
12420     //   "((End - 1) - (Start - Stride)) /u Stride"
12421     // Let's do a quick case analysis to show these are equivalent under
12422     // our precondition that max(RHS,Start) > Start - Stride.
12423     // * For RHS <= Start, the backedge-taken count must be zero.
12424     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12425     //   "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12426     //   "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12427     //     of Stride.  For 0 stride, we've use umin(1,Stride) above, reducing
12428     //     this to the stride of 1 case.
12429     // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12430     //   "((End - 1) - (Start - Stride)) /u Stride" reduces to
12431     //   "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12432     //   "((RHS - (Start - Stride) - 1) /u Stride".
12433     //   Our preconditions trivially imply no overflow in that form.
12434     const SCEV *MinusOne = getMinusOne(Stride->getType());
12435     const SCEV *Numerator =
12436         getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12437     BECount = getUDivExpr(Numerator, Stride);
12438   }
12439 
12440   const SCEV *BECountIfBackedgeTaken = nullptr;
12441   if (!BECount) {
12442     auto canProveRHSGreaterThanEqualStart = [&]() {
12443       auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12444       if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12445         return true;
12446 
12447       // (RHS > Start - 1) implies RHS >= Start.
12448       // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12449       //   "Start - 1" doesn't overflow.
12450       // * For signed comparison, if Start - 1 does overflow, it's equal
12451       //   to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12452       // * For unsigned comparison, if Start - 1 does overflow, it's equal
12453       //   to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12454       //
12455       // FIXME: Should isLoopEntryGuardedByCond do this for us?
12456       auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12457       auto *StartMinusOne = getAddExpr(OrigStart,
12458                                        getMinusOne(OrigStart->getType()));
12459       return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12460     };
12461 
12462     // If we know that RHS >= Start in the context of loop, then we know that
12463     // max(RHS, Start) = RHS at this point.
12464     const SCEV *End;
12465     if (canProveRHSGreaterThanEqualStart()) {
12466       End = RHS;
12467     } else {
12468       // If RHS < Start, the backedge will be taken zero times.  So in
12469       // general, we can write the backedge-taken count as:
12470       //
12471       //     RHS >= Start ? ceil(RHS - Start) / Stride : 0
12472       //
12473       // We convert it to the following to make it more convenient for SCEV:
12474       //
12475       //     ceil(max(RHS, Start) - Start) / Stride
12476       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12477 
12478       // See what would happen if we assume the backedge is taken. This is
12479       // used to compute MaxBECount.
12480       BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12481     }
12482 
12483     // At this point, we know:
12484     //
12485     // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12486     // 2. The index variable doesn't overflow.
12487     //
12488     // Therefore, we know N exists such that
12489     // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12490     // doesn't overflow.
12491     //
12492     // Using this information, try to prove whether the addition in
12493     // "(Start - End) + (Stride - 1)" has unsigned overflow.
12494     const SCEV *One = getOne(Stride->getType());
12495     bool MayAddOverflow = [&] {
12496       if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12497         if (StrideC->getAPInt().isPowerOf2()) {
12498           // Suppose Stride is a power of two, and Start/End are unsigned
12499           // integers.  Let UMAX be the largest representable unsigned
12500           // integer.
12501           //
12502           // By the preconditions of this function, we know
12503           // "(Start + Stride * N) >= End", and this doesn't overflow.
12504           // As a formula:
12505           //
12506           //   End <= (Start + Stride * N) <= UMAX
12507           //
12508           // Subtracting Start from all the terms:
12509           //
12510           //   End - Start <= Stride * N <= UMAX - Start
12511           //
12512           // Since Start is unsigned, UMAX - Start <= UMAX.  Therefore:
12513           //
12514           //   End - Start <= Stride * N <= UMAX
12515           //
12516           // Stride * N is a multiple of Stride. Therefore,
12517           //
12518           //   End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12519           //
12520           // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12521           // Therefore, UMAX mod Stride == Stride - 1.  So we can write:
12522           //
12523           //   End - Start <= Stride * N <= UMAX - Stride - 1
12524           //
12525           // Dropping the middle term:
12526           //
12527           //   End - Start <= UMAX - Stride - 1
12528           //
12529           // Adding Stride - 1 to both sides:
12530           //
12531           //   (End - Start) + (Stride - 1) <= UMAX
12532           //
12533           // In other words, the addition doesn't have unsigned overflow.
12534           //
12535           // A similar proof works if we treat Start/End as signed values.
12536           // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12537           // use signed max instead of unsigned max. Note that we're trying
12538           // to prove a lack of unsigned overflow in either case.
12539           return false;
12540         }
12541       }
12542       if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12543         // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12544         // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12545         // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12546         //
12547         // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12548         return false;
12549       }
12550       return true;
12551     }();
12552 
12553     const SCEV *Delta = getMinusSCEV(End, Start);
12554     if (!MayAddOverflow) {
12555       // floor((D + (S - 1)) / S)
12556       // We prefer this formulation if it's legal because it's fewer operations.
12557       BECount =
12558           getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
12559     } else {
12560       BECount = getUDivCeilSCEV(Delta, Stride);
12561     }
12562   }
12563 
12564   const SCEV *MaxBECount;
12565   bool MaxOrZero = false;
12566   if (isa<SCEVConstant>(BECount)) {
12567     MaxBECount = BECount;
12568   } else if (BECountIfBackedgeTaken &&
12569              isa<SCEVConstant>(BECountIfBackedgeTaken)) {
12570     // If we know exactly how many times the backedge will be taken if it's
12571     // taken at least once, then the backedge count will either be that or
12572     // zero.
12573     MaxBECount = BECountIfBackedgeTaken;
12574     MaxOrZero = true;
12575   } else {
12576     MaxBECount = computeMaxBECountForLT(
12577         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12578   }
12579 
12580   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
12581       !isa<SCEVCouldNotCompute>(BECount))
12582     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
12583 
12584   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
12585 }
12586 
12587 ScalarEvolution::ExitLimit
12588 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
12589                                      const Loop *L, bool IsSigned,
12590                                      bool ControlsExit, bool AllowPredicates) {
12591   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12592   // We handle only IV > Invariant
12593   if (!isLoopInvariant(RHS, L))
12594     return getCouldNotCompute();
12595 
12596   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12597   if (!IV && AllowPredicates)
12598     // Try to make this an AddRec using runtime tests, in the first X
12599     // iterations of this loop, where X is the SCEV expression found by the
12600     // algorithm below.
12601     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12602 
12603   // Avoid weird loops
12604   if (!IV || IV->getLoop() != L || !IV->isAffine())
12605     return getCouldNotCompute();
12606 
12607   auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12608   bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12609   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12610 
12611   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
12612 
12613   // Avoid negative or zero stride values
12614   if (!isKnownPositive(Stride))
12615     return getCouldNotCompute();
12616 
12617   // Avoid proven overflow cases: this will ensure that the backedge taken count
12618   // will not generate any unsigned overflow. Relaxed no-overflow conditions
12619   // exploit NoWrapFlags, allowing to optimize in presence of undefined
12620   // behaviors like the case of C language.
12621   if (!Stride->isOne() && !NoWrap)
12622     if (canIVOverflowOnGT(RHS, Stride, IsSigned))
12623       return getCouldNotCompute();
12624 
12625   const SCEV *Start = IV->getStart();
12626   const SCEV *End = RHS;
12627   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
12628     // If we know that Start >= RHS in the context of loop, then we know that
12629     // min(RHS, Start) = RHS at this point.
12630     if (isLoopEntryGuardedByCond(
12631             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
12632       End = RHS;
12633     else
12634       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
12635   }
12636 
12637   if (Start->getType()->isPointerTy()) {
12638     Start = getLosslessPtrToIntExpr(Start);
12639     if (isa<SCEVCouldNotCompute>(Start))
12640       return Start;
12641   }
12642   if (End->getType()->isPointerTy()) {
12643     End = getLosslessPtrToIntExpr(End);
12644     if (isa<SCEVCouldNotCompute>(End))
12645       return End;
12646   }
12647 
12648   // Compute ((Start - End) + (Stride - 1)) / Stride.
12649   // FIXME: This can overflow. Holding off on fixing this for now;
12650   // howManyGreaterThans will hopefully be gone soon.
12651   const SCEV *One = getOne(Stride->getType());
12652   const SCEV *BECount = getUDivExpr(
12653       getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
12654 
12655   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
12656                             : getUnsignedRangeMax(Start);
12657 
12658   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
12659                              : getUnsignedRangeMin(Stride);
12660 
12661   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
12662   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
12663                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
12664 
12665   // Although End can be a MIN expression we estimate MinEnd considering only
12666   // the case End = RHS. This is safe because in the other case (Start - End)
12667   // is zero, leading to a zero maximum backedge taken count.
12668   APInt MinEnd =
12669     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
12670              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
12671 
12672   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
12673                                ? BECount
12674                                : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
12675                                                  getConstant(MinStride));
12676 
12677   if (isa<SCEVCouldNotCompute>(MaxBECount))
12678     MaxBECount = BECount;
12679 
12680   return ExitLimit(BECount, MaxBECount, false, Predicates);
12681 }
12682 
12683 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
12684                                                     ScalarEvolution &SE) const {
12685   if (Range.isFullSet())  // Infinite loop.
12686     return SE.getCouldNotCompute();
12687 
12688   // If the start is a non-zero constant, shift the range to simplify things.
12689   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
12690     if (!SC->getValue()->isZero()) {
12691       SmallVector<const SCEV *, 4> Operands(operands());
12692       Operands[0] = SE.getZero(SC->getType());
12693       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
12694                                              getNoWrapFlags(FlagNW));
12695       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
12696         return ShiftedAddRec->getNumIterationsInRange(
12697             Range.subtract(SC->getAPInt()), SE);
12698       // This is strange and shouldn't happen.
12699       return SE.getCouldNotCompute();
12700     }
12701 
12702   // The only time we can solve this is when we have all constant indices.
12703   // Otherwise, we cannot determine the overflow conditions.
12704   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
12705     return SE.getCouldNotCompute();
12706 
12707   // Okay at this point we know that all elements of the chrec are constants and
12708   // that the start element is zero.
12709 
12710   // First check to see if the range contains zero.  If not, the first
12711   // iteration exits.
12712   unsigned BitWidth = SE.getTypeSizeInBits(getType());
12713   if (!Range.contains(APInt(BitWidth, 0)))
12714     return SE.getZero(getType());
12715 
12716   if (isAffine()) {
12717     // If this is an affine expression then we have this situation:
12718     //   Solve {0,+,A} in Range  ===  Ax in Range
12719 
12720     // We know that zero is in the range.  If A is positive then we know that
12721     // the upper value of the range must be the first possible exit value.
12722     // If A is negative then the lower of the range is the last possible loop
12723     // value.  Also note that we already checked for a full range.
12724     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
12725     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
12726 
12727     // The exit value should be (End+A)/A.
12728     APInt ExitVal = (End + A).udiv(A);
12729     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
12730 
12731     // Evaluate at the exit value.  If we really did fall out of the valid
12732     // range, then we computed our trip count, otherwise wrap around or other
12733     // things must have happened.
12734     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
12735     if (Range.contains(Val->getValue()))
12736       return SE.getCouldNotCompute();  // Something strange happened
12737 
12738     // Ensure that the previous value is in the range.
12739     assert(Range.contains(
12740            EvaluateConstantChrecAtConstant(this,
12741            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
12742            "Linear scev computation is off in a bad way!");
12743     return SE.getConstant(ExitValue);
12744   }
12745 
12746   if (isQuadratic()) {
12747     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
12748       return SE.getConstant(S.getValue());
12749   }
12750 
12751   return SE.getCouldNotCompute();
12752 }
12753 
12754 const SCEVAddRecExpr *
12755 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
12756   assert(getNumOperands() > 1 && "AddRec with zero step?");
12757   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
12758   // but in this case we cannot guarantee that the value returned will be an
12759   // AddRec because SCEV does not have a fixed point where it stops
12760   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
12761   // may happen if we reach arithmetic depth limit while simplifying. So we
12762   // construct the returned value explicitly.
12763   SmallVector<const SCEV *, 3> Ops;
12764   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
12765   // (this + Step) is {A+B,+,B+C,+...,+,N}.
12766   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
12767     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
12768   // We know that the last operand is not a constant zero (otherwise it would
12769   // have been popped out earlier). This guarantees us that if the result has
12770   // the same last operand, then it will also not be popped out, meaning that
12771   // the returned value will be an AddRec.
12772   const SCEV *Last = getOperand(getNumOperands() - 1);
12773   assert(!Last->isZero() && "Recurrency with zero step?");
12774   Ops.push_back(Last);
12775   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
12776                                                SCEV::FlagAnyWrap));
12777 }
12778 
12779 // Return true when S contains at least an undef value.
12780 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
12781   return SCEVExprContains(S, [](const SCEV *S) {
12782     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
12783       return isa<UndefValue>(SU->getValue());
12784     return false;
12785   });
12786 }
12787 
12788 /// Return the size of an element read or written by Inst.
12789 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
12790   Type *Ty;
12791   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
12792     Ty = Store->getValueOperand()->getType();
12793   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
12794     Ty = Load->getType();
12795   else
12796     return nullptr;
12797 
12798   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
12799   return getSizeOfExpr(ETy, Ty);
12800 }
12801 
12802 //===----------------------------------------------------------------------===//
12803 //                   SCEVCallbackVH Class Implementation
12804 //===----------------------------------------------------------------------===//
12805 
12806 void ScalarEvolution::SCEVCallbackVH::deleted() {
12807   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12808   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
12809     SE->ConstantEvolutionLoopExitValue.erase(PN);
12810   SE->eraseValueFromMap(getValPtr());
12811   // this now dangles!
12812 }
12813 
12814 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
12815   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
12816 
12817   // Forget all the expressions associated with users of the old value,
12818   // so that future queries will recompute the expressions using the new
12819   // value.
12820   Value *Old = getValPtr();
12821   SmallVector<User *, 16> Worklist(Old->users());
12822   SmallPtrSet<User *, 8> Visited;
12823   while (!Worklist.empty()) {
12824     User *U = Worklist.pop_back_val();
12825     // Deleting the Old value will cause this to dangle. Postpone
12826     // that until everything else is done.
12827     if (U == Old)
12828       continue;
12829     if (!Visited.insert(U).second)
12830       continue;
12831     if (PHINode *PN = dyn_cast<PHINode>(U))
12832       SE->ConstantEvolutionLoopExitValue.erase(PN);
12833     SE->eraseValueFromMap(U);
12834     llvm::append_range(Worklist, U->users());
12835   }
12836   // Delete the Old value.
12837   if (PHINode *PN = dyn_cast<PHINode>(Old))
12838     SE->ConstantEvolutionLoopExitValue.erase(PN);
12839   SE->eraseValueFromMap(Old);
12840   // this now dangles!
12841 }
12842 
12843 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
12844   : CallbackVH(V), SE(se) {}
12845 
12846 //===----------------------------------------------------------------------===//
12847 //                   ScalarEvolution Class Implementation
12848 //===----------------------------------------------------------------------===//
12849 
12850 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
12851                                  AssumptionCache &AC, DominatorTree &DT,
12852                                  LoopInfo &LI)
12853     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
12854       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
12855       LoopDispositions(64), BlockDispositions(64) {
12856   // To use guards for proving predicates, we need to scan every instruction in
12857   // relevant basic blocks, and not just terminators.  Doing this is a waste of
12858   // time if the IR does not actually contain any calls to
12859   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
12860   //
12861   // This pessimizes the case where a pass that preserves ScalarEvolution wants
12862   // to _add_ guards to the module when there weren't any before, and wants
12863   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
12864   // efficient in lieu of being smart in that rather obscure case.
12865 
12866   auto *GuardDecl = F.getParent()->getFunction(
12867       Intrinsic::getName(Intrinsic::experimental_guard));
12868   HasGuards = GuardDecl && !GuardDecl->use_empty();
12869 }
12870 
12871 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12872     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12873       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12874       ValueExprMap(std::move(Arg.ValueExprMap)),
12875       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12876       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12877       PendingMerges(std::move(Arg.PendingMerges)),
12878       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12879       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12880       PredicatedBackedgeTakenCounts(
12881           std::move(Arg.PredicatedBackedgeTakenCounts)),
12882       BECountUsers(std::move(Arg.BECountUsers)),
12883       ConstantEvolutionLoopExitValue(
12884           std::move(Arg.ConstantEvolutionLoopExitValue)),
12885       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12886       ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
12887       LoopDispositions(std::move(Arg.LoopDispositions)),
12888       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12889       BlockDispositions(std::move(Arg.BlockDispositions)),
12890       SCEVUsers(std::move(Arg.SCEVUsers)),
12891       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12892       SignedRanges(std::move(Arg.SignedRanges)),
12893       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12894       UniquePreds(std::move(Arg.UniquePreds)),
12895       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12896       LoopUsers(std::move(Arg.LoopUsers)),
12897       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12898       FirstUnknown(Arg.FirstUnknown) {
12899   Arg.FirstUnknown = nullptr;
12900 }
12901 
12902 ScalarEvolution::~ScalarEvolution() {
12903   // Iterate through all the SCEVUnknown instances and call their
12904   // destructors, so that they release their references to their values.
12905   for (SCEVUnknown *U = FirstUnknown; U;) {
12906     SCEVUnknown *Tmp = U;
12907     U = U->Next;
12908     Tmp->~SCEVUnknown();
12909   }
12910   FirstUnknown = nullptr;
12911 
12912   ExprValueMap.clear();
12913   ValueExprMap.clear();
12914   HasRecMap.clear();
12915   BackedgeTakenCounts.clear();
12916   PredicatedBackedgeTakenCounts.clear();
12917 
12918   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12919   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12920   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12921   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12922   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12923 }
12924 
12925 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12926   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12927 }
12928 
12929 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12930                           const Loop *L) {
12931   // Print all inner loops first
12932   for (Loop *I : *L)
12933     PrintLoopInfo(OS, SE, I);
12934 
12935   OS << "Loop ";
12936   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12937   OS << ": ";
12938 
12939   SmallVector<BasicBlock *, 8> ExitingBlocks;
12940   L->getExitingBlocks(ExitingBlocks);
12941   if (ExitingBlocks.size() != 1)
12942     OS << "<multiple exits> ";
12943 
12944   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12945     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12946   else
12947     OS << "Unpredictable backedge-taken count.\n";
12948 
12949   if (ExitingBlocks.size() > 1)
12950     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12951       OS << "  exit count for " << ExitingBlock->getName() << ": "
12952          << *SE->getExitCount(L, ExitingBlock) << "\n";
12953     }
12954 
12955   OS << "Loop ";
12956   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12957   OS << ": ";
12958 
12959   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12960     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12961     if (SE->isBackedgeTakenCountMaxOrZero(L))
12962       OS << ", actual taken count either this or zero.";
12963   } else {
12964     OS << "Unpredictable max backedge-taken count. ";
12965   }
12966 
12967   OS << "\n"
12968         "Loop ";
12969   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12970   OS << ": ";
12971 
12972   SmallVector<const SCEVPredicate *, 4> Preds;
12973   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
12974   if (!isa<SCEVCouldNotCompute>(PBT)) {
12975     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12976     OS << " Predicates:\n";
12977     for (auto *P : Preds)
12978       P->print(OS, 4);
12979   } else {
12980     OS << "Unpredictable predicated backedge-taken count. ";
12981   }
12982   OS << "\n";
12983 
12984   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12985     OS << "Loop ";
12986     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12987     OS << ": ";
12988     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12989   }
12990 }
12991 
12992 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12993   switch (LD) {
12994   case ScalarEvolution::LoopVariant:
12995     return "Variant";
12996   case ScalarEvolution::LoopInvariant:
12997     return "Invariant";
12998   case ScalarEvolution::LoopComputable:
12999     return "Computable";
13000   }
13001   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
13002 }
13003 
13004 void ScalarEvolution::print(raw_ostream &OS) const {
13005   // ScalarEvolution's implementation of the print method is to print
13006   // out SCEV values of all instructions that are interesting. Doing
13007   // this potentially causes it to create new SCEV objects though,
13008   // which technically conflicts with the const qualifier. This isn't
13009   // observable from outside the class though, so casting away the
13010   // const isn't dangerous.
13011   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13012 
13013   if (ClassifyExpressions) {
13014     OS << "Classifying expressions for: ";
13015     F.printAsOperand(OS, /*PrintType=*/false);
13016     OS << "\n";
13017     for (Instruction &I : instructions(F))
13018       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13019         OS << I << '\n';
13020         OS << "  -->  ";
13021         const SCEV *SV = SE.getSCEV(&I);
13022         SV->print(OS);
13023         if (!isa<SCEVCouldNotCompute>(SV)) {
13024           OS << " U: ";
13025           SE.getUnsignedRange(SV).print(OS);
13026           OS << " S: ";
13027           SE.getSignedRange(SV).print(OS);
13028         }
13029 
13030         const Loop *L = LI.getLoopFor(I.getParent());
13031 
13032         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13033         if (AtUse != SV) {
13034           OS << "  -->  ";
13035           AtUse->print(OS);
13036           if (!isa<SCEVCouldNotCompute>(AtUse)) {
13037             OS << " U: ";
13038             SE.getUnsignedRange(AtUse).print(OS);
13039             OS << " S: ";
13040             SE.getSignedRange(AtUse).print(OS);
13041           }
13042         }
13043 
13044         if (L) {
13045           OS << "\t\t" "Exits: ";
13046           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13047           if (!SE.isLoopInvariant(ExitValue, L)) {
13048             OS << "<<Unknown>>";
13049           } else {
13050             OS << *ExitValue;
13051           }
13052 
13053           bool First = true;
13054           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13055             if (First) {
13056               OS << "\t\t" "LoopDispositions: { ";
13057               First = false;
13058             } else {
13059               OS << ", ";
13060             }
13061 
13062             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13063             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
13064           }
13065 
13066           for (auto *InnerL : depth_first(L)) {
13067             if (InnerL == L)
13068               continue;
13069             if (First) {
13070               OS << "\t\t" "LoopDispositions: { ";
13071               First = false;
13072             } else {
13073               OS << ", ";
13074             }
13075 
13076             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13077             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
13078           }
13079 
13080           OS << " }";
13081         }
13082 
13083         OS << "\n";
13084       }
13085   }
13086 
13087   OS << "Determining loop execution counts for: ";
13088   F.printAsOperand(OS, /*PrintType=*/false);
13089   OS << "\n";
13090   for (Loop *I : LI)
13091     PrintLoopInfo(OS, &SE, I);
13092 }
13093 
13094 ScalarEvolution::LoopDisposition
13095 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13096   auto &Values = LoopDispositions[S];
13097   for (auto &V : Values) {
13098     if (V.getPointer() == L)
13099       return V.getInt();
13100   }
13101   Values.emplace_back(L, LoopVariant);
13102   LoopDisposition D = computeLoopDisposition(S, L);
13103   auto &Values2 = LoopDispositions[S];
13104   for (auto &V : llvm::reverse(Values2)) {
13105     if (V.getPointer() == L) {
13106       V.setInt(D);
13107       break;
13108     }
13109   }
13110   return D;
13111 }
13112 
13113 ScalarEvolution::LoopDisposition
13114 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13115   switch (S->getSCEVType()) {
13116   case scConstant:
13117     return LoopInvariant;
13118   case scPtrToInt:
13119   case scTruncate:
13120   case scZeroExtend:
13121   case scSignExtend:
13122     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
13123   case scAddRecExpr: {
13124     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13125 
13126     // If L is the addrec's loop, it's computable.
13127     if (AR->getLoop() == L)
13128       return LoopComputable;
13129 
13130     // Add recurrences are never invariant in the function-body (null loop).
13131     if (!L)
13132       return LoopVariant;
13133 
13134     // Everything that is not defined at loop entry is variant.
13135     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13136       return LoopVariant;
13137     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13138            " dominate the contained loop's header?");
13139 
13140     // This recurrence is invariant w.r.t. L if AR's loop contains L.
13141     if (AR->getLoop()->contains(L))
13142       return LoopInvariant;
13143 
13144     // This recurrence is variant w.r.t. L if any of its operands
13145     // are variant.
13146     for (auto *Op : AR->operands())
13147       if (!isLoopInvariant(Op, L))
13148         return LoopVariant;
13149 
13150     // Otherwise it's loop-invariant.
13151     return LoopInvariant;
13152   }
13153   case scAddExpr:
13154   case scMulExpr:
13155   case scUMaxExpr:
13156   case scSMaxExpr:
13157   case scUMinExpr:
13158   case scSMinExpr:
13159   case scSequentialUMinExpr: {
13160     bool HasVarying = false;
13161     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
13162       LoopDisposition D = getLoopDisposition(Op, L);
13163       if (D == LoopVariant)
13164         return LoopVariant;
13165       if (D == LoopComputable)
13166         HasVarying = true;
13167     }
13168     return HasVarying ? LoopComputable : LoopInvariant;
13169   }
13170   case scUDivExpr: {
13171     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13172     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
13173     if (LD == LoopVariant)
13174       return LoopVariant;
13175     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
13176     if (RD == LoopVariant)
13177       return LoopVariant;
13178     return (LD == LoopInvariant && RD == LoopInvariant) ?
13179            LoopInvariant : LoopComputable;
13180   }
13181   case scUnknown:
13182     // All non-instruction values are loop invariant.  All instructions are loop
13183     // invariant if they are not contained in the specified loop.
13184     // Instructions are never considered invariant in the function body
13185     // (null loop) because they are defined within the "loop".
13186     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13187       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13188     return LoopInvariant;
13189   case scCouldNotCompute:
13190     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13191   }
13192   llvm_unreachable("Unknown SCEV kind!");
13193 }
13194 
13195 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13196   return getLoopDisposition(S, L) == LoopInvariant;
13197 }
13198 
13199 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13200   return getLoopDisposition(S, L) == LoopComputable;
13201 }
13202 
13203 ScalarEvolution::BlockDisposition
13204 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13205   auto &Values = BlockDispositions[S];
13206   for (auto &V : Values) {
13207     if (V.getPointer() == BB)
13208       return V.getInt();
13209   }
13210   Values.emplace_back(BB, DoesNotDominateBlock);
13211   BlockDisposition D = computeBlockDisposition(S, BB);
13212   auto &Values2 = BlockDispositions[S];
13213   for (auto &V : llvm::reverse(Values2)) {
13214     if (V.getPointer() == BB) {
13215       V.setInt(D);
13216       break;
13217     }
13218   }
13219   return D;
13220 }
13221 
13222 ScalarEvolution::BlockDisposition
13223 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13224   switch (S->getSCEVType()) {
13225   case scConstant:
13226     return ProperlyDominatesBlock;
13227   case scPtrToInt:
13228   case scTruncate:
13229   case scZeroExtend:
13230   case scSignExtend:
13231     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
13232   case scAddRecExpr: {
13233     // This uses a "dominates" query instead of "properly dominates" query
13234     // to test for proper dominance too, because the instruction which
13235     // produces the addrec's value is a PHI, and a PHI effectively properly
13236     // dominates its entire containing block.
13237     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13238     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13239       return DoesNotDominateBlock;
13240 
13241     // Fall through into SCEVNAryExpr handling.
13242     LLVM_FALLTHROUGH;
13243   }
13244   case scAddExpr:
13245   case scMulExpr:
13246   case scUMaxExpr:
13247   case scSMaxExpr:
13248   case scUMinExpr:
13249   case scSMinExpr:
13250   case scSequentialUMinExpr: {
13251     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
13252     bool Proper = true;
13253     for (const SCEV *NAryOp : NAry->operands()) {
13254       BlockDisposition D = getBlockDisposition(NAryOp, BB);
13255       if (D == DoesNotDominateBlock)
13256         return DoesNotDominateBlock;
13257       if (D == DominatesBlock)
13258         Proper = false;
13259     }
13260     return Proper ? ProperlyDominatesBlock : DominatesBlock;
13261   }
13262   case scUDivExpr: {
13263     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
13264     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
13265     BlockDisposition LD = getBlockDisposition(LHS, BB);
13266     if (LD == DoesNotDominateBlock)
13267       return DoesNotDominateBlock;
13268     BlockDisposition RD = getBlockDisposition(RHS, BB);
13269     if (RD == DoesNotDominateBlock)
13270       return DoesNotDominateBlock;
13271     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
13272       ProperlyDominatesBlock : DominatesBlock;
13273   }
13274   case scUnknown:
13275     if (Instruction *I =
13276           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13277       if (I->getParent() == BB)
13278         return DominatesBlock;
13279       if (DT.properlyDominates(I->getParent(), BB))
13280         return ProperlyDominatesBlock;
13281       return DoesNotDominateBlock;
13282     }
13283     return ProperlyDominatesBlock;
13284   case scCouldNotCompute:
13285     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13286   }
13287   llvm_unreachable("Unknown SCEV kind!");
13288 }
13289 
13290 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13291   return getBlockDisposition(S, BB) >= DominatesBlock;
13292 }
13293 
13294 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13295   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13296 }
13297 
13298 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13299   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13300 }
13301 
13302 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13303                                                 bool Predicated) {
13304   auto &BECounts =
13305       Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13306   auto It = BECounts.find(L);
13307   if (It != BECounts.end()) {
13308     for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13309       if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13310         auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13311         assert(UserIt != BECountUsers.end());
13312         UserIt->second.erase({L, Predicated});
13313       }
13314     }
13315     BECounts.erase(It);
13316   }
13317 }
13318 
13319 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13320   SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13321   SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13322 
13323   while (!Worklist.empty()) {
13324     const SCEV *Curr = Worklist.pop_back_val();
13325     auto Users = SCEVUsers.find(Curr);
13326     if (Users != SCEVUsers.end())
13327       for (auto *User : Users->second)
13328         if (ToForget.insert(User).second)
13329           Worklist.push_back(User);
13330   }
13331 
13332   for (auto *S : ToForget)
13333     forgetMemoizedResultsImpl(S);
13334 
13335   for (auto I = PredicatedSCEVRewrites.begin();
13336        I != PredicatedSCEVRewrites.end();) {
13337     std::pair<const SCEV *, const Loop *> Entry = I->first;
13338     if (ToForget.count(Entry.first))
13339       PredicatedSCEVRewrites.erase(I++);
13340     else
13341       ++I;
13342   }
13343 }
13344 
13345 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13346   LoopDispositions.erase(S);
13347   BlockDispositions.erase(S);
13348   UnsignedRanges.erase(S);
13349   SignedRanges.erase(S);
13350   HasRecMap.erase(S);
13351   MinTrailingZerosCache.erase(S);
13352 
13353   auto ExprIt = ExprValueMap.find(S);
13354   if (ExprIt != ExprValueMap.end()) {
13355     for (Value *V : ExprIt->second) {
13356       auto ValueIt = ValueExprMap.find_as(V);
13357       if (ValueIt != ValueExprMap.end())
13358         ValueExprMap.erase(ValueIt);
13359     }
13360     ExprValueMap.erase(ExprIt);
13361   }
13362 
13363   auto ScopeIt = ValuesAtScopes.find(S);
13364   if (ScopeIt != ValuesAtScopes.end()) {
13365     for (const auto &Pair : ScopeIt->second)
13366       if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13367         erase_value(ValuesAtScopesUsers[Pair.second],
13368                     std::make_pair(Pair.first, S));
13369     ValuesAtScopes.erase(ScopeIt);
13370   }
13371 
13372   auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13373   if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13374     for (const auto &Pair : ScopeUserIt->second)
13375       erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13376     ValuesAtScopesUsers.erase(ScopeUserIt);
13377   }
13378 
13379   auto BEUsersIt = BECountUsers.find(S);
13380   if (BEUsersIt != BECountUsers.end()) {
13381     // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13382     auto Copy = BEUsersIt->second;
13383     for (const auto &Pair : Copy)
13384       forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13385     BECountUsers.erase(BEUsersIt);
13386   }
13387 }
13388 
13389 void
13390 ScalarEvolution::getUsedLoops(const SCEV *S,
13391                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13392   struct FindUsedLoops {
13393     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13394         : LoopsUsed(LoopsUsed) {}
13395     SmallPtrSetImpl<const Loop *> &LoopsUsed;
13396     bool follow(const SCEV *S) {
13397       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13398         LoopsUsed.insert(AR->getLoop());
13399       return true;
13400     }
13401 
13402     bool isDone() const { return false; }
13403   };
13404 
13405   FindUsedLoops F(LoopsUsed);
13406   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13407 }
13408 
13409 static void getReachableBlocks(SmallPtrSetImpl<BasicBlock *> &Reachable,
13410                                Function &F) {
13411   SmallVector<BasicBlock *> Worklist;
13412   Worklist.push_back(&F.getEntryBlock());
13413   while (!Worklist.empty()) {
13414     BasicBlock *BB = Worklist.pop_back_val();
13415     if (!Reachable.insert(BB).second)
13416       continue;
13417 
13418     const APInt *Cond;
13419     BasicBlock *TrueBB, *FalseBB;
13420     if (match(BB->getTerminator(),
13421               m_Br(m_APInt(Cond), m_BasicBlock(TrueBB), m_BasicBlock(FalseBB))))
13422       Worklist.push_back(Cond->isOne() ? TrueBB : FalseBB);
13423     else
13424       append_range(Worklist, successors(BB));
13425   }
13426 }
13427 
13428 void ScalarEvolution::verify() const {
13429   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13430   ScalarEvolution SE2(F, TLI, AC, DT, LI);
13431 
13432   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13433 
13434   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13435   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13436     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13437 
13438     const SCEV *visitConstant(const SCEVConstant *Constant) {
13439       return SE.getConstant(Constant->getAPInt());
13440     }
13441 
13442     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13443       return SE.getUnknown(Expr->getValue());
13444     }
13445 
13446     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13447       return SE.getCouldNotCompute();
13448     }
13449   };
13450 
13451   SCEVMapper SCM(SE2);
13452   SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13453   getReachableBlocks(ReachableBlocks, F);
13454 
13455   while (!LoopStack.empty()) {
13456     auto *L = LoopStack.pop_back_val();
13457     llvm::append_range(LoopStack, *L);
13458 
13459     // Only verify BECounts in reachable loops. For an unreachable loop,
13460     // any BECount is legal.
13461     if (!ReachableBlocks.contains(L->getHeader()))
13462       continue;
13463 
13464     auto *CurBECount = SCM.visit(
13465         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
13466     auto *NewBECount = SE2.getBackedgeTakenCount(L);
13467 
13468     if (CurBECount == SE2.getCouldNotCompute() ||
13469         NewBECount == SE2.getCouldNotCompute()) {
13470       // NB! This situation is legal, but is very suspicious -- whatever pass
13471       // change the loop to make a trip count go from could not compute to
13472       // computable or vice-versa *should have* invalidated SCEV.  However, we
13473       // choose not to assert here (for now) since we don't want false
13474       // positives.
13475       continue;
13476     }
13477 
13478     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
13479       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13480       // not propagate undef aggressively).  This means we can (and do) fail
13481       // verification in cases where a transform makes the trip count of a loop
13482       // go from "undef" to "undef+1" (say).  The transform is fine, since in
13483       // both cases the loop iterates "undef" times, but SCEV thinks we
13484       // increased the trip count of the loop by 1 incorrectly.
13485       continue;
13486     }
13487 
13488     if (SE.getTypeSizeInBits(CurBECount->getType()) >
13489         SE.getTypeSizeInBits(NewBECount->getType()))
13490       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13491     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13492              SE.getTypeSizeInBits(NewBECount->getType()))
13493       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13494 
13495     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
13496 
13497     // Unless VerifySCEVStrict is set, we only compare constant deltas.
13498     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
13499       dbgs() << "Trip Count for " << *L << " Changed!\n";
13500       dbgs() << "Old: " << *CurBECount << "\n";
13501       dbgs() << "New: " << *NewBECount << "\n";
13502       dbgs() << "Delta: " << *Delta << "\n";
13503       std::abort();
13504     }
13505   }
13506 
13507   // Collect all valid loops currently in LoopInfo.
13508   SmallPtrSet<Loop *, 32> ValidLoops;
13509   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
13510   while (!Worklist.empty()) {
13511     Loop *L = Worklist.pop_back_val();
13512     if (ValidLoops.insert(L).second)
13513       Worklist.append(L->begin(), L->end());
13514   }
13515   for (auto &KV : ValueExprMap) {
13516 #ifndef NDEBUG
13517     // Check for SCEV expressions referencing invalid/deleted loops.
13518     if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
13519       assert(ValidLoops.contains(AR->getLoop()) &&
13520              "AddRec references invalid loop");
13521     }
13522 #endif
13523 
13524     // Check that the value is also part of the reverse map.
13525     auto It = ExprValueMap.find(KV.second);
13526     if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
13527       dbgs() << "Value " << *KV.first
13528              << " is in ValueExprMap but not in ExprValueMap\n";
13529       std::abort();
13530     }
13531   }
13532 
13533   for (const auto &KV : ExprValueMap) {
13534     for (Value *V : KV.second) {
13535       auto It = ValueExprMap.find_as(V);
13536       if (It == ValueExprMap.end()) {
13537         dbgs() << "Value " << *V
13538                << " is in ExprValueMap but not in ValueExprMap\n";
13539         std::abort();
13540       }
13541       if (It->second != KV.first) {
13542         dbgs() << "Value " << *V << " mapped to " << *It->second
13543                << " rather than " << *KV.first << "\n";
13544         std::abort();
13545       }
13546     }
13547   }
13548 
13549   // Verify integrity of SCEV users.
13550   for (const auto &S : UniqueSCEVs) {
13551     SmallVector<const SCEV *, 4> Ops;
13552     collectUniqueOps(&S, Ops);
13553     for (const auto *Op : Ops) {
13554       // We do not store dependencies of constants.
13555       if (isa<SCEVConstant>(Op))
13556         continue;
13557       auto It = SCEVUsers.find(Op);
13558       if (It != SCEVUsers.end() && It->second.count(&S))
13559         continue;
13560       dbgs() << "Use of operand  " << *Op << " by user " << S
13561              << " is not being tracked!\n";
13562       std::abort();
13563     }
13564   }
13565 
13566   // Verify integrity of ValuesAtScopes users.
13567   for (const auto &ValueAndVec : ValuesAtScopes) {
13568     const SCEV *Value = ValueAndVec.first;
13569     for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
13570       const Loop *L = LoopAndValueAtScope.first;
13571       const SCEV *ValueAtScope = LoopAndValueAtScope.second;
13572       if (!isa<SCEVConstant>(ValueAtScope)) {
13573         auto It = ValuesAtScopesUsers.find(ValueAtScope);
13574         if (It != ValuesAtScopesUsers.end() &&
13575             is_contained(It->second, std::make_pair(L, Value)))
13576           continue;
13577         dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13578                << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
13579         std::abort();
13580       }
13581     }
13582   }
13583 
13584   for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
13585     const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
13586     for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
13587       const Loop *L = LoopAndValue.first;
13588       const SCEV *Value = LoopAndValue.second;
13589       assert(!isa<SCEVConstant>(Value));
13590       auto It = ValuesAtScopes.find(Value);
13591       if (It != ValuesAtScopes.end() &&
13592           is_contained(It->second, std::make_pair(L, ValueAtScope)))
13593         continue;
13594       dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
13595              << *ValueAtScope << " missing in ValuesAtScopes\n";
13596       std::abort();
13597     }
13598   }
13599 
13600   // Verify integrity of BECountUsers.
13601   auto VerifyBECountUsers = [&](bool Predicated) {
13602     auto &BECounts =
13603         Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13604     for (const auto &LoopAndBEInfo : BECounts) {
13605       for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
13606         if (!isa<SCEVConstant>(ENT.ExactNotTaken)) {
13607           auto UserIt = BECountUsers.find(ENT.ExactNotTaken);
13608           if (UserIt != BECountUsers.end() &&
13609               UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
13610             continue;
13611           dbgs() << "Value " << *ENT.ExactNotTaken << " for loop "
13612                  << *LoopAndBEInfo.first << " missing from BECountUsers\n";
13613           std::abort();
13614         }
13615       }
13616     }
13617   };
13618   VerifyBECountUsers(/* Predicated */ false);
13619   VerifyBECountUsers(/* Predicated */ true);
13620 }
13621 
13622 bool ScalarEvolution::invalidate(
13623     Function &F, const PreservedAnalyses &PA,
13624     FunctionAnalysisManager::Invalidator &Inv) {
13625   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
13626   // of its dependencies is invalidated.
13627   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
13628   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
13629          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
13630          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
13631          Inv.invalidate<LoopAnalysis>(F, PA);
13632 }
13633 
13634 AnalysisKey ScalarEvolutionAnalysis::Key;
13635 
13636 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
13637                                              FunctionAnalysisManager &AM) {
13638   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
13639                          AM.getResult<AssumptionAnalysis>(F),
13640                          AM.getResult<DominatorTreeAnalysis>(F),
13641                          AM.getResult<LoopAnalysis>(F));
13642 }
13643 
13644 PreservedAnalyses
13645 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
13646   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
13647   return PreservedAnalyses::all();
13648 }
13649 
13650 PreservedAnalyses
13651 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
13652   // For compatibility with opt's -analyze feature under legacy pass manager
13653   // which was not ported to NPM. This keeps tests using
13654   // update_analyze_test_checks.py working.
13655   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
13656      << F.getName() << "':\n";
13657   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
13658   return PreservedAnalyses::all();
13659 }
13660 
13661 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
13662                       "Scalar Evolution Analysis", false, true)
13663 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
13664 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
13665 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
13666 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
13667 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
13668                     "Scalar Evolution Analysis", false, true)
13669 
13670 char ScalarEvolutionWrapperPass::ID = 0;
13671 
13672 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
13673   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
13674 }
13675 
13676 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
13677   SE.reset(new ScalarEvolution(
13678       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
13679       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
13680       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
13681       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
13682   return false;
13683 }
13684 
13685 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
13686 
13687 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
13688   SE->print(OS);
13689 }
13690 
13691 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
13692   if (!VerifySCEV)
13693     return;
13694 
13695   SE->verify();
13696 }
13697 
13698 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
13699   AU.setPreservesAll();
13700   AU.addRequiredTransitive<AssumptionCacheTracker>();
13701   AU.addRequiredTransitive<LoopInfoWrapperPass>();
13702   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
13703   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
13704 }
13705 
13706 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
13707                                                         const SCEV *RHS) {
13708   return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
13709 }
13710 
13711 const SCEVPredicate *
13712 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
13713                                      const SCEV *LHS, const SCEV *RHS) {
13714   FoldingSetNodeID ID;
13715   assert(LHS->getType() == RHS->getType() &&
13716          "Type mismatch between LHS and RHS");
13717   // Unique this node based on the arguments
13718   ID.AddInteger(SCEVPredicate::P_Compare);
13719   ID.AddInteger(Pred);
13720   ID.AddPointer(LHS);
13721   ID.AddPointer(RHS);
13722   void *IP = nullptr;
13723   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13724     return S;
13725   SCEVComparePredicate *Eq = new (SCEVAllocator)
13726     SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
13727   UniquePreds.InsertNode(Eq, IP);
13728   return Eq;
13729 }
13730 
13731 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
13732     const SCEVAddRecExpr *AR,
13733     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13734   FoldingSetNodeID ID;
13735   // Unique this node based on the arguments
13736   ID.AddInteger(SCEVPredicate::P_Wrap);
13737   ID.AddPointer(AR);
13738   ID.AddInteger(AddedFlags);
13739   void *IP = nullptr;
13740   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
13741     return S;
13742   auto *OF = new (SCEVAllocator)
13743       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
13744   UniquePreds.InsertNode(OF, IP);
13745   return OF;
13746 }
13747 
13748 namespace {
13749 
13750 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
13751 public:
13752 
13753   /// Rewrites \p S in the context of a loop L and the SCEV predication
13754   /// infrastructure.
13755   ///
13756   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
13757   /// equivalences present in \p Pred.
13758   ///
13759   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
13760   /// \p NewPreds such that the result will be an AddRecExpr.
13761   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
13762                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13763                              const SCEVPredicate *Pred) {
13764     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
13765     return Rewriter.visit(S);
13766   }
13767 
13768   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13769     if (Pred) {
13770       if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
13771         for (auto *Pred : U->getPredicates())
13772           if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
13773             if (IPred->getLHS() == Expr &&
13774                 IPred->getPredicate() == ICmpInst::ICMP_EQ)
13775               return IPred->getRHS();
13776       } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
13777         if (IPred->getLHS() == Expr &&
13778             IPred->getPredicate() == ICmpInst::ICMP_EQ)
13779           return IPred->getRHS();
13780       }
13781     }
13782     return convertToAddRecWithPreds(Expr);
13783   }
13784 
13785   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
13786     const SCEV *Operand = visit(Expr->getOperand());
13787     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13788     if (AR && AR->getLoop() == L && AR->isAffine()) {
13789       // This couldn't be folded because the operand didn't have the nuw
13790       // flag. Add the nusw flag as an assumption that we could make.
13791       const SCEV *Step = AR->getStepRecurrence(SE);
13792       Type *Ty = Expr->getType();
13793       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
13794         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
13795                                 SE.getSignExtendExpr(Step, Ty), L,
13796                                 AR->getNoWrapFlags());
13797     }
13798     return SE.getZeroExtendExpr(Operand, Expr->getType());
13799   }
13800 
13801   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
13802     const SCEV *Operand = visit(Expr->getOperand());
13803     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
13804     if (AR && AR->getLoop() == L && AR->isAffine()) {
13805       // This couldn't be folded because the operand didn't have the nsw
13806       // flag. Add the nssw flag as an assumption that we could make.
13807       const SCEV *Step = AR->getStepRecurrence(SE);
13808       Type *Ty = Expr->getType();
13809       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
13810         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
13811                                 SE.getSignExtendExpr(Step, Ty), L,
13812                                 AR->getNoWrapFlags());
13813     }
13814     return SE.getSignExtendExpr(Operand, Expr->getType());
13815   }
13816 
13817 private:
13818   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
13819                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
13820                         const SCEVPredicate *Pred)
13821       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
13822 
13823   bool addOverflowAssumption(const SCEVPredicate *P) {
13824     if (!NewPreds) {
13825       // Check if we've already made this assumption.
13826       return Pred && Pred->implies(P);
13827     }
13828     NewPreds->insert(P);
13829     return true;
13830   }
13831 
13832   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
13833                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
13834     auto *A = SE.getWrapPredicate(AR, AddedFlags);
13835     return addOverflowAssumption(A);
13836   }
13837 
13838   // If \p Expr represents a PHINode, we try to see if it can be represented
13839   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
13840   // to add this predicate as a runtime overflow check, we return the AddRec.
13841   // If \p Expr does not meet these conditions (is not a PHI node, or we
13842   // couldn't create an AddRec for it, or couldn't add the predicate), we just
13843   // return \p Expr.
13844   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
13845     if (!isa<PHINode>(Expr->getValue()))
13846       return Expr;
13847     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
13848     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
13849     if (!PredicatedRewrite)
13850       return Expr;
13851     for (auto *P : PredicatedRewrite->second){
13852       // Wrap predicates from outer loops are not supported.
13853       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
13854         if (L != WP->getExpr()->getLoop())
13855           return Expr;
13856       }
13857       if (!addOverflowAssumption(P))
13858         return Expr;
13859     }
13860     return PredicatedRewrite->first;
13861   }
13862 
13863   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
13864   const SCEVPredicate *Pred;
13865   const Loop *L;
13866 };
13867 
13868 } // end anonymous namespace
13869 
13870 const SCEV *
13871 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
13872                                        const SCEVPredicate &Preds) {
13873   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
13874 }
13875 
13876 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
13877     const SCEV *S, const Loop *L,
13878     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
13879   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
13880   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
13881   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
13882 
13883   if (!AddRec)
13884     return nullptr;
13885 
13886   // Since the transformation was successful, we can now transfer the SCEV
13887   // predicates.
13888   for (auto *P : TransformPreds)
13889     Preds.insert(P);
13890 
13891   return AddRec;
13892 }
13893 
13894 /// SCEV predicates
13895 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
13896                              SCEVPredicateKind Kind)
13897     : FastID(ID), Kind(Kind) {}
13898 
13899 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
13900                                    const ICmpInst::Predicate Pred,
13901                                    const SCEV *LHS, const SCEV *RHS)
13902   : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
13903   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
13904   assert(LHS != RHS && "LHS and RHS are the same SCEV");
13905 }
13906 
13907 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
13908   const auto *Op = dyn_cast<SCEVComparePredicate>(N);
13909 
13910   if (!Op)
13911     return false;
13912 
13913   if (Pred != ICmpInst::ICMP_EQ)
13914     return false;
13915 
13916   return Op->LHS == LHS && Op->RHS == RHS;
13917 }
13918 
13919 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
13920 
13921 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
13922   if (Pred == ICmpInst::ICMP_EQ)
13923     OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
13924   else
13925     OS.indent(Depth) << "Compare predicate: " << *LHS
13926                      << " " << CmpInst::getPredicateName(Pred) << ") "
13927                      << *RHS << "\n";
13928 
13929 }
13930 
13931 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
13932                                      const SCEVAddRecExpr *AR,
13933                                      IncrementWrapFlags Flags)
13934     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
13935 
13936 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
13937 
13938 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
13939   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
13940 
13941   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
13942 }
13943 
13944 bool SCEVWrapPredicate::isAlwaysTrue() const {
13945   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
13946   IncrementWrapFlags IFlags = Flags;
13947 
13948   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
13949     IFlags = clearFlags(IFlags, IncrementNSSW);
13950 
13951   return IFlags == IncrementAnyWrap;
13952 }
13953 
13954 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
13955   OS.indent(Depth) << *getExpr() << " Added Flags: ";
13956   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
13957     OS << "<nusw>";
13958   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
13959     OS << "<nssw>";
13960   OS << "\n";
13961 }
13962 
13963 SCEVWrapPredicate::IncrementWrapFlags
13964 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
13965                                    ScalarEvolution &SE) {
13966   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
13967   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
13968 
13969   // We can safely transfer the NSW flag as NSSW.
13970   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
13971     ImpliedFlags = IncrementNSSW;
13972 
13973   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
13974     // If the increment is positive, the SCEV NUW flag will also imply the
13975     // WrapPredicate NUSW flag.
13976     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
13977       if (Step->getValue()->getValue().isNonNegative())
13978         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
13979   }
13980 
13981   return ImpliedFlags;
13982 }
13983 
13984 /// Union predicates don't get cached so create a dummy set ID for it.
13985 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
13986   : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
13987   for (auto *P : Preds)
13988     add(P);
13989 }
13990 
13991 bool SCEVUnionPredicate::isAlwaysTrue() const {
13992   return all_of(Preds,
13993                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
13994 }
13995 
13996 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
13997   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
13998     return all_of(Set->Preds,
13999                   [this](const SCEVPredicate *I) { return this->implies(I); });
14000 
14001   return any_of(Preds,
14002                 [N](const SCEVPredicate *I) { return I->implies(N); });
14003 }
14004 
14005 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14006   for (auto Pred : Preds)
14007     Pred->print(OS, Depth);
14008 }
14009 
14010 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14011   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14012     for (auto Pred : Set->Preds)
14013       add(Pred);
14014     return;
14015   }
14016 
14017   Preds.push_back(N);
14018 }
14019 
14020 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14021                                                      Loop &L)
14022     : SE(SE), L(L) {
14023   SmallVector<const SCEVPredicate*, 4> Empty;
14024   Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14025 }
14026 
14027 void ScalarEvolution::registerUser(const SCEV *User,
14028                                    ArrayRef<const SCEV *> Ops) {
14029   for (auto *Op : Ops)
14030     // We do not expect that forgetting cached data for SCEVConstants will ever
14031     // open any prospects for sharpening or introduce any correctness issues,
14032     // so we don't bother storing their dependencies.
14033     if (!isa<SCEVConstant>(Op))
14034       SCEVUsers[Op].insert(User);
14035 }
14036 
14037 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14038   const SCEV *Expr = SE.getSCEV(V);
14039   RewriteEntry &Entry = RewriteMap[Expr];
14040 
14041   // If we already have an entry and the version matches, return it.
14042   if (Entry.second && Generation == Entry.first)
14043     return Entry.second;
14044 
14045   // We found an entry but it's stale. Rewrite the stale entry
14046   // according to the current predicate.
14047   if (Entry.second)
14048     Expr = Entry.second;
14049 
14050   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14051   Entry = {Generation, NewSCEV};
14052 
14053   return NewSCEV;
14054 }
14055 
14056 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14057   if (!BackedgeCount) {
14058     SmallVector<const SCEVPredicate *, 4> Preds;
14059     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14060     for (auto *P : Preds)
14061       addPredicate(*P);
14062   }
14063   return BackedgeCount;
14064 }
14065 
14066 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14067   if (Preds->implies(&Pred))
14068     return;
14069 
14070   auto &OldPreds = Preds->getPredicates();
14071   SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14072   NewPreds.push_back(&Pred);
14073   Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14074   updateGeneration();
14075 }
14076 
14077 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14078   return *Preds;
14079 }
14080 
14081 void PredicatedScalarEvolution::updateGeneration() {
14082   // If the generation number wrapped recompute everything.
14083   if (++Generation == 0) {
14084     for (auto &II : RewriteMap) {
14085       const SCEV *Rewritten = II.second.second;
14086       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14087     }
14088   }
14089 }
14090 
14091 void PredicatedScalarEvolution::setNoOverflow(
14092     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14093   const SCEV *Expr = getSCEV(V);
14094   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14095 
14096   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14097 
14098   // Clear the statically implied flags.
14099   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14100   addPredicate(*SE.getWrapPredicate(AR, Flags));
14101 
14102   auto II = FlagsMap.insert({V, Flags});
14103   if (!II.second)
14104     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14105 }
14106 
14107 bool PredicatedScalarEvolution::hasNoOverflow(
14108     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14109   const SCEV *Expr = getSCEV(V);
14110   const auto *AR = cast<SCEVAddRecExpr>(Expr);
14111 
14112   Flags = SCEVWrapPredicate::clearFlags(
14113       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14114 
14115   auto II = FlagsMap.find(V);
14116 
14117   if (II != FlagsMap.end())
14118     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14119 
14120   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14121 }
14122 
14123 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14124   const SCEV *Expr = this->getSCEV(V);
14125   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14126   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14127 
14128   if (!New)
14129     return nullptr;
14130 
14131   for (auto *P : NewPreds)
14132     addPredicate(*P);
14133 
14134   RewriteMap[SE.getSCEV(V)] = {Generation, New};
14135   return New;
14136 }
14137 
14138 PredicatedScalarEvolution::PredicatedScalarEvolution(
14139     const PredicatedScalarEvolution &Init)
14140   : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14141     Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14142     Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14143   for (auto I : Init.FlagsMap)
14144     FlagsMap.insert(I);
14145 }
14146 
14147 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14148   // For each block.
14149   for (auto *BB : L.getBlocks())
14150     for (auto &I : *BB) {
14151       if (!SE.isSCEVable(I.getType()))
14152         continue;
14153 
14154       auto *Expr = SE.getSCEV(&I);
14155       auto II = RewriteMap.find(Expr);
14156 
14157       if (II == RewriteMap.end())
14158         continue;
14159 
14160       // Don't print things that are not interesting.
14161       if (II->second.second == Expr)
14162         continue;
14163 
14164       OS.indent(Depth) << "[PSE]" << I << ":\n";
14165       OS.indent(Depth + 2) << *Expr << "\n";
14166       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14167     }
14168 }
14169 
14170 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14171 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14172 // for URem with constant power-of-2 second operands.
14173 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14174 // 4, A / B becomes X / 8).
14175 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14176                                 const SCEV *&RHS) {
14177   // Try to match 'zext (trunc A to iB) to iY', which is used
14178   // for URem with constant power-of-2 second operands. Make sure the size of
14179   // the operand A matches the size of the whole expressions.
14180   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14181     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14182       LHS = Trunc->getOperand();
14183       // Bail out if the type of the LHS is larger than the type of the
14184       // expression for now.
14185       if (getTypeSizeInBits(LHS->getType()) >
14186           getTypeSizeInBits(Expr->getType()))
14187         return false;
14188       if (LHS->getType() != Expr->getType())
14189         LHS = getZeroExtendExpr(LHS, Expr->getType());
14190       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14191                         << getTypeSizeInBits(Trunc->getType()));
14192       return true;
14193     }
14194   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14195   if (Add == nullptr || Add->getNumOperands() != 2)
14196     return false;
14197 
14198   const SCEV *A = Add->getOperand(1);
14199   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14200 
14201   if (Mul == nullptr)
14202     return false;
14203 
14204   const auto MatchURemWithDivisor = [&](const SCEV *B) {
14205     // (SomeExpr + (-(SomeExpr / B) * B)).
14206     if (Expr == getURemExpr(A, B)) {
14207       LHS = A;
14208       RHS = B;
14209       return true;
14210     }
14211     return false;
14212   };
14213 
14214   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14215   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14216     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14217            MatchURemWithDivisor(Mul->getOperand(2));
14218 
14219   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14220   if (Mul->getNumOperands() == 2)
14221     return MatchURemWithDivisor(Mul->getOperand(1)) ||
14222            MatchURemWithDivisor(Mul->getOperand(0)) ||
14223            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14224            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14225   return false;
14226 }
14227 
14228 const SCEV *
14229 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14230   SmallVector<BasicBlock*, 16> ExitingBlocks;
14231   L->getExitingBlocks(ExitingBlocks);
14232 
14233   // Form an expression for the maximum exit count possible for this loop. We
14234   // merge the max and exact information to approximate a version of
14235   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14236   SmallVector<const SCEV*, 4> ExitCounts;
14237   for (BasicBlock *ExitingBB : ExitingBlocks) {
14238     const SCEV *ExitCount = getExitCount(L, ExitingBB);
14239     if (isa<SCEVCouldNotCompute>(ExitCount))
14240       ExitCount = getExitCount(L, ExitingBB,
14241                                   ScalarEvolution::ConstantMaximum);
14242     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14243       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14244              "We should only have known counts for exiting blocks that "
14245              "dominate latch!");
14246       ExitCounts.push_back(ExitCount);
14247     }
14248   }
14249   if (ExitCounts.empty())
14250     return getCouldNotCompute();
14251   return getUMinFromMismatchedTypes(ExitCounts);
14252 }
14253 
14254 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14255 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14256 /// replacement is loop invariant in the loop of the AddRec.
14257 ///
14258 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
14259 /// supported.
14260 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14261   const DenseMap<const SCEV *, const SCEV *> &Map;
14262 
14263 public:
14264   SCEVLoopGuardRewriter(ScalarEvolution &SE,
14265                         DenseMap<const SCEV *, const SCEV *> &M)
14266       : SCEVRewriteVisitor(SE), Map(M) {}
14267 
14268   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14269 
14270   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14271     auto I = Map.find(Expr);
14272     if (I == Map.end())
14273       return Expr;
14274     return I->second;
14275   }
14276 
14277   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14278     auto I = Map.find(Expr);
14279     if (I == Map.end())
14280       return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14281           Expr);
14282     return I->second;
14283   }
14284 };
14285 
14286 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14287   SmallVector<const SCEV *> ExprsToRewrite;
14288   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14289                               const SCEV *RHS,
14290                               DenseMap<const SCEV *, const SCEV *>
14291                                   &RewriteMap) {
14292     // WARNING: It is generally unsound to apply any wrap flags to the proposed
14293     // replacement SCEV which isn't directly implied by the structure of that
14294     // SCEV.  In particular, using contextual facts to imply flags is *NOT*
14295     // legal.  See the scoping rules for flags in the header to understand why.
14296 
14297     // If LHS is a constant, apply information to the other expression.
14298     if (isa<SCEVConstant>(LHS)) {
14299       std::swap(LHS, RHS);
14300       Predicate = CmpInst::getSwappedPredicate(Predicate);
14301     }
14302 
14303     // Check for a condition of the form (-C1 + X < C2).  InstCombine will
14304     // create this form when combining two checks of the form (X u< C2 + C1) and
14305     // (X >=u C1).
14306     auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14307                                  &ExprsToRewrite]() {
14308       auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14309       if (!AddExpr || AddExpr->getNumOperands() != 2)
14310         return false;
14311 
14312       auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14313       auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14314       auto *C2 = dyn_cast<SCEVConstant>(RHS);
14315       if (!C1 || !C2 || !LHSUnknown)
14316         return false;
14317 
14318       auto ExactRegion =
14319           ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14320               .sub(C1->getAPInt());
14321 
14322       // Bail out, unless we have a non-wrapping, monotonic range.
14323       if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14324         return false;
14325       auto I = RewriteMap.find(LHSUnknown);
14326       const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14327       RewriteMap[LHSUnknown] = getUMaxExpr(
14328           getConstant(ExactRegion.getUnsignedMin()),
14329           getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14330       ExprsToRewrite.push_back(LHSUnknown);
14331       return true;
14332     };
14333     if (MatchRangeCheckIdiom())
14334       return;
14335 
14336     // If we have LHS == 0, check if LHS is computing a property of some unknown
14337     // SCEV %v which we can rewrite %v to express explicitly.
14338     const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
14339     if (Predicate == CmpInst::ICMP_EQ && RHSC &&
14340         RHSC->getValue()->isNullValue()) {
14341       // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
14342       // explicitly express that.
14343       const SCEV *URemLHS = nullptr;
14344       const SCEV *URemRHS = nullptr;
14345       if (matchURem(LHS, URemLHS, URemRHS)) {
14346         if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
14347           auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
14348           RewriteMap[LHSUnknown] = Multiple;
14349           ExprsToRewrite.push_back(LHSUnknown);
14350           return;
14351         }
14352       }
14353     }
14354 
14355     // Do not apply information for constants or if RHS contains an AddRec.
14356     if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
14357       return;
14358 
14359     // If RHS is SCEVUnknown, make sure the information is applied to it.
14360     if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
14361       std::swap(LHS, RHS);
14362       Predicate = CmpInst::getSwappedPredicate(Predicate);
14363     }
14364 
14365     // Limit to expressions that can be rewritten.
14366     if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
14367       return;
14368 
14369     // Check whether LHS has already been rewritten. In that case we want to
14370     // chain further rewrites onto the already rewritten value.
14371     auto I = RewriteMap.find(LHS);
14372     const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
14373 
14374     const SCEV *RewrittenRHS = nullptr;
14375     switch (Predicate) {
14376     case CmpInst::ICMP_ULT:
14377       RewrittenRHS =
14378           getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14379       break;
14380     case CmpInst::ICMP_SLT:
14381       RewrittenRHS =
14382           getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
14383       break;
14384     case CmpInst::ICMP_ULE:
14385       RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
14386       break;
14387     case CmpInst::ICMP_SLE:
14388       RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
14389       break;
14390     case CmpInst::ICMP_UGT:
14391       RewrittenRHS =
14392           getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14393       break;
14394     case CmpInst::ICMP_SGT:
14395       RewrittenRHS =
14396           getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
14397       break;
14398     case CmpInst::ICMP_UGE:
14399       RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
14400       break;
14401     case CmpInst::ICMP_SGE:
14402       RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
14403       break;
14404     case CmpInst::ICMP_EQ:
14405       if (isa<SCEVConstant>(RHS))
14406         RewrittenRHS = RHS;
14407       break;
14408     case CmpInst::ICMP_NE:
14409       if (isa<SCEVConstant>(RHS) &&
14410           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
14411         RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
14412       break;
14413     default:
14414       break;
14415     }
14416 
14417     if (RewrittenRHS) {
14418       RewriteMap[LHS] = RewrittenRHS;
14419       if (LHS == RewrittenLHS)
14420         ExprsToRewrite.push_back(LHS);
14421     }
14422   };
14423   // First, collect conditions from dominating branches. Starting at the loop
14424   // predecessor, climb up the predecessor chain, as long as there are
14425   // predecessors that can be found that have unique successors leading to the
14426   // original header.
14427   // TODO: share this logic with isLoopEntryGuardedByCond.
14428   SmallVector<std::pair<Value *, bool>> Terms;
14429   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
14430            L->getLoopPredecessor(), L->getHeader());
14431        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
14432 
14433     const BranchInst *LoopEntryPredicate =
14434         dyn_cast<BranchInst>(Pair.first->getTerminator());
14435     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
14436       continue;
14437 
14438     Terms.emplace_back(LoopEntryPredicate->getCondition(),
14439                        LoopEntryPredicate->getSuccessor(0) == Pair.second);
14440   }
14441 
14442   // Now apply the information from the collected conditions to RewriteMap.
14443   // Conditions are processed in reverse order, so the earliest conditions is
14444   // processed first. This ensures the SCEVs with the shortest dependency chains
14445   // are constructed first.
14446   DenseMap<const SCEV *, const SCEV *> RewriteMap;
14447   for (auto &E : reverse(Terms)) {
14448     bool EnterIfTrue = E.second;
14449     SmallVector<Value *, 8> Worklist;
14450     SmallPtrSet<Value *, 8> Visited;
14451     Worklist.push_back(E.first);
14452     while (!Worklist.empty()) {
14453       Value *Cond = Worklist.pop_back_val();
14454       if (!Visited.insert(Cond).second)
14455         continue;
14456 
14457       if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14458         auto Predicate =
14459             EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
14460         CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
14461                          getSCEV(Cmp->getOperand(1)), RewriteMap);
14462         continue;
14463       }
14464 
14465       Value *L, *R;
14466       if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
14467                       : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
14468         Worklist.push_back(L);
14469         Worklist.push_back(R);
14470       }
14471     }
14472   }
14473 
14474   // Also collect information from assumptions dominating the loop.
14475   for (auto &AssumeVH : AC.assumptions()) {
14476     if (!AssumeVH)
14477       continue;
14478     auto *AssumeI = cast<CallInst>(AssumeVH);
14479     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
14480     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
14481       continue;
14482     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
14483                      getSCEV(Cmp->getOperand(1)), RewriteMap);
14484   }
14485 
14486   if (RewriteMap.empty())
14487     return Expr;
14488 
14489   // Now that all rewrite information is collect, rewrite the collected
14490   // expressions with the information in the map. This applies information to
14491   // sub-expressions.
14492   if (ExprsToRewrite.size() > 1) {
14493     for (const SCEV *Expr : ExprsToRewrite) {
14494       const SCEV *RewriteTo = RewriteMap[Expr];
14495       RewriteMap.erase(Expr);
14496       SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14497       RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
14498     }
14499   }
14500 
14501   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
14502   return Rewriter.visit(Expr);
14503 }
14504