xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision fcfe8cd3ae78f26643973affd6e8af182528a682)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/SmallPtrSet.h"
66 #include "llvm/ADT/Statistic.h"
67 #include "llvm/Analysis/AssumptionCache.h"
68 #include "llvm/Analysis/ConstantFolding.h"
69 #include "llvm/Analysis/InstructionSimplify.h"
70 #include "llvm/Analysis/LoopInfo.h"
71 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
72 #include "llvm/Analysis/TargetLibraryInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Dominators.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/GlobalAlias.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/InstIterator.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/LLVMContext.h"
85 #include "llvm/IR/Metadata.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Debug.h"
90 #include "llvm/Support/ErrorHandling.h"
91 #include "llvm/Support/MathExtras.h"
92 #include "llvm/Support/raw_ostream.h"
93 #include "llvm/Support/SaveAndRestore.h"
94 #include <algorithm>
95 using namespace llvm;
96 
97 #define DEBUG_TYPE "scalar-evolution"
98 
99 STATISTIC(NumArrayLenItCounts,
100           "Number of trip counts computed with array length");
101 STATISTIC(NumTripCountsComputed,
102           "Number of loops with predictable loop counts");
103 STATISTIC(NumTripCountsNotComputed,
104           "Number of loops without predictable loop counts");
105 STATISTIC(NumBruteForceTripCountsComputed,
106           "Number of loops with trip counts computed by force");
107 
108 static cl::opt<unsigned>
109 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
110                         cl::desc("Maximum number of iterations SCEV will "
111                                  "symbolically execute a constant "
112                                  "derived loop"),
113                         cl::init(100));
114 
115 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
116 static cl::opt<bool>
117 VerifySCEV("verify-scev",
118            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
119 static cl::opt<bool>
120     VerifySCEVMap("verify-scev-maps",
121                   cl::desc("Verify no dangling value in ScalarEvolution's "
122                            "ExprValueMap (slow)"));
123 
124 static cl::opt<unsigned> MulOpsInlineThreshold(
125     "scev-mulops-inline-threshold", cl::Hidden,
126     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
127     cl::init(1000));
128 
129 //===----------------------------------------------------------------------===//
130 //                           SCEV class definitions
131 //===----------------------------------------------------------------------===//
132 
133 //===----------------------------------------------------------------------===//
134 // Implementation of the SCEV class.
135 //
136 
137 LLVM_DUMP_METHOD
138 void SCEV::dump() const {
139   print(dbgs());
140   dbgs() << '\n';
141 }
142 
143 void SCEV::print(raw_ostream &OS) const {
144   switch (static_cast<SCEVTypes>(getSCEVType())) {
145   case scConstant:
146     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
147     return;
148   case scTruncate: {
149     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
150     const SCEV *Op = Trunc->getOperand();
151     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
152        << *Trunc->getType() << ")";
153     return;
154   }
155   case scZeroExtend: {
156     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
157     const SCEV *Op = ZExt->getOperand();
158     OS << "(zext " << *Op->getType() << " " << *Op << " to "
159        << *ZExt->getType() << ")";
160     return;
161   }
162   case scSignExtend: {
163     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
164     const SCEV *Op = SExt->getOperand();
165     OS << "(sext " << *Op->getType() << " " << *Op << " to "
166        << *SExt->getType() << ")";
167     return;
168   }
169   case scAddRecExpr: {
170     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
171     OS << "{" << *AR->getOperand(0);
172     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
173       OS << ",+," << *AR->getOperand(i);
174     OS << "}<";
175     if (AR->hasNoUnsignedWrap())
176       OS << "nuw><";
177     if (AR->hasNoSignedWrap())
178       OS << "nsw><";
179     if (AR->hasNoSelfWrap() &&
180         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
181       OS << "nw><";
182     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
183     OS << ">";
184     return;
185   }
186   case scAddExpr:
187   case scMulExpr:
188   case scUMaxExpr:
189   case scSMaxExpr: {
190     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
191     const char *OpStr = nullptr;
192     switch (NAry->getSCEVType()) {
193     case scAddExpr: OpStr = " + "; break;
194     case scMulExpr: OpStr = " * "; break;
195     case scUMaxExpr: OpStr = " umax "; break;
196     case scSMaxExpr: OpStr = " smax "; break;
197     }
198     OS << "(";
199     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
200          I != E; ++I) {
201       OS << **I;
202       if (std::next(I) != E)
203         OS << OpStr;
204     }
205     OS << ")";
206     switch (NAry->getSCEVType()) {
207     case scAddExpr:
208     case scMulExpr:
209       if (NAry->hasNoUnsignedWrap())
210         OS << "<nuw>";
211       if (NAry->hasNoSignedWrap())
212         OS << "<nsw>";
213     }
214     return;
215   }
216   case scUDivExpr: {
217     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
218     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
219     return;
220   }
221   case scUnknown: {
222     const SCEVUnknown *U = cast<SCEVUnknown>(this);
223     Type *AllocTy;
224     if (U->isSizeOf(AllocTy)) {
225       OS << "sizeof(" << *AllocTy << ")";
226       return;
227     }
228     if (U->isAlignOf(AllocTy)) {
229       OS << "alignof(" << *AllocTy << ")";
230       return;
231     }
232 
233     Type *CTy;
234     Constant *FieldNo;
235     if (U->isOffsetOf(CTy, FieldNo)) {
236       OS << "offsetof(" << *CTy << ", ";
237       FieldNo->printAsOperand(OS, false);
238       OS << ")";
239       return;
240     }
241 
242     // Otherwise just print it normally.
243     U->getValue()->printAsOperand(OS, false);
244     return;
245   }
246   case scCouldNotCompute:
247     OS << "***COULDNOTCOMPUTE***";
248     return;
249   }
250   llvm_unreachable("Unknown SCEV kind!");
251 }
252 
253 Type *SCEV::getType() const {
254   switch (static_cast<SCEVTypes>(getSCEVType())) {
255   case scConstant:
256     return cast<SCEVConstant>(this)->getType();
257   case scTruncate:
258   case scZeroExtend:
259   case scSignExtend:
260     return cast<SCEVCastExpr>(this)->getType();
261   case scAddRecExpr:
262   case scMulExpr:
263   case scUMaxExpr:
264   case scSMaxExpr:
265     return cast<SCEVNAryExpr>(this)->getType();
266   case scAddExpr:
267     return cast<SCEVAddExpr>(this)->getType();
268   case scUDivExpr:
269     return cast<SCEVUDivExpr>(this)->getType();
270   case scUnknown:
271     return cast<SCEVUnknown>(this)->getType();
272   case scCouldNotCompute:
273     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
274   }
275   llvm_unreachable("Unknown SCEV kind!");
276 }
277 
278 bool SCEV::isZero() const {
279   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
280     return SC->getValue()->isZero();
281   return false;
282 }
283 
284 bool SCEV::isOne() const {
285   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286     return SC->getValue()->isOne();
287   return false;
288 }
289 
290 bool SCEV::isAllOnesValue() const {
291   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
292     return SC->getValue()->isAllOnesValue();
293   return false;
294 }
295 
296 bool SCEV::isNonConstantNegative() const {
297   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
298   if (!Mul) return false;
299 
300   // If there is a constant factor, it will be first.
301   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
302   if (!SC) return false;
303 
304   // Return true if the value is negative, this matches things like (-42 * V).
305   return SC->getAPInt().isNegative();
306 }
307 
308 SCEVCouldNotCompute::SCEVCouldNotCompute() :
309   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
310 
311 bool SCEVCouldNotCompute::classof(const SCEV *S) {
312   return S->getSCEVType() == scCouldNotCompute;
313 }
314 
315 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
316   FoldingSetNodeID ID;
317   ID.AddInteger(scConstant);
318   ID.AddPointer(V);
319   void *IP = nullptr;
320   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
321   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
322   UniqueSCEVs.InsertNode(S, IP);
323   return S;
324 }
325 
326 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
327   return getConstant(ConstantInt::get(getContext(), Val));
328 }
329 
330 const SCEV *
331 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
332   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
333   return getConstant(ConstantInt::get(ITy, V, isSigned));
334 }
335 
336 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
337                            unsigned SCEVTy, const SCEV *op, Type *ty)
338   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
339 
340 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
341                                    const SCEV *op, Type *ty)
342   : SCEVCastExpr(ID, scTruncate, op, ty) {
343   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
344          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
345          "Cannot truncate non-integer value!");
346 }
347 
348 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
349                                        const SCEV *op, Type *ty)
350   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
351   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
352          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
353          "Cannot zero extend non-integer value!");
354 }
355 
356 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
357                                        const SCEV *op, Type *ty)
358   : SCEVCastExpr(ID, scSignExtend, op, ty) {
359   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
360          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
361          "Cannot sign extend non-integer value!");
362 }
363 
364 void SCEVUnknown::deleted() {
365   // Clear this SCEVUnknown from various maps.
366   SE->forgetMemoizedResults(this);
367 
368   // Remove this SCEVUnknown from the uniquing map.
369   SE->UniqueSCEVs.RemoveNode(this);
370 
371   // Release the value.
372   setValPtr(nullptr);
373 }
374 
375 void SCEVUnknown::allUsesReplacedWith(Value *New) {
376   // Clear this SCEVUnknown from various maps.
377   SE->forgetMemoizedResults(this);
378 
379   // Remove this SCEVUnknown from the uniquing map.
380   SE->UniqueSCEVs.RemoveNode(this);
381 
382   // Update this SCEVUnknown to point to the new value. This is needed
383   // because there may still be outstanding SCEVs which still point to
384   // this SCEVUnknown.
385   setValPtr(New);
386 }
387 
388 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
389   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
390     if (VCE->getOpcode() == Instruction::PtrToInt)
391       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
392         if (CE->getOpcode() == Instruction::GetElementPtr &&
393             CE->getOperand(0)->isNullValue() &&
394             CE->getNumOperands() == 2)
395           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
396             if (CI->isOne()) {
397               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
398                                  ->getElementType();
399               return true;
400             }
401 
402   return false;
403 }
404 
405 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
406   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
407     if (VCE->getOpcode() == Instruction::PtrToInt)
408       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
409         if (CE->getOpcode() == Instruction::GetElementPtr &&
410             CE->getOperand(0)->isNullValue()) {
411           Type *Ty =
412             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
413           if (StructType *STy = dyn_cast<StructType>(Ty))
414             if (!STy->isPacked() &&
415                 CE->getNumOperands() == 3 &&
416                 CE->getOperand(1)->isNullValue()) {
417               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
418                 if (CI->isOne() &&
419                     STy->getNumElements() == 2 &&
420                     STy->getElementType(0)->isIntegerTy(1)) {
421                   AllocTy = STy->getElementType(1);
422                   return true;
423                 }
424             }
425         }
426 
427   return false;
428 }
429 
430 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
431   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
432     if (VCE->getOpcode() == Instruction::PtrToInt)
433       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
434         if (CE->getOpcode() == Instruction::GetElementPtr &&
435             CE->getNumOperands() == 3 &&
436             CE->getOperand(0)->isNullValue() &&
437             CE->getOperand(1)->isNullValue()) {
438           Type *Ty =
439             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
440           // Ignore vector types here so that ScalarEvolutionExpander doesn't
441           // emit getelementptrs that index into vectors.
442           if (Ty->isStructTy() || Ty->isArrayTy()) {
443             CTy = Ty;
444             FieldNo = CE->getOperand(2);
445             return true;
446           }
447         }
448 
449   return false;
450 }
451 
452 //===----------------------------------------------------------------------===//
453 //                               SCEV Utilities
454 //===----------------------------------------------------------------------===//
455 
456 static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
457                                   Value *RV, unsigned DepthLeft = 2) {
458   if (DepthLeft == 0)
459     return 0;
460 
461   // Order pointer values after integer values. This helps SCEVExpander form
462   // GEPs.
463   bool LIsPointer = LV->getType()->isPointerTy(),
464        RIsPointer = RV->getType()->isPointerTy();
465   if (LIsPointer != RIsPointer)
466     return (int)LIsPointer - (int)RIsPointer;
467 
468   // Compare getValueID values.
469   unsigned LID = LV->getValueID(), RID = RV->getValueID();
470   if (LID != RID)
471     return (int)LID - (int)RID;
472 
473   // Sort arguments by their position.
474   if (const Argument *LA = dyn_cast<Argument>(LV)) {
475     const Argument *RA = cast<Argument>(RV);
476     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
477     return (int)LArgNo - (int)RArgNo;
478   }
479 
480   // For instructions, compare their loop depth, and their operand count.  This
481   // is pretty loose.
482   if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
483     const Instruction *RInst = cast<Instruction>(RV);
484 
485     // Compare loop depths.
486     const BasicBlock *LParent = LInst->getParent(),
487                      *RParent = RInst->getParent();
488     if (LParent != RParent) {
489       unsigned LDepth = LI->getLoopDepth(LParent),
490                RDepth = LI->getLoopDepth(RParent);
491       if (LDepth != RDepth)
492         return (int)LDepth - (int)RDepth;
493     }
494 
495     // Compare the number of operands.
496     unsigned LNumOps = LInst->getNumOperands(),
497              RNumOps = RInst->getNumOperands();
498     if (LNumOps != RNumOps || LNumOps != 1)
499       return (int)LNumOps - (int)RNumOps;
500 
501     // We only bother "recursing" if we have one operand to look at (so we don't
502     // really recurse as much as we iterate).  We can consider expanding this
503     // logic in the future.
504     return CompareValueComplexity(LI, LInst->getOperand(0),
505                                   RInst->getOperand(0), DepthLeft - 1);
506   }
507 
508   return 0;
509 }
510 
511 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
512 // than RHS, respectively. A three-way result allows recursive comparisons to be
513 // more efficient.
514 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
515                                  const SCEV *RHS) {
516   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
517   if (LHS == RHS)
518     return 0;
519 
520   // Primarily, sort the SCEVs by their getSCEVType().
521   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
522   if (LType != RType)
523     return (int)LType - (int)RType;
524 
525   // Aside from the getSCEVType() ordering, the particular ordering
526   // isn't very important except that it's beneficial to be consistent,
527   // so that (a + b) and (b + a) don't end up as different expressions.
528   switch (static_cast<SCEVTypes>(LType)) {
529   case scUnknown: {
530     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
531     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
532 
533     return CompareValueComplexity(LI, LU->getValue(), RU->getValue());
534   }
535 
536   case scConstant: {
537     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
538     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
539 
540     // Compare constant values.
541     const APInt &LA = LC->getAPInt();
542     const APInt &RA = RC->getAPInt();
543     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
544     if (LBitWidth != RBitWidth)
545       return (int)LBitWidth - (int)RBitWidth;
546     return LA.ult(RA) ? -1 : 1;
547   }
548 
549   case scAddRecExpr: {
550     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
551     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
552 
553     // Compare addrec loop depths.
554     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
555     if (LLoop != RLoop) {
556       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
557       if (LDepth != RDepth)
558         return (int)LDepth - (int)RDepth;
559     }
560 
561     // Addrec complexity grows with operand count.
562     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
563     if (LNumOps != RNumOps)
564       return (int)LNumOps - (int)RNumOps;
565 
566     // Lexicographically compare.
567     for (unsigned i = 0; i != LNumOps; ++i) {
568       long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i));
569       if (X != 0)
570         return X;
571     }
572 
573     return 0;
574   }
575 
576   case scAddExpr:
577   case scMulExpr:
578   case scSMaxExpr:
579   case scUMaxExpr: {
580     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
581     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
582 
583     // Lexicographically compare n-ary expressions.
584     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
585     if (LNumOps != RNumOps)
586       return (int)LNumOps - (int)RNumOps;
587 
588     for (unsigned i = 0; i != LNumOps; ++i) {
589       if (i >= RNumOps)
590         return 1;
591       long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i));
592       if (X != 0)
593         return X;
594     }
595     return (int)LNumOps - (int)RNumOps;
596   }
597 
598   case scUDivExpr: {
599     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
600     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
601 
602     // Lexicographically compare udiv expressions.
603     long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS());
604     if (X != 0)
605       return X;
606     return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS());
607   }
608 
609   case scTruncate:
610   case scZeroExtend:
611   case scSignExtend: {
612     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
613     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
614 
615     // Compare cast expressions by operand.
616     return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand());
617   }
618 
619   case scCouldNotCompute:
620     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
621   }
622   llvm_unreachable("Unknown SCEV kind!");
623 }
624 
625 /// Given a list of SCEV objects, order them by their complexity, and group
626 /// objects of the same complexity together by value.  When this routine is
627 /// finished, we know that any duplicates in the vector are consecutive and that
628 /// complexity is monotonically increasing.
629 ///
630 /// Note that we go take special precautions to ensure that we get deterministic
631 /// results from this routine.  In other words, we don't want the results of
632 /// this to depend on where the addresses of various SCEV objects happened to
633 /// land in memory.
634 ///
635 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
636                               LoopInfo *LI) {
637   if (Ops.size() < 2) return;  // Noop
638   if (Ops.size() == 2) {
639     // This is the common case, which also happens to be trivially simple.
640     // Special case it.
641     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
642     if (CompareSCEVComplexity(LI, RHS, LHS) < 0)
643       std::swap(LHS, RHS);
644     return;
645   }
646 
647   // Do the rough sort by complexity.
648   std::stable_sort(Ops.begin(), Ops.end(),
649                    [LI](const SCEV *LHS, const SCEV *RHS) {
650                      return CompareSCEVComplexity(LI, LHS, RHS) < 0;
651                    });
652 
653   // Now that we are sorted by complexity, group elements of the same
654   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
655   // be extremely short in practice.  Note that we take this approach because we
656   // do not want to depend on the addresses of the objects we are grouping.
657   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
658     const SCEV *S = Ops[i];
659     unsigned Complexity = S->getSCEVType();
660 
661     // If there are any objects of the same complexity and same value as this
662     // one, group them.
663     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
664       if (Ops[j] == S) { // Found a duplicate.
665         // Move it to immediately after i'th element.
666         std::swap(Ops[i+1], Ops[j]);
667         ++i;   // no need to rescan it.
668         if (i == e-2) return;  // Done!
669       }
670     }
671   }
672 }
673 
674 // Returns the size of the SCEV S.
675 static inline int sizeOfSCEV(const SCEV *S) {
676   struct FindSCEVSize {
677     int Size;
678     FindSCEVSize() : Size(0) {}
679 
680     bool follow(const SCEV *S) {
681       ++Size;
682       // Keep looking at all operands of S.
683       return true;
684     }
685     bool isDone() const {
686       return false;
687     }
688   };
689 
690   FindSCEVSize F;
691   SCEVTraversal<FindSCEVSize> ST(F);
692   ST.visitAll(S);
693   return F.Size;
694 }
695 
696 namespace {
697 
698 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
699 public:
700   // Computes the Quotient and Remainder of the division of Numerator by
701   // Denominator.
702   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
703                      const SCEV *Denominator, const SCEV **Quotient,
704                      const SCEV **Remainder) {
705     assert(Numerator && Denominator && "Uninitialized SCEV");
706 
707     SCEVDivision D(SE, Numerator, Denominator);
708 
709     // Check for the trivial case here to avoid having to check for it in the
710     // rest of the code.
711     if (Numerator == Denominator) {
712       *Quotient = D.One;
713       *Remainder = D.Zero;
714       return;
715     }
716 
717     if (Numerator->isZero()) {
718       *Quotient = D.Zero;
719       *Remainder = D.Zero;
720       return;
721     }
722 
723     // A simple case when N/1. The quotient is N.
724     if (Denominator->isOne()) {
725       *Quotient = Numerator;
726       *Remainder = D.Zero;
727       return;
728     }
729 
730     // Split the Denominator when it is a product.
731     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
732       const SCEV *Q, *R;
733       *Quotient = Numerator;
734       for (const SCEV *Op : T->operands()) {
735         divide(SE, *Quotient, Op, &Q, &R);
736         *Quotient = Q;
737 
738         // Bail out when the Numerator is not divisible by one of the terms of
739         // the Denominator.
740         if (!R->isZero()) {
741           *Quotient = D.Zero;
742           *Remainder = Numerator;
743           return;
744         }
745       }
746       *Remainder = D.Zero;
747       return;
748     }
749 
750     D.visit(Numerator);
751     *Quotient = D.Quotient;
752     *Remainder = D.Remainder;
753   }
754 
755   // Except in the trivial case described above, we do not know how to divide
756   // Expr by Denominator for the following functions with empty implementation.
757   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
758   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
759   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
760   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
761   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
762   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
763   void visitUnknown(const SCEVUnknown *Numerator) {}
764   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
765 
766   void visitConstant(const SCEVConstant *Numerator) {
767     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
768       APInt NumeratorVal = Numerator->getAPInt();
769       APInt DenominatorVal = D->getAPInt();
770       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
771       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
772 
773       if (NumeratorBW > DenominatorBW)
774         DenominatorVal = DenominatorVal.sext(NumeratorBW);
775       else if (NumeratorBW < DenominatorBW)
776         NumeratorVal = NumeratorVal.sext(DenominatorBW);
777 
778       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
779       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
780       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
781       Quotient = SE.getConstant(QuotientVal);
782       Remainder = SE.getConstant(RemainderVal);
783       return;
784     }
785   }
786 
787   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
788     const SCEV *StartQ, *StartR, *StepQ, *StepR;
789     if (!Numerator->isAffine())
790       return cannotDivide(Numerator);
791     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
792     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
793     // Bail out if the types do not match.
794     Type *Ty = Denominator->getType();
795     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
796         Ty != StepQ->getType() || Ty != StepR->getType())
797       return cannotDivide(Numerator);
798     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
799                                 Numerator->getNoWrapFlags());
800     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
801                                  Numerator->getNoWrapFlags());
802   }
803 
804   void visitAddExpr(const SCEVAddExpr *Numerator) {
805     SmallVector<const SCEV *, 2> Qs, Rs;
806     Type *Ty = Denominator->getType();
807 
808     for (const SCEV *Op : Numerator->operands()) {
809       const SCEV *Q, *R;
810       divide(SE, Op, Denominator, &Q, &R);
811 
812       // Bail out if types do not match.
813       if (Ty != Q->getType() || Ty != R->getType())
814         return cannotDivide(Numerator);
815 
816       Qs.push_back(Q);
817       Rs.push_back(R);
818     }
819 
820     if (Qs.size() == 1) {
821       Quotient = Qs[0];
822       Remainder = Rs[0];
823       return;
824     }
825 
826     Quotient = SE.getAddExpr(Qs);
827     Remainder = SE.getAddExpr(Rs);
828   }
829 
830   void visitMulExpr(const SCEVMulExpr *Numerator) {
831     SmallVector<const SCEV *, 2> Qs;
832     Type *Ty = Denominator->getType();
833 
834     bool FoundDenominatorTerm = false;
835     for (const SCEV *Op : Numerator->operands()) {
836       // Bail out if types do not match.
837       if (Ty != Op->getType())
838         return cannotDivide(Numerator);
839 
840       if (FoundDenominatorTerm) {
841         Qs.push_back(Op);
842         continue;
843       }
844 
845       // Check whether Denominator divides one of the product operands.
846       const SCEV *Q, *R;
847       divide(SE, Op, Denominator, &Q, &R);
848       if (!R->isZero()) {
849         Qs.push_back(Op);
850         continue;
851       }
852 
853       // Bail out if types do not match.
854       if (Ty != Q->getType())
855         return cannotDivide(Numerator);
856 
857       FoundDenominatorTerm = true;
858       Qs.push_back(Q);
859     }
860 
861     if (FoundDenominatorTerm) {
862       Remainder = Zero;
863       if (Qs.size() == 1)
864         Quotient = Qs[0];
865       else
866         Quotient = SE.getMulExpr(Qs);
867       return;
868     }
869 
870     if (!isa<SCEVUnknown>(Denominator))
871       return cannotDivide(Numerator);
872 
873     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
874     ValueToValueMap RewriteMap;
875     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
876         cast<SCEVConstant>(Zero)->getValue();
877     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
878 
879     if (Remainder->isZero()) {
880       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
881       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
882           cast<SCEVConstant>(One)->getValue();
883       Quotient =
884           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
885       return;
886     }
887 
888     // Quotient is (Numerator - Remainder) divided by Denominator.
889     const SCEV *Q, *R;
890     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
891     // This SCEV does not seem to simplify: fail the division here.
892     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
893       return cannotDivide(Numerator);
894     divide(SE, Diff, Denominator, &Q, &R);
895     if (R != Zero)
896       return cannotDivide(Numerator);
897     Quotient = Q;
898   }
899 
900 private:
901   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
902                const SCEV *Denominator)
903       : SE(S), Denominator(Denominator) {
904     Zero = SE.getZero(Denominator->getType());
905     One = SE.getOne(Denominator->getType());
906 
907     // We generally do not know how to divide Expr by Denominator. We
908     // initialize the division to a "cannot divide" state to simplify the rest
909     // of the code.
910     cannotDivide(Numerator);
911   }
912 
913   // Convenience function for giving up on the division. We set the quotient to
914   // be equal to zero and the remainder to be equal to the numerator.
915   void cannotDivide(const SCEV *Numerator) {
916     Quotient = Zero;
917     Remainder = Numerator;
918   }
919 
920   ScalarEvolution &SE;
921   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
922 };
923 
924 }
925 
926 //===----------------------------------------------------------------------===//
927 //                      Simple SCEV method implementations
928 //===----------------------------------------------------------------------===//
929 
930 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
931 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
932                                        ScalarEvolution &SE,
933                                        Type *ResultTy) {
934   // Handle the simplest case efficiently.
935   if (K == 1)
936     return SE.getTruncateOrZeroExtend(It, ResultTy);
937 
938   // We are using the following formula for BC(It, K):
939   //
940   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
941   //
942   // Suppose, W is the bitwidth of the return value.  We must be prepared for
943   // overflow.  Hence, we must assure that the result of our computation is
944   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
945   // safe in modular arithmetic.
946   //
947   // However, this code doesn't use exactly that formula; the formula it uses
948   // is something like the following, where T is the number of factors of 2 in
949   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
950   // exponentiation:
951   //
952   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
953   //
954   // This formula is trivially equivalent to the previous formula.  However,
955   // this formula can be implemented much more efficiently.  The trick is that
956   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
957   // arithmetic.  To do exact division in modular arithmetic, all we have
958   // to do is multiply by the inverse.  Therefore, this step can be done at
959   // width W.
960   //
961   // The next issue is how to safely do the division by 2^T.  The way this
962   // is done is by doing the multiplication step at a width of at least W + T
963   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
964   // when we perform the division by 2^T (which is equivalent to a right shift
965   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
966   // truncated out after the division by 2^T.
967   //
968   // In comparison to just directly using the first formula, this technique
969   // is much more efficient; using the first formula requires W * K bits,
970   // but this formula less than W + K bits. Also, the first formula requires
971   // a division step, whereas this formula only requires multiplies and shifts.
972   //
973   // It doesn't matter whether the subtraction step is done in the calculation
974   // width or the input iteration count's width; if the subtraction overflows,
975   // the result must be zero anyway.  We prefer here to do it in the width of
976   // the induction variable because it helps a lot for certain cases; CodeGen
977   // isn't smart enough to ignore the overflow, which leads to much less
978   // efficient code if the width of the subtraction is wider than the native
979   // register width.
980   //
981   // (It's possible to not widen at all by pulling out factors of 2 before
982   // the multiplication; for example, K=2 can be calculated as
983   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
984   // extra arithmetic, so it's not an obvious win, and it gets
985   // much more complicated for K > 3.)
986 
987   // Protection from insane SCEVs; this bound is conservative,
988   // but it probably doesn't matter.
989   if (K > 1000)
990     return SE.getCouldNotCompute();
991 
992   unsigned W = SE.getTypeSizeInBits(ResultTy);
993 
994   // Calculate K! / 2^T and T; we divide out the factors of two before
995   // multiplying for calculating K! / 2^T to avoid overflow.
996   // Other overflow doesn't matter because we only care about the bottom
997   // W bits of the result.
998   APInt OddFactorial(W, 1);
999   unsigned T = 1;
1000   for (unsigned i = 3; i <= K; ++i) {
1001     APInt Mult(W, i);
1002     unsigned TwoFactors = Mult.countTrailingZeros();
1003     T += TwoFactors;
1004     Mult = Mult.lshr(TwoFactors);
1005     OddFactorial *= Mult;
1006   }
1007 
1008   // We need at least W + T bits for the multiplication step
1009   unsigned CalculationBits = W + T;
1010 
1011   // Calculate 2^T, at width T+W.
1012   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1013 
1014   // Calculate the multiplicative inverse of K! / 2^T;
1015   // this multiplication factor will perform the exact division by
1016   // K! / 2^T.
1017   APInt Mod = APInt::getSignedMinValue(W+1);
1018   APInt MultiplyFactor = OddFactorial.zext(W+1);
1019   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1020   MultiplyFactor = MultiplyFactor.trunc(W);
1021 
1022   // Calculate the product, at width T+W
1023   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1024                                                       CalculationBits);
1025   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1026   for (unsigned i = 1; i != K; ++i) {
1027     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1028     Dividend = SE.getMulExpr(Dividend,
1029                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1030   }
1031 
1032   // Divide by 2^T
1033   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1034 
1035   // Truncate the result, and divide by K! / 2^T.
1036 
1037   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1038                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1039 }
1040 
1041 /// Return the value of this chain of recurrences at the specified iteration
1042 /// number.  We can evaluate this recurrence by multiplying each element in the
1043 /// chain by the binomial coefficient corresponding to it.  In other words, we
1044 /// can evaluate {A,+,B,+,C,+,D} as:
1045 ///
1046 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1047 ///
1048 /// where BC(It, k) stands for binomial coefficient.
1049 ///
1050 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1051                                                 ScalarEvolution &SE) const {
1052   const SCEV *Result = getStart();
1053   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1054     // The computation is correct in the face of overflow provided that the
1055     // multiplication is performed _after_ the evaluation of the binomial
1056     // coefficient.
1057     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1058     if (isa<SCEVCouldNotCompute>(Coeff))
1059       return Coeff;
1060 
1061     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1062   }
1063   return Result;
1064 }
1065 
1066 //===----------------------------------------------------------------------===//
1067 //                    SCEV Expression folder implementations
1068 //===----------------------------------------------------------------------===//
1069 
1070 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1071                                              Type *Ty) {
1072   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1073          "This is not a truncating conversion!");
1074   assert(isSCEVable(Ty) &&
1075          "This is not a conversion to a SCEVable type!");
1076   Ty = getEffectiveSCEVType(Ty);
1077 
1078   FoldingSetNodeID ID;
1079   ID.AddInteger(scTruncate);
1080   ID.AddPointer(Op);
1081   ID.AddPointer(Ty);
1082   void *IP = nullptr;
1083   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1084 
1085   // Fold if the operand is constant.
1086   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1087     return getConstant(
1088       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1089 
1090   // trunc(trunc(x)) --> trunc(x)
1091   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1092     return getTruncateExpr(ST->getOperand(), Ty);
1093 
1094   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1095   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1096     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1097 
1098   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1099   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1100     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1101 
1102   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1103   // eliminate all the truncates, or we replace other casts with truncates.
1104   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1105     SmallVector<const SCEV *, 4> Operands;
1106     bool hasTrunc = false;
1107     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1108       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1109       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1110         hasTrunc = isa<SCEVTruncateExpr>(S);
1111       Operands.push_back(S);
1112     }
1113     if (!hasTrunc)
1114       return getAddExpr(Operands);
1115     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1116   }
1117 
1118   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1119   // eliminate all the truncates, or we replace other casts with truncates.
1120   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1121     SmallVector<const SCEV *, 4> Operands;
1122     bool hasTrunc = false;
1123     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1124       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1125       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1126         hasTrunc = isa<SCEVTruncateExpr>(S);
1127       Operands.push_back(S);
1128     }
1129     if (!hasTrunc)
1130       return getMulExpr(Operands);
1131     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1132   }
1133 
1134   // If the input value is a chrec scev, truncate the chrec's operands.
1135   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1136     SmallVector<const SCEV *, 4> Operands;
1137     for (const SCEV *Op : AddRec->operands())
1138       Operands.push_back(getTruncateExpr(Op, Ty));
1139     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1140   }
1141 
1142   // The cast wasn't folded; create an explicit cast node. We can reuse
1143   // the existing insert position since if we get here, we won't have
1144   // made any changes which would invalidate it.
1145   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1146                                                  Op, Ty);
1147   UniqueSCEVs.InsertNode(S, IP);
1148   return S;
1149 }
1150 
1151 // Get the limit of a recurrence such that incrementing by Step cannot cause
1152 // signed overflow as long as the value of the recurrence within the
1153 // loop does not exceed this limit before incrementing.
1154 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1155                                                  ICmpInst::Predicate *Pred,
1156                                                  ScalarEvolution *SE) {
1157   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1158   if (SE->isKnownPositive(Step)) {
1159     *Pred = ICmpInst::ICMP_SLT;
1160     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1161                            SE->getSignedRange(Step).getSignedMax());
1162   }
1163   if (SE->isKnownNegative(Step)) {
1164     *Pred = ICmpInst::ICMP_SGT;
1165     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1166                            SE->getSignedRange(Step).getSignedMin());
1167   }
1168   return nullptr;
1169 }
1170 
1171 // Get the limit of a recurrence such that incrementing by Step cannot cause
1172 // unsigned overflow as long as the value of the recurrence within the loop does
1173 // not exceed this limit before incrementing.
1174 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1175                                                    ICmpInst::Predicate *Pred,
1176                                                    ScalarEvolution *SE) {
1177   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1178   *Pred = ICmpInst::ICMP_ULT;
1179 
1180   return SE->getConstant(APInt::getMinValue(BitWidth) -
1181                          SE->getUnsignedRange(Step).getUnsignedMax());
1182 }
1183 
1184 namespace {
1185 
1186 struct ExtendOpTraitsBase {
1187   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1188 };
1189 
1190 // Used to make code generic over signed and unsigned overflow.
1191 template <typename ExtendOp> struct ExtendOpTraits {
1192   // Members present:
1193   //
1194   // static const SCEV::NoWrapFlags WrapType;
1195   //
1196   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1197   //
1198   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1199   //                                           ICmpInst::Predicate *Pred,
1200   //                                           ScalarEvolution *SE);
1201 };
1202 
1203 template <>
1204 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1205   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1206 
1207   static const GetExtendExprTy GetExtendExpr;
1208 
1209   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210                                              ICmpInst::Predicate *Pred,
1211                                              ScalarEvolution *SE) {
1212     return getSignedOverflowLimitForStep(Step, Pred, SE);
1213   }
1214 };
1215 
1216 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1217     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1218 
1219 template <>
1220 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1221   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1222 
1223   static const GetExtendExprTy GetExtendExpr;
1224 
1225   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1226                                              ICmpInst::Predicate *Pred,
1227                                              ScalarEvolution *SE) {
1228     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1229   }
1230 };
1231 
1232 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1233     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1234 }
1235 
1236 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1237 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1238 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1239 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1240 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1241 // expression "Step + sext/zext(PreIncAR)" is congruent with
1242 // "sext/zext(PostIncAR)"
1243 template <typename ExtendOpTy>
1244 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1245                                         ScalarEvolution *SE) {
1246   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1247   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1248 
1249   const Loop *L = AR->getLoop();
1250   const SCEV *Start = AR->getStart();
1251   const SCEV *Step = AR->getStepRecurrence(*SE);
1252 
1253   // Check for a simple looking step prior to loop entry.
1254   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1255   if (!SA)
1256     return nullptr;
1257 
1258   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1259   // subtraction is expensive. For this purpose, perform a quick and dirty
1260   // difference, by checking for Step in the operand list.
1261   SmallVector<const SCEV *, 4> DiffOps;
1262   for (const SCEV *Op : SA->operands())
1263     if (Op != Step)
1264       DiffOps.push_back(Op);
1265 
1266   if (DiffOps.size() == SA->getNumOperands())
1267     return nullptr;
1268 
1269   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1270   // `Step`:
1271 
1272   // 1. NSW/NUW flags on the step increment.
1273   auto PreStartFlags =
1274     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1275   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1276   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1277       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1278 
1279   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1280   // "S+X does not sign/unsign-overflow".
1281   //
1282 
1283   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1284   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1285       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1286     return PreStart;
1287 
1288   // 2. Direct overflow check on the step operation's expression.
1289   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1290   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1291   const SCEV *OperandExtendedStart =
1292       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1293                      (SE->*GetExtendExpr)(Step, WideTy));
1294   if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1295     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1296       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1297       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1298       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1299       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1300     }
1301     return PreStart;
1302   }
1303 
1304   // 3. Loop precondition.
1305   ICmpInst::Predicate Pred;
1306   const SCEV *OverflowLimit =
1307       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1308 
1309   if (OverflowLimit &&
1310       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1311     return PreStart;
1312 
1313   return nullptr;
1314 }
1315 
1316 // Get the normalized zero or sign extended expression for this AddRec's Start.
1317 template <typename ExtendOpTy>
1318 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1319                                         ScalarEvolution *SE) {
1320   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1321 
1322   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1323   if (!PreStart)
1324     return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1325 
1326   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1327                         (SE->*GetExtendExpr)(PreStart, Ty));
1328 }
1329 
1330 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1331 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1332 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1333 //
1334 // Formally:
1335 //
1336 //     {S,+,X} == {S-T,+,X} + T
1337 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1338 //
1339 // If ({S-T,+,X} + T) does not overflow  ... (1)
1340 //
1341 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1342 //
1343 // If {S-T,+,X} does not overflow  ... (2)
1344 //
1345 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1346 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1347 //
1348 // If (S-T)+T does not overflow  ... (3)
1349 //
1350 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1351 //      == {Ext(S),+,Ext(X)} == LHS
1352 //
1353 // Thus, if (1), (2) and (3) are true for some T, then
1354 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1355 //
1356 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1357 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1358 // to check for (1) and (2).
1359 //
1360 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1361 // is `Delta` (defined below).
1362 //
1363 template <typename ExtendOpTy>
1364 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1365                                                 const SCEV *Step,
1366                                                 const Loop *L) {
1367   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1368 
1369   // We restrict `Start` to a constant to prevent SCEV from spending too much
1370   // time here.  It is correct (but more expensive) to continue with a
1371   // non-constant `Start` and do a general SCEV subtraction to compute
1372   // `PreStart` below.
1373   //
1374   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1375   if (!StartC)
1376     return false;
1377 
1378   APInt StartAI = StartC->getAPInt();
1379 
1380   for (unsigned Delta : {-2, -1, 1, 2}) {
1381     const SCEV *PreStart = getConstant(StartAI - Delta);
1382 
1383     FoldingSetNodeID ID;
1384     ID.AddInteger(scAddRecExpr);
1385     ID.AddPointer(PreStart);
1386     ID.AddPointer(Step);
1387     ID.AddPointer(L);
1388     void *IP = nullptr;
1389     const auto *PreAR =
1390       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1391 
1392     // Give up if we don't already have the add recurrence we need because
1393     // actually constructing an add recurrence is relatively expensive.
1394     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1395       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1396       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1397       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1398           DeltaS, &Pred, this);
1399       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1400         return true;
1401     }
1402   }
1403 
1404   return false;
1405 }
1406 
1407 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1408                                                Type *Ty) {
1409   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1410          "This is not an extending conversion!");
1411   assert(isSCEVable(Ty) &&
1412          "This is not a conversion to a SCEVable type!");
1413   Ty = getEffectiveSCEVType(Ty);
1414 
1415   // Fold if the operand is constant.
1416   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1417     return getConstant(
1418       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1419 
1420   // zext(zext(x)) --> zext(x)
1421   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1422     return getZeroExtendExpr(SZ->getOperand(), Ty);
1423 
1424   // Before doing any expensive analysis, check to see if we've already
1425   // computed a SCEV for this Op and Ty.
1426   FoldingSetNodeID ID;
1427   ID.AddInteger(scZeroExtend);
1428   ID.AddPointer(Op);
1429   ID.AddPointer(Ty);
1430   void *IP = nullptr;
1431   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1432 
1433   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1434   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1435     // It's possible the bits taken off by the truncate were all zero bits. If
1436     // so, we should be able to simplify this further.
1437     const SCEV *X = ST->getOperand();
1438     ConstantRange CR = getUnsignedRange(X);
1439     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1440     unsigned NewBits = getTypeSizeInBits(Ty);
1441     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1442             CR.zextOrTrunc(NewBits)))
1443       return getTruncateOrZeroExtend(X, Ty);
1444   }
1445 
1446   // If the input value is a chrec scev, and we can prove that the value
1447   // did not overflow the old, smaller, value, we can zero extend all of the
1448   // operands (often constants).  This allows analysis of something like
1449   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1450   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1451     if (AR->isAffine()) {
1452       const SCEV *Start = AR->getStart();
1453       const SCEV *Step = AR->getStepRecurrence(*this);
1454       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1455       const Loop *L = AR->getLoop();
1456 
1457       if (!AR->hasNoUnsignedWrap()) {
1458         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1459         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1460       }
1461 
1462       // If we have special knowledge that this addrec won't overflow,
1463       // we don't need to do any further analysis.
1464       if (AR->hasNoUnsignedWrap())
1465         return getAddRecExpr(
1466             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1467             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1468 
1469       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1470       // Note that this serves two purposes: It filters out loops that are
1471       // simply not analyzable, and it covers the case where this code is
1472       // being called from within backedge-taken count analysis, such that
1473       // attempting to ask for the backedge-taken count would likely result
1474       // in infinite recursion. In the later case, the analysis code will
1475       // cope with a conservative value, and it will take care to purge
1476       // that value once it has finished.
1477       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1478       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1479         // Manually compute the final value for AR, checking for
1480         // overflow.
1481 
1482         // Check whether the backedge-taken count can be losslessly casted to
1483         // the addrec's type. The count is always unsigned.
1484         const SCEV *CastedMaxBECount =
1485           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1486         const SCEV *RecastedMaxBECount =
1487           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1488         if (MaxBECount == RecastedMaxBECount) {
1489           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1490           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1491           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1492           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1493           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1494           const SCEV *WideMaxBECount =
1495             getZeroExtendExpr(CastedMaxBECount, WideTy);
1496           const SCEV *OperandExtendedAdd =
1497             getAddExpr(WideStart,
1498                        getMulExpr(WideMaxBECount,
1499                                   getZeroExtendExpr(Step, WideTy)));
1500           if (ZAdd == OperandExtendedAdd) {
1501             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1502             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1503             // Return the expression with the addrec on the outside.
1504             return getAddRecExpr(
1505                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1506                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1507           }
1508           // Similar to above, only this time treat the step value as signed.
1509           // This covers loops that count down.
1510           OperandExtendedAdd =
1511             getAddExpr(WideStart,
1512                        getMulExpr(WideMaxBECount,
1513                                   getSignExtendExpr(Step, WideTy)));
1514           if (ZAdd == OperandExtendedAdd) {
1515             // Cache knowledge of AR NW, which is propagated to this AddRec.
1516             // Negative step causes unsigned wrap, but it still can't self-wrap.
1517             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1518             // Return the expression with the addrec on the outside.
1519             return getAddRecExpr(
1520                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1521                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1522           }
1523         }
1524       }
1525 
1526       // Normally, in the cases we can prove no-overflow via a
1527       // backedge guarding condition, we can also compute a backedge
1528       // taken count for the loop.  The exceptions are assumptions and
1529       // guards present in the loop -- SCEV is not great at exploiting
1530       // these to compute max backedge taken counts, but can still use
1531       // these to prove lack of overflow.  Use this fact to avoid
1532       // doing extra work that may not pay off.
1533       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1534           !AC.assumptions().empty()) {
1535         // If the backedge is guarded by a comparison with the pre-inc
1536         // value the addrec is safe. Also, if the entry is guarded by
1537         // a comparison with the start value and the backedge is
1538         // guarded by a comparison with the post-inc value, the addrec
1539         // is safe.
1540         if (isKnownPositive(Step)) {
1541           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1542                                       getUnsignedRange(Step).getUnsignedMax());
1543           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1544               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1545                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1546                                            AR->getPostIncExpr(*this), N))) {
1547             // Cache knowledge of AR NUW, which is propagated to this
1548             // AddRec.
1549             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1550             // Return the expression with the addrec on the outside.
1551             return getAddRecExpr(
1552                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1553                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1554           }
1555         } else if (isKnownNegative(Step)) {
1556           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1557                                       getSignedRange(Step).getSignedMin());
1558           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1559               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1560                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1561                                            AR->getPostIncExpr(*this), N))) {
1562             // Cache knowledge of AR NW, which is propagated to this
1563             // AddRec.  Negative step causes unsigned wrap, but it
1564             // still can't self-wrap.
1565             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1566             // Return the expression with the addrec on the outside.
1567             return getAddRecExpr(
1568                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1569                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1570           }
1571         }
1572       }
1573 
1574       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1575         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1576         return getAddRecExpr(
1577             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1578             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1579       }
1580     }
1581 
1582   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1583     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1584     if (SA->hasNoUnsignedWrap()) {
1585       // If the addition does not unsign overflow then we can, by definition,
1586       // commute the zero extension with the addition operation.
1587       SmallVector<const SCEV *, 4> Ops;
1588       for (const auto *Op : SA->operands())
1589         Ops.push_back(getZeroExtendExpr(Op, Ty));
1590       return getAddExpr(Ops, SCEV::FlagNUW);
1591     }
1592   }
1593 
1594   // The cast wasn't folded; create an explicit cast node.
1595   // Recompute the insert position, as it may have been invalidated.
1596   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1597   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1598                                                    Op, Ty);
1599   UniqueSCEVs.InsertNode(S, IP);
1600   return S;
1601 }
1602 
1603 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1604                                                Type *Ty) {
1605   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1606          "This is not an extending conversion!");
1607   assert(isSCEVable(Ty) &&
1608          "This is not a conversion to a SCEVable type!");
1609   Ty = getEffectiveSCEVType(Ty);
1610 
1611   // Fold if the operand is constant.
1612   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1613     return getConstant(
1614       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1615 
1616   // sext(sext(x)) --> sext(x)
1617   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1618     return getSignExtendExpr(SS->getOperand(), Ty);
1619 
1620   // sext(zext(x)) --> zext(x)
1621   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1622     return getZeroExtendExpr(SZ->getOperand(), Ty);
1623 
1624   // Before doing any expensive analysis, check to see if we've already
1625   // computed a SCEV for this Op and Ty.
1626   FoldingSetNodeID ID;
1627   ID.AddInteger(scSignExtend);
1628   ID.AddPointer(Op);
1629   ID.AddPointer(Ty);
1630   void *IP = nullptr;
1631   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1632 
1633   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1634   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1635     // It's possible the bits taken off by the truncate were all sign bits. If
1636     // so, we should be able to simplify this further.
1637     const SCEV *X = ST->getOperand();
1638     ConstantRange CR = getSignedRange(X);
1639     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1640     unsigned NewBits = getTypeSizeInBits(Ty);
1641     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1642             CR.sextOrTrunc(NewBits)))
1643       return getTruncateOrSignExtend(X, Ty);
1644   }
1645 
1646   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1647   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1648     if (SA->getNumOperands() == 2) {
1649       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1650       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1651       if (SMul && SC1) {
1652         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1653           const APInt &C1 = SC1->getAPInt();
1654           const APInt &C2 = SC2->getAPInt();
1655           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1656               C2.ugt(C1) && C2.isPowerOf2())
1657             return getAddExpr(getSignExtendExpr(SC1, Ty),
1658                               getSignExtendExpr(SMul, Ty));
1659         }
1660       }
1661     }
1662 
1663     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1664     if (SA->hasNoSignedWrap()) {
1665       // If the addition does not sign overflow then we can, by definition,
1666       // commute the sign extension with the addition operation.
1667       SmallVector<const SCEV *, 4> Ops;
1668       for (const auto *Op : SA->operands())
1669         Ops.push_back(getSignExtendExpr(Op, Ty));
1670       return getAddExpr(Ops, SCEV::FlagNSW);
1671     }
1672   }
1673   // If the input value is a chrec scev, and we can prove that the value
1674   // did not overflow the old, smaller, value, we can sign extend all of the
1675   // operands (often constants).  This allows analysis of something like
1676   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1677   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1678     if (AR->isAffine()) {
1679       const SCEV *Start = AR->getStart();
1680       const SCEV *Step = AR->getStepRecurrence(*this);
1681       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1682       const Loop *L = AR->getLoop();
1683 
1684       if (!AR->hasNoSignedWrap()) {
1685         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1686         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1687       }
1688 
1689       // If we have special knowledge that this addrec won't overflow,
1690       // we don't need to do any further analysis.
1691       if (AR->hasNoSignedWrap())
1692         return getAddRecExpr(
1693             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1694             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1695 
1696       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1697       // Note that this serves two purposes: It filters out loops that are
1698       // simply not analyzable, and it covers the case where this code is
1699       // being called from within backedge-taken count analysis, such that
1700       // attempting to ask for the backedge-taken count would likely result
1701       // in infinite recursion. In the later case, the analysis code will
1702       // cope with a conservative value, and it will take care to purge
1703       // that value once it has finished.
1704       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1705       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1706         // Manually compute the final value for AR, checking for
1707         // overflow.
1708 
1709         // Check whether the backedge-taken count can be losslessly casted to
1710         // the addrec's type. The count is always unsigned.
1711         const SCEV *CastedMaxBECount =
1712           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1713         const SCEV *RecastedMaxBECount =
1714           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1715         if (MaxBECount == RecastedMaxBECount) {
1716           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1717           // Check whether Start+Step*MaxBECount has no signed overflow.
1718           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1719           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1720           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1721           const SCEV *WideMaxBECount =
1722             getZeroExtendExpr(CastedMaxBECount, WideTy);
1723           const SCEV *OperandExtendedAdd =
1724             getAddExpr(WideStart,
1725                        getMulExpr(WideMaxBECount,
1726                                   getSignExtendExpr(Step, WideTy)));
1727           if (SAdd == OperandExtendedAdd) {
1728             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1729             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1730             // Return the expression with the addrec on the outside.
1731             return getAddRecExpr(
1732                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1733                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1734           }
1735           // Similar to above, only this time treat the step value as unsigned.
1736           // This covers loops that count up with an unsigned step.
1737           OperandExtendedAdd =
1738             getAddExpr(WideStart,
1739                        getMulExpr(WideMaxBECount,
1740                                   getZeroExtendExpr(Step, WideTy)));
1741           if (SAdd == OperandExtendedAdd) {
1742             // If AR wraps around then
1743             //
1744             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1745             // => SAdd != OperandExtendedAdd
1746             //
1747             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1748             // (SAdd == OperandExtendedAdd => AR is NW)
1749 
1750             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1751 
1752             // Return the expression with the addrec on the outside.
1753             return getAddRecExpr(
1754                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1755                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1756           }
1757         }
1758       }
1759 
1760       // Normally, in the cases we can prove no-overflow via a
1761       // backedge guarding condition, we can also compute a backedge
1762       // taken count for the loop.  The exceptions are assumptions and
1763       // guards present in the loop -- SCEV is not great at exploiting
1764       // these to compute max backedge taken counts, but can still use
1765       // these to prove lack of overflow.  Use this fact to avoid
1766       // doing extra work that may not pay off.
1767 
1768       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1769           !AC.assumptions().empty()) {
1770         // If the backedge is guarded by a comparison with the pre-inc
1771         // value the addrec is safe. Also, if the entry is guarded by
1772         // a comparison with the start value and the backedge is
1773         // guarded by a comparison with the post-inc value, the addrec
1774         // is safe.
1775         ICmpInst::Predicate Pred;
1776         const SCEV *OverflowLimit =
1777             getSignedOverflowLimitForStep(Step, &Pred, this);
1778         if (OverflowLimit &&
1779             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1780              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1781               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1782                                           OverflowLimit)))) {
1783           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1784           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1785           return getAddRecExpr(
1786               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1787               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1788         }
1789       }
1790 
1791       // If Start and Step are constants, check if we can apply this
1792       // transformation:
1793       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1794       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1795       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1796       if (SC1 && SC2) {
1797         const APInt &C1 = SC1->getAPInt();
1798         const APInt &C2 = SC2->getAPInt();
1799         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1800             C2.isPowerOf2()) {
1801           Start = getSignExtendExpr(Start, Ty);
1802           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1803                                             AR->getNoWrapFlags());
1804           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1805         }
1806       }
1807 
1808       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1809         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1810         return getAddRecExpr(
1811             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1812             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1813       }
1814     }
1815 
1816   // If the input value is provably positive and we could not simplify
1817   // away the sext build a zext instead.
1818   if (isKnownNonNegative(Op))
1819     return getZeroExtendExpr(Op, Ty);
1820 
1821   // The cast wasn't folded; create an explicit cast node.
1822   // Recompute the insert position, as it may have been invalidated.
1823   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1824   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1825                                                    Op, Ty);
1826   UniqueSCEVs.InsertNode(S, IP);
1827   return S;
1828 }
1829 
1830 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1831 /// unspecified bits out to the given type.
1832 ///
1833 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1834                                               Type *Ty) {
1835   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1836          "This is not an extending conversion!");
1837   assert(isSCEVable(Ty) &&
1838          "This is not a conversion to a SCEVable type!");
1839   Ty = getEffectiveSCEVType(Ty);
1840 
1841   // Sign-extend negative constants.
1842   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1843     if (SC->getAPInt().isNegative())
1844       return getSignExtendExpr(Op, Ty);
1845 
1846   // Peel off a truncate cast.
1847   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1848     const SCEV *NewOp = T->getOperand();
1849     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1850       return getAnyExtendExpr(NewOp, Ty);
1851     return getTruncateOrNoop(NewOp, Ty);
1852   }
1853 
1854   // Next try a zext cast. If the cast is folded, use it.
1855   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1856   if (!isa<SCEVZeroExtendExpr>(ZExt))
1857     return ZExt;
1858 
1859   // Next try a sext cast. If the cast is folded, use it.
1860   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1861   if (!isa<SCEVSignExtendExpr>(SExt))
1862     return SExt;
1863 
1864   // Force the cast to be folded into the operands of an addrec.
1865   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1866     SmallVector<const SCEV *, 4> Ops;
1867     for (const SCEV *Op : AR->operands())
1868       Ops.push_back(getAnyExtendExpr(Op, Ty));
1869     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1870   }
1871 
1872   // If the expression is obviously signed, use the sext cast value.
1873   if (isa<SCEVSMaxExpr>(Op))
1874     return SExt;
1875 
1876   // Absent any other information, use the zext cast value.
1877   return ZExt;
1878 }
1879 
1880 /// Process the given Ops list, which is a list of operands to be added under
1881 /// the given scale, update the given map. This is a helper function for
1882 /// getAddRecExpr. As an example of what it does, given a sequence of operands
1883 /// that would form an add expression like this:
1884 ///
1885 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1886 ///
1887 /// where A and B are constants, update the map with these values:
1888 ///
1889 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1890 ///
1891 /// and add 13 + A*B*29 to AccumulatedConstant.
1892 /// This will allow getAddRecExpr to produce this:
1893 ///
1894 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1895 ///
1896 /// This form often exposes folding opportunities that are hidden in
1897 /// the original operand list.
1898 ///
1899 /// Return true iff it appears that any interesting folding opportunities
1900 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1901 /// the common case where no interesting opportunities are present, and
1902 /// is also used as a check to avoid infinite recursion.
1903 ///
1904 static bool
1905 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1906                              SmallVectorImpl<const SCEV *> &NewOps,
1907                              APInt &AccumulatedConstant,
1908                              const SCEV *const *Ops, size_t NumOperands,
1909                              const APInt &Scale,
1910                              ScalarEvolution &SE) {
1911   bool Interesting = false;
1912 
1913   // Iterate over the add operands. They are sorted, with constants first.
1914   unsigned i = 0;
1915   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1916     ++i;
1917     // Pull a buried constant out to the outside.
1918     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1919       Interesting = true;
1920     AccumulatedConstant += Scale * C->getAPInt();
1921   }
1922 
1923   // Next comes everything else. We're especially interested in multiplies
1924   // here, but they're in the middle, so just visit the rest with one loop.
1925   for (; i != NumOperands; ++i) {
1926     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1927     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1928       APInt NewScale =
1929           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
1930       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1931         // A multiplication of a constant with another add; recurse.
1932         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1933         Interesting |=
1934           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1935                                        Add->op_begin(), Add->getNumOperands(),
1936                                        NewScale, SE);
1937       } else {
1938         // A multiplication of a constant with some other value. Update
1939         // the map.
1940         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1941         const SCEV *Key = SE.getMulExpr(MulOps);
1942         auto Pair = M.insert({Key, NewScale});
1943         if (Pair.second) {
1944           NewOps.push_back(Pair.first->first);
1945         } else {
1946           Pair.first->second += NewScale;
1947           // The map already had an entry for this value, which may indicate
1948           // a folding opportunity.
1949           Interesting = true;
1950         }
1951       }
1952     } else {
1953       // An ordinary operand. Update the map.
1954       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1955           M.insert({Ops[i], Scale});
1956       if (Pair.second) {
1957         NewOps.push_back(Pair.first->first);
1958       } else {
1959         Pair.first->second += Scale;
1960         // The map already had an entry for this value, which may indicate
1961         // a folding opportunity.
1962         Interesting = true;
1963       }
1964     }
1965   }
1966 
1967   return Interesting;
1968 }
1969 
1970 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1971 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
1972 // can't-overflow flags for the operation if possible.
1973 static SCEV::NoWrapFlags
1974 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1975                       const SmallVectorImpl<const SCEV *> &Ops,
1976                       SCEV::NoWrapFlags Flags) {
1977   using namespace std::placeholders;
1978   typedef OverflowingBinaryOperator OBO;
1979 
1980   bool CanAnalyze =
1981       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1982   (void)CanAnalyze;
1983   assert(CanAnalyze && "don't call from other places!");
1984 
1985   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1986   SCEV::NoWrapFlags SignOrUnsignWrap =
1987       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1988 
1989   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1990   auto IsKnownNonNegative = [&](const SCEV *S) {
1991     return SE->isKnownNonNegative(S);
1992   };
1993 
1994   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
1995     Flags =
1996         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1997 
1998   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1999 
2000   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2001       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2002 
2003     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2004     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2005 
2006     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2007     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2008       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2009           Instruction::Add, C, OBO::NoSignedWrap);
2010       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2011         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2012     }
2013     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2014       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2015           Instruction::Add, C, OBO::NoUnsignedWrap);
2016       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2017         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2018     }
2019   }
2020 
2021   return Flags;
2022 }
2023 
2024 /// Get a canonical add expression, or something simpler if possible.
2025 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2026                                         SCEV::NoWrapFlags Flags) {
2027   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2028          "only nuw or nsw allowed");
2029   assert(!Ops.empty() && "Cannot get empty add!");
2030   if (Ops.size() == 1) return Ops[0];
2031 #ifndef NDEBUG
2032   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2033   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2034     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2035            "SCEVAddExpr operand types don't match!");
2036 #endif
2037 
2038   // Sort by complexity, this groups all similar expression types together.
2039   GroupByComplexity(Ops, &LI);
2040 
2041   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2042 
2043   // If there are any constants, fold them together.
2044   unsigned Idx = 0;
2045   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2046     ++Idx;
2047     assert(Idx < Ops.size());
2048     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2049       // We found two constants, fold them together!
2050       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2051       if (Ops.size() == 2) return Ops[0];
2052       Ops.erase(Ops.begin()+1);  // Erase the folded element
2053       LHSC = cast<SCEVConstant>(Ops[0]);
2054     }
2055 
2056     // If we are left with a constant zero being added, strip it off.
2057     if (LHSC->getValue()->isZero()) {
2058       Ops.erase(Ops.begin());
2059       --Idx;
2060     }
2061 
2062     if (Ops.size() == 1) return Ops[0];
2063   }
2064 
2065   // Okay, check to see if the same value occurs in the operand list more than
2066   // once.  If so, merge them together into an multiply expression.  Since we
2067   // sorted the list, these values are required to be adjacent.
2068   Type *Ty = Ops[0]->getType();
2069   bool FoundMatch = false;
2070   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2071     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2072       // Scan ahead to count how many equal operands there are.
2073       unsigned Count = 2;
2074       while (i+Count != e && Ops[i+Count] == Ops[i])
2075         ++Count;
2076       // Merge the values into a multiply.
2077       const SCEV *Scale = getConstant(Ty, Count);
2078       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2079       if (Ops.size() == Count)
2080         return Mul;
2081       Ops[i] = Mul;
2082       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2083       --i; e -= Count - 1;
2084       FoundMatch = true;
2085     }
2086   if (FoundMatch)
2087     return getAddExpr(Ops, Flags);
2088 
2089   // Check for truncates. If all the operands are truncated from the same
2090   // type, see if factoring out the truncate would permit the result to be
2091   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2092   // if the contents of the resulting outer trunc fold to something simple.
2093   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2094     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2095     Type *DstType = Trunc->getType();
2096     Type *SrcType = Trunc->getOperand()->getType();
2097     SmallVector<const SCEV *, 8> LargeOps;
2098     bool Ok = true;
2099     // Check all the operands to see if they can be represented in the
2100     // source type of the truncate.
2101     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2102       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2103         if (T->getOperand()->getType() != SrcType) {
2104           Ok = false;
2105           break;
2106         }
2107         LargeOps.push_back(T->getOperand());
2108       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2109         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2110       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2111         SmallVector<const SCEV *, 8> LargeMulOps;
2112         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2113           if (const SCEVTruncateExpr *T =
2114                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2115             if (T->getOperand()->getType() != SrcType) {
2116               Ok = false;
2117               break;
2118             }
2119             LargeMulOps.push_back(T->getOperand());
2120           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2121             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2122           } else {
2123             Ok = false;
2124             break;
2125           }
2126         }
2127         if (Ok)
2128           LargeOps.push_back(getMulExpr(LargeMulOps));
2129       } else {
2130         Ok = false;
2131         break;
2132       }
2133     }
2134     if (Ok) {
2135       // Evaluate the expression in the larger type.
2136       const SCEV *Fold = getAddExpr(LargeOps, Flags);
2137       // If it folds to something simple, use it. Otherwise, don't.
2138       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2139         return getTruncateExpr(Fold, DstType);
2140     }
2141   }
2142 
2143   // Skip past any other cast SCEVs.
2144   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2145     ++Idx;
2146 
2147   // If there are add operands they would be next.
2148   if (Idx < Ops.size()) {
2149     bool DeletedAdd = false;
2150     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2151       // If we have an add, expand the add operands onto the end of the operands
2152       // list.
2153       Ops.erase(Ops.begin()+Idx);
2154       Ops.append(Add->op_begin(), Add->op_end());
2155       DeletedAdd = true;
2156     }
2157 
2158     // If we deleted at least one add, we added operands to the end of the list,
2159     // and they are not necessarily sorted.  Recurse to resort and resimplify
2160     // any operands we just acquired.
2161     if (DeletedAdd)
2162       return getAddExpr(Ops);
2163   }
2164 
2165   // Skip over the add expression until we get to a multiply.
2166   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2167     ++Idx;
2168 
2169   // Check to see if there are any folding opportunities present with
2170   // operands multiplied by constant values.
2171   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2172     uint64_t BitWidth = getTypeSizeInBits(Ty);
2173     DenseMap<const SCEV *, APInt> M;
2174     SmallVector<const SCEV *, 8> NewOps;
2175     APInt AccumulatedConstant(BitWidth, 0);
2176     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2177                                      Ops.data(), Ops.size(),
2178                                      APInt(BitWidth, 1), *this)) {
2179       struct APIntCompare {
2180         bool operator()(const APInt &LHS, const APInt &RHS) const {
2181           return LHS.ult(RHS);
2182         }
2183       };
2184 
2185       // Some interesting folding opportunity is present, so its worthwhile to
2186       // re-generate the operands list. Group the operands by constant scale,
2187       // to avoid multiplying by the same constant scale multiple times.
2188       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2189       for (const SCEV *NewOp : NewOps)
2190         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2191       // Re-generate the operands list.
2192       Ops.clear();
2193       if (AccumulatedConstant != 0)
2194         Ops.push_back(getConstant(AccumulatedConstant));
2195       for (auto &MulOp : MulOpLists)
2196         if (MulOp.first != 0)
2197           Ops.push_back(getMulExpr(getConstant(MulOp.first),
2198                                    getAddExpr(MulOp.second)));
2199       if (Ops.empty())
2200         return getZero(Ty);
2201       if (Ops.size() == 1)
2202         return Ops[0];
2203       return getAddExpr(Ops);
2204     }
2205   }
2206 
2207   // If we are adding something to a multiply expression, make sure the
2208   // something is not already an operand of the multiply.  If so, merge it into
2209   // the multiply.
2210   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2211     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2212     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2213       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2214       if (isa<SCEVConstant>(MulOpSCEV))
2215         continue;
2216       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2217         if (MulOpSCEV == Ops[AddOp]) {
2218           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2219           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2220           if (Mul->getNumOperands() != 2) {
2221             // If the multiply has more than two operands, we must get the
2222             // Y*Z term.
2223             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2224                                                 Mul->op_begin()+MulOp);
2225             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2226             InnerMul = getMulExpr(MulOps);
2227           }
2228           const SCEV *One = getOne(Ty);
2229           const SCEV *AddOne = getAddExpr(One, InnerMul);
2230           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2231           if (Ops.size() == 2) return OuterMul;
2232           if (AddOp < Idx) {
2233             Ops.erase(Ops.begin()+AddOp);
2234             Ops.erase(Ops.begin()+Idx-1);
2235           } else {
2236             Ops.erase(Ops.begin()+Idx);
2237             Ops.erase(Ops.begin()+AddOp-1);
2238           }
2239           Ops.push_back(OuterMul);
2240           return getAddExpr(Ops);
2241         }
2242 
2243       // Check this multiply against other multiplies being added together.
2244       for (unsigned OtherMulIdx = Idx+1;
2245            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2246            ++OtherMulIdx) {
2247         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2248         // If MulOp occurs in OtherMul, we can fold the two multiplies
2249         // together.
2250         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2251              OMulOp != e; ++OMulOp)
2252           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2253             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2254             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2255             if (Mul->getNumOperands() != 2) {
2256               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2257                                                   Mul->op_begin()+MulOp);
2258               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2259               InnerMul1 = getMulExpr(MulOps);
2260             }
2261             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2262             if (OtherMul->getNumOperands() != 2) {
2263               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2264                                                   OtherMul->op_begin()+OMulOp);
2265               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2266               InnerMul2 = getMulExpr(MulOps);
2267             }
2268             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2269             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2270             if (Ops.size() == 2) return OuterMul;
2271             Ops.erase(Ops.begin()+Idx);
2272             Ops.erase(Ops.begin()+OtherMulIdx-1);
2273             Ops.push_back(OuterMul);
2274             return getAddExpr(Ops);
2275           }
2276       }
2277     }
2278   }
2279 
2280   // If there are any add recurrences in the operands list, see if any other
2281   // added values are loop invariant.  If so, we can fold them into the
2282   // recurrence.
2283   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2284     ++Idx;
2285 
2286   // Scan over all recurrences, trying to fold loop invariants into them.
2287   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2288     // Scan all of the other operands to this add and add them to the vector if
2289     // they are loop invariant w.r.t. the recurrence.
2290     SmallVector<const SCEV *, 8> LIOps;
2291     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2292     const Loop *AddRecLoop = AddRec->getLoop();
2293     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2294       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2295         LIOps.push_back(Ops[i]);
2296         Ops.erase(Ops.begin()+i);
2297         --i; --e;
2298       }
2299 
2300     // If we found some loop invariants, fold them into the recurrence.
2301     if (!LIOps.empty()) {
2302       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2303       LIOps.push_back(AddRec->getStart());
2304 
2305       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2306                                              AddRec->op_end());
2307       // This follows from the fact that the no-wrap flags on the outer add
2308       // expression are applicable on the 0th iteration, when the add recurrence
2309       // will be equal to its start value.
2310       AddRecOps[0] = getAddExpr(LIOps, Flags);
2311 
2312       // Build the new addrec. Propagate the NUW and NSW flags if both the
2313       // outer add and the inner addrec are guaranteed to have no overflow.
2314       // Always propagate NW.
2315       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2316       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2317 
2318       // If all of the other operands were loop invariant, we are done.
2319       if (Ops.size() == 1) return NewRec;
2320 
2321       // Otherwise, add the folded AddRec by the non-invariant parts.
2322       for (unsigned i = 0;; ++i)
2323         if (Ops[i] == AddRec) {
2324           Ops[i] = NewRec;
2325           break;
2326         }
2327       return getAddExpr(Ops);
2328     }
2329 
2330     // Okay, if there weren't any loop invariants to be folded, check to see if
2331     // there are multiple AddRec's with the same loop induction variable being
2332     // added together.  If so, we can fold them.
2333     for (unsigned OtherIdx = Idx+1;
2334          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2335          ++OtherIdx)
2336       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2337         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2338         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2339                                                AddRec->op_end());
2340         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2341              ++OtherIdx)
2342           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2343             if (OtherAddRec->getLoop() == AddRecLoop) {
2344               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2345                    i != e; ++i) {
2346                 if (i >= AddRecOps.size()) {
2347                   AddRecOps.append(OtherAddRec->op_begin()+i,
2348                                    OtherAddRec->op_end());
2349                   break;
2350                 }
2351                 AddRecOps[i] = getAddExpr(AddRecOps[i],
2352                                           OtherAddRec->getOperand(i));
2353               }
2354               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2355             }
2356         // Step size has changed, so we cannot guarantee no self-wraparound.
2357         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2358         return getAddExpr(Ops);
2359       }
2360 
2361     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2362     // next one.
2363   }
2364 
2365   // Okay, it looks like we really DO need an add expr.  Check to see if we
2366   // already have one, otherwise create a new one.
2367   FoldingSetNodeID ID;
2368   ID.AddInteger(scAddExpr);
2369   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2370     ID.AddPointer(Ops[i]);
2371   void *IP = nullptr;
2372   SCEVAddExpr *S =
2373     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2374   if (!S) {
2375     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2376     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2377     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2378                                         O, Ops.size());
2379     UniqueSCEVs.InsertNode(S, IP);
2380   }
2381   S->setNoWrapFlags(Flags);
2382   return S;
2383 }
2384 
2385 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2386   uint64_t k = i*j;
2387   if (j > 1 && k / j != i) Overflow = true;
2388   return k;
2389 }
2390 
2391 /// Compute the result of "n choose k", the binomial coefficient.  If an
2392 /// intermediate computation overflows, Overflow will be set and the return will
2393 /// be garbage. Overflow is not cleared on absence of overflow.
2394 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2395   // We use the multiplicative formula:
2396   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2397   // At each iteration, we take the n-th term of the numeral and divide by the
2398   // (k-n)th term of the denominator.  This division will always produce an
2399   // integral result, and helps reduce the chance of overflow in the
2400   // intermediate computations. However, we can still overflow even when the
2401   // final result would fit.
2402 
2403   if (n == 0 || n == k) return 1;
2404   if (k > n) return 0;
2405 
2406   if (k > n/2)
2407     k = n-k;
2408 
2409   uint64_t r = 1;
2410   for (uint64_t i = 1; i <= k; ++i) {
2411     r = umul_ov(r, n-(i-1), Overflow);
2412     r /= i;
2413   }
2414   return r;
2415 }
2416 
2417 /// Determine if any of the operands in this SCEV are a constant or if
2418 /// any of the add or multiply expressions in this SCEV contain a constant.
2419 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2420   SmallVector<const SCEV *, 4> Ops;
2421   Ops.push_back(StartExpr);
2422   while (!Ops.empty()) {
2423     const SCEV *CurrentExpr = Ops.pop_back_val();
2424     if (isa<SCEVConstant>(*CurrentExpr))
2425       return true;
2426 
2427     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2428       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2429       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2430     }
2431   }
2432   return false;
2433 }
2434 
2435 /// Get a canonical multiply expression, or something simpler if possible.
2436 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2437                                         SCEV::NoWrapFlags Flags) {
2438   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2439          "only nuw or nsw allowed");
2440   assert(!Ops.empty() && "Cannot get empty mul!");
2441   if (Ops.size() == 1) return Ops[0];
2442 #ifndef NDEBUG
2443   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2444   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2445     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2446            "SCEVMulExpr operand types don't match!");
2447 #endif
2448 
2449   // Sort by complexity, this groups all similar expression types together.
2450   GroupByComplexity(Ops, &LI);
2451 
2452   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2453 
2454   // If there are any constants, fold them together.
2455   unsigned Idx = 0;
2456   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2457 
2458     // C1*(C2+V) -> C1*C2 + C1*V
2459     if (Ops.size() == 2)
2460         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2461           // If any of Add's ops are Adds or Muls with a constant,
2462           // apply this transformation as well.
2463           if (Add->getNumOperands() == 2)
2464             if (containsConstantSomewhere(Add))
2465               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2466                                 getMulExpr(LHSC, Add->getOperand(1)));
2467 
2468     ++Idx;
2469     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2470       // We found two constants, fold them together!
2471       ConstantInt *Fold =
2472           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2473       Ops[0] = getConstant(Fold);
2474       Ops.erase(Ops.begin()+1);  // Erase the folded element
2475       if (Ops.size() == 1) return Ops[0];
2476       LHSC = cast<SCEVConstant>(Ops[0]);
2477     }
2478 
2479     // If we are left with a constant one being multiplied, strip it off.
2480     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2481       Ops.erase(Ops.begin());
2482       --Idx;
2483     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2484       // If we have a multiply of zero, it will always be zero.
2485       return Ops[0];
2486     } else if (Ops[0]->isAllOnesValue()) {
2487       // If we have a mul by -1 of an add, try distributing the -1 among the
2488       // add operands.
2489       if (Ops.size() == 2) {
2490         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2491           SmallVector<const SCEV *, 4> NewOps;
2492           bool AnyFolded = false;
2493           for (const SCEV *AddOp : Add->operands()) {
2494             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2495             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2496             NewOps.push_back(Mul);
2497           }
2498           if (AnyFolded)
2499             return getAddExpr(NewOps);
2500         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2501           // Negation preserves a recurrence's no self-wrap property.
2502           SmallVector<const SCEV *, 4> Operands;
2503           for (const SCEV *AddRecOp : AddRec->operands())
2504             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2505 
2506           return getAddRecExpr(Operands, AddRec->getLoop(),
2507                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2508         }
2509       }
2510     }
2511 
2512     if (Ops.size() == 1)
2513       return Ops[0];
2514   }
2515 
2516   // Skip over the add expression until we get to a multiply.
2517   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2518     ++Idx;
2519 
2520   // If there are mul operands inline them all into this expression.
2521   if (Idx < Ops.size()) {
2522     bool DeletedMul = false;
2523     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2524       if (Ops.size() > MulOpsInlineThreshold)
2525         break;
2526       // If we have an mul, expand the mul operands onto the end of the operands
2527       // list.
2528       Ops.erase(Ops.begin()+Idx);
2529       Ops.append(Mul->op_begin(), Mul->op_end());
2530       DeletedMul = true;
2531     }
2532 
2533     // If we deleted at least one mul, we added operands to the end of the list,
2534     // and they are not necessarily sorted.  Recurse to resort and resimplify
2535     // any operands we just acquired.
2536     if (DeletedMul)
2537       return getMulExpr(Ops);
2538   }
2539 
2540   // If there are any add recurrences in the operands list, see if any other
2541   // added values are loop invariant.  If so, we can fold them into the
2542   // recurrence.
2543   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2544     ++Idx;
2545 
2546   // Scan over all recurrences, trying to fold loop invariants into them.
2547   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2548     // Scan all of the other operands to this mul and add them to the vector if
2549     // they are loop invariant w.r.t. the recurrence.
2550     SmallVector<const SCEV *, 8> LIOps;
2551     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2552     const Loop *AddRecLoop = AddRec->getLoop();
2553     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2554       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2555         LIOps.push_back(Ops[i]);
2556         Ops.erase(Ops.begin()+i);
2557         --i; --e;
2558       }
2559 
2560     // If we found some loop invariants, fold them into the recurrence.
2561     if (!LIOps.empty()) {
2562       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2563       SmallVector<const SCEV *, 4> NewOps;
2564       NewOps.reserve(AddRec->getNumOperands());
2565       const SCEV *Scale = getMulExpr(LIOps);
2566       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2567         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2568 
2569       // Build the new addrec. Propagate the NUW and NSW flags if both the
2570       // outer mul and the inner addrec are guaranteed to have no overflow.
2571       //
2572       // No self-wrap cannot be guaranteed after changing the step size, but
2573       // will be inferred if either NUW or NSW is true.
2574       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2575       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2576 
2577       // If all of the other operands were loop invariant, we are done.
2578       if (Ops.size() == 1) return NewRec;
2579 
2580       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2581       for (unsigned i = 0;; ++i)
2582         if (Ops[i] == AddRec) {
2583           Ops[i] = NewRec;
2584           break;
2585         }
2586       return getMulExpr(Ops);
2587     }
2588 
2589     // Okay, if there weren't any loop invariants to be folded, check to see if
2590     // there are multiple AddRec's with the same loop induction variable being
2591     // multiplied together.  If so, we can fold them.
2592 
2593     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2594     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2595     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2596     //   ]]],+,...up to x=2n}.
2597     // Note that the arguments to choose() are always integers with values
2598     // known at compile time, never SCEV objects.
2599     //
2600     // The implementation avoids pointless extra computations when the two
2601     // addrec's are of different length (mathematically, it's equivalent to
2602     // an infinite stream of zeros on the right).
2603     bool OpsModified = false;
2604     for (unsigned OtherIdx = Idx+1;
2605          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2606          ++OtherIdx) {
2607       const SCEVAddRecExpr *OtherAddRec =
2608         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2609       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2610         continue;
2611 
2612       bool Overflow = false;
2613       Type *Ty = AddRec->getType();
2614       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2615       SmallVector<const SCEV*, 7> AddRecOps;
2616       for (int x = 0, xe = AddRec->getNumOperands() +
2617              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2618         const SCEV *Term = getZero(Ty);
2619         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2620           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2621           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2622                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2623                z < ze && !Overflow; ++z) {
2624             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2625             uint64_t Coeff;
2626             if (LargerThan64Bits)
2627               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2628             else
2629               Coeff = Coeff1*Coeff2;
2630             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2631             const SCEV *Term1 = AddRec->getOperand(y-z);
2632             const SCEV *Term2 = OtherAddRec->getOperand(z);
2633             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2634           }
2635         }
2636         AddRecOps.push_back(Term);
2637       }
2638       if (!Overflow) {
2639         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2640                                               SCEV::FlagAnyWrap);
2641         if (Ops.size() == 2) return NewAddRec;
2642         Ops[Idx] = NewAddRec;
2643         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2644         OpsModified = true;
2645         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2646         if (!AddRec)
2647           break;
2648       }
2649     }
2650     if (OpsModified)
2651       return getMulExpr(Ops);
2652 
2653     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2654     // next one.
2655   }
2656 
2657   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2658   // already have one, otherwise create a new one.
2659   FoldingSetNodeID ID;
2660   ID.AddInteger(scMulExpr);
2661   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2662     ID.AddPointer(Ops[i]);
2663   void *IP = nullptr;
2664   SCEVMulExpr *S =
2665     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2666   if (!S) {
2667     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2668     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2669     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2670                                         O, Ops.size());
2671     UniqueSCEVs.InsertNode(S, IP);
2672   }
2673   S->setNoWrapFlags(Flags);
2674   return S;
2675 }
2676 
2677 /// Get a canonical unsigned division expression, or something simpler if
2678 /// possible.
2679 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2680                                          const SCEV *RHS) {
2681   assert(getEffectiveSCEVType(LHS->getType()) ==
2682          getEffectiveSCEVType(RHS->getType()) &&
2683          "SCEVUDivExpr operand types don't match!");
2684 
2685   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2686     if (RHSC->getValue()->equalsInt(1))
2687       return LHS;                               // X udiv 1 --> x
2688     // If the denominator is zero, the result of the udiv is undefined. Don't
2689     // try to analyze it, because the resolution chosen here may differ from
2690     // the resolution chosen in other parts of the compiler.
2691     if (!RHSC->getValue()->isZero()) {
2692       // Determine if the division can be folded into the operands of
2693       // its operands.
2694       // TODO: Generalize this to non-constants by using known-bits information.
2695       Type *Ty = LHS->getType();
2696       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2697       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2698       // For non-power-of-two values, effectively round the value up to the
2699       // nearest power of two.
2700       if (!RHSC->getAPInt().isPowerOf2())
2701         ++MaxShiftAmt;
2702       IntegerType *ExtTy =
2703         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2704       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2705         if (const SCEVConstant *Step =
2706             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2707           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2708           const APInt &StepInt = Step->getAPInt();
2709           const APInt &DivInt = RHSC->getAPInt();
2710           if (!StepInt.urem(DivInt) &&
2711               getZeroExtendExpr(AR, ExtTy) ==
2712               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2713                             getZeroExtendExpr(Step, ExtTy),
2714                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2715             SmallVector<const SCEV *, 4> Operands;
2716             for (const SCEV *Op : AR->operands())
2717               Operands.push_back(getUDivExpr(Op, RHS));
2718             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2719           }
2720           /// Get a canonical UDivExpr for a recurrence.
2721           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2722           // We can currently only fold X%N if X is constant.
2723           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2724           if (StartC && !DivInt.urem(StepInt) &&
2725               getZeroExtendExpr(AR, ExtTy) ==
2726               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2727                             getZeroExtendExpr(Step, ExtTy),
2728                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2729             const APInt &StartInt = StartC->getAPInt();
2730             const APInt &StartRem = StartInt.urem(StepInt);
2731             if (StartRem != 0)
2732               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2733                                   AR->getLoop(), SCEV::FlagNW);
2734           }
2735         }
2736       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2737       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2738         SmallVector<const SCEV *, 4> Operands;
2739         for (const SCEV *Op : M->operands())
2740           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2741         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2742           // Find an operand that's safely divisible.
2743           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2744             const SCEV *Op = M->getOperand(i);
2745             const SCEV *Div = getUDivExpr(Op, RHSC);
2746             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2747               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2748                                                       M->op_end());
2749               Operands[i] = Div;
2750               return getMulExpr(Operands);
2751             }
2752           }
2753       }
2754       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2755       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2756         SmallVector<const SCEV *, 4> Operands;
2757         for (const SCEV *Op : A->operands())
2758           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2759         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2760           Operands.clear();
2761           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2762             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2763             if (isa<SCEVUDivExpr>(Op) ||
2764                 getMulExpr(Op, RHS) != A->getOperand(i))
2765               break;
2766             Operands.push_back(Op);
2767           }
2768           if (Operands.size() == A->getNumOperands())
2769             return getAddExpr(Operands);
2770         }
2771       }
2772 
2773       // Fold if both operands are constant.
2774       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2775         Constant *LHSCV = LHSC->getValue();
2776         Constant *RHSCV = RHSC->getValue();
2777         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2778                                                                    RHSCV)));
2779       }
2780     }
2781   }
2782 
2783   FoldingSetNodeID ID;
2784   ID.AddInteger(scUDivExpr);
2785   ID.AddPointer(LHS);
2786   ID.AddPointer(RHS);
2787   void *IP = nullptr;
2788   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2789   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2790                                              LHS, RHS);
2791   UniqueSCEVs.InsertNode(S, IP);
2792   return S;
2793 }
2794 
2795 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2796   APInt A = C1->getAPInt().abs();
2797   APInt B = C2->getAPInt().abs();
2798   uint32_t ABW = A.getBitWidth();
2799   uint32_t BBW = B.getBitWidth();
2800 
2801   if (ABW > BBW)
2802     B = B.zext(ABW);
2803   else if (ABW < BBW)
2804     A = A.zext(BBW);
2805 
2806   return APIntOps::GreatestCommonDivisor(A, B);
2807 }
2808 
2809 /// Get a canonical unsigned division expression, or something simpler if
2810 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2811 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2812 /// it's not exact because the udiv may be clearing bits.
2813 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2814                                               const SCEV *RHS) {
2815   // TODO: we could try to find factors in all sorts of things, but for now we
2816   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2817   // end of this file for inspiration.
2818 
2819   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2820   if (!Mul)
2821     return getUDivExpr(LHS, RHS);
2822 
2823   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2824     // If the mulexpr multiplies by a constant, then that constant must be the
2825     // first element of the mulexpr.
2826     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2827       if (LHSCst == RHSCst) {
2828         SmallVector<const SCEV *, 2> Operands;
2829         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2830         return getMulExpr(Operands);
2831       }
2832 
2833       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2834       // that there's a factor provided by one of the other terms. We need to
2835       // check.
2836       APInt Factor = gcd(LHSCst, RHSCst);
2837       if (!Factor.isIntN(1)) {
2838         LHSCst =
2839             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2840         RHSCst =
2841             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
2842         SmallVector<const SCEV *, 2> Operands;
2843         Operands.push_back(LHSCst);
2844         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2845         LHS = getMulExpr(Operands);
2846         RHS = RHSCst;
2847         Mul = dyn_cast<SCEVMulExpr>(LHS);
2848         if (!Mul)
2849           return getUDivExactExpr(LHS, RHS);
2850       }
2851     }
2852   }
2853 
2854   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2855     if (Mul->getOperand(i) == RHS) {
2856       SmallVector<const SCEV *, 2> Operands;
2857       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2858       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2859       return getMulExpr(Operands);
2860     }
2861   }
2862 
2863   return getUDivExpr(LHS, RHS);
2864 }
2865 
2866 /// Get an add recurrence expression for the specified loop.  Simplify the
2867 /// expression as much as possible.
2868 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2869                                            const Loop *L,
2870                                            SCEV::NoWrapFlags Flags) {
2871   SmallVector<const SCEV *, 4> Operands;
2872   Operands.push_back(Start);
2873   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2874     if (StepChrec->getLoop() == L) {
2875       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2876       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2877     }
2878 
2879   Operands.push_back(Step);
2880   return getAddRecExpr(Operands, L, Flags);
2881 }
2882 
2883 /// Get an add recurrence expression for the specified loop.  Simplify the
2884 /// expression as much as possible.
2885 const SCEV *
2886 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2887                                const Loop *L, SCEV::NoWrapFlags Flags) {
2888   if (Operands.size() == 1) return Operands[0];
2889 #ifndef NDEBUG
2890   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2891   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2892     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2893            "SCEVAddRecExpr operand types don't match!");
2894   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2895     assert(isLoopInvariant(Operands[i], L) &&
2896            "SCEVAddRecExpr operand is not loop-invariant!");
2897 #endif
2898 
2899   if (Operands.back()->isZero()) {
2900     Operands.pop_back();
2901     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2902   }
2903 
2904   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2905   // use that information to infer NUW and NSW flags. However, computing a
2906   // BE count requires calling getAddRecExpr, so we may not yet have a
2907   // meaningful BE count at this point (and if we don't, we'd be stuck
2908   // with a SCEVCouldNotCompute as the cached BE count).
2909 
2910   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2911 
2912   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2913   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2914     const Loop *NestedLoop = NestedAR->getLoop();
2915     if (L->contains(NestedLoop)
2916             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2917             : (!NestedLoop->contains(L) &&
2918                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
2919       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2920                                                   NestedAR->op_end());
2921       Operands[0] = NestedAR->getStart();
2922       // AddRecs require their operands be loop-invariant with respect to their
2923       // loops. Don't perform this transformation if it would break this
2924       // requirement.
2925       bool AllInvariant = all_of(
2926           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
2927 
2928       if (AllInvariant) {
2929         // Create a recurrence for the outer loop with the same step size.
2930         //
2931         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2932         // inner recurrence has the same property.
2933         SCEV::NoWrapFlags OuterFlags =
2934           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2935 
2936         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2937         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2938           return isLoopInvariant(Op, NestedLoop);
2939         });
2940 
2941         if (AllInvariant) {
2942           // Ok, both add recurrences are valid after the transformation.
2943           //
2944           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2945           // the outer recurrence has the same property.
2946           SCEV::NoWrapFlags InnerFlags =
2947             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2948           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2949         }
2950       }
2951       // Reset Operands to its original state.
2952       Operands[0] = NestedAR;
2953     }
2954   }
2955 
2956   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
2957   // already have one, otherwise create a new one.
2958   FoldingSetNodeID ID;
2959   ID.AddInteger(scAddRecExpr);
2960   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2961     ID.AddPointer(Operands[i]);
2962   ID.AddPointer(L);
2963   void *IP = nullptr;
2964   SCEVAddRecExpr *S =
2965     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2966   if (!S) {
2967     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2968     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2969     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2970                                            O, Operands.size(), L);
2971     UniqueSCEVs.InsertNode(S, IP);
2972   }
2973   S->setNoWrapFlags(Flags);
2974   return S;
2975 }
2976 
2977 const SCEV *
2978 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2979                             const SmallVectorImpl<const SCEV *> &IndexExprs,
2980                             bool InBounds) {
2981   // getSCEV(Base)->getType() has the same address space as Base->getType()
2982   // because SCEV::getType() preserves the address space.
2983   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2984   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2985   // instruction to its SCEV, because the Instruction may be guarded by control
2986   // flow and the no-overflow bits may not be valid for the expression in any
2987   // context. This can be fixed similarly to how these flags are handled for
2988   // adds.
2989   SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2990 
2991   const SCEV *TotalOffset = getZero(IntPtrTy);
2992   // The address space is unimportant. The first thing we do on CurTy is getting
2993   // its element type.
2994   Type *CurTy = PointerType::getUnqual(PointeeType);
2995   for (const SCEV *IndexExpr : IndexExprs) {
2996     // Compute the (potentially symbolic) offset in bytes for this index.
2997     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2998       // For a struct, add the member offset.
2999       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3000       unsigned FieldNo = Index->getZExtValue();
3001       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3002 
3003       // Add the field offset to the running total offset.
3004       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3005 
3006       // Update CurTy to the type of the field at Index.
3007       CurTy = STy->getTypeAtIndex(Index);
3008     } else {
3009       // Update CurTy to its element type.
3010       CurTy = cast<SequentialType>(CurTy)->getElementType();
3011       // For an array, add the element offset, explicitly scaled.
3012       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3013       // Getelementptr indices are signed.
3014       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3015 
3016       // Multiply the index by the element size to compute the element offset.
3017       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3018 
3019       // Add the element offset to the running total offset.
3020       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3021     }
3022   }
3023 
3024   // Add the total offset from all the GEP indices to the base.
3025   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3026 }
3027 
3028 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3029                                          const SCEV *RHS) {
3030   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3031   return getSMaxExpr(Ops);
3032 }
3033 
3034 const SCEV *
3035 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3036   assert(!Ops.empty() && "Cannot get empty smax!");
3037   if (Ops.size() == 1) return Ops[0];
3038 #ifndef NDEBUG
3039   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3040   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3041     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3042            "SCEVSMaxExpr operand types don't match!");
3043 #endif
3044 
3045   // Sort by complexity, this groups all similar expression types together.
3046   GroupByComplexity(Ops, &LI);
3047 
3048   // If there are any constants, fold them together.
3049   unsigned Idx = 0;
3050   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3051     ++Idx;
3052     assert(Idx < Ops.size());
3053     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3054       // We found two constants, fold them together!
3055       ConstantInt *Fold = ConstantInt::get(
3056           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3057       Ops[0] = getConstant(Fold);
3058       Ops.erase(Ops.begin()+1);  // Erase the folded element
3059       if (Ops.size() == 1) return Ops[0];
3060       LHSC = cast<SCEVConstant>(Ops[0]);
3061     }
3062 
3063     // If we are left with a constant minimum-int, strip it off.
3064     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3065       Ops.erase(Ops.begin());
3066       --Idx;
3067     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3068       // If we have an smax with a constant maximum-int, it will always be
3069       // maximum-int.
3070       return Ops[0];
3071     }
3072 
3073     if (Ops.size() == 1) return Ops[0];
3074   }
3075 
3076   // Find the first SMax
3077   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3078     ++Idx;
3079 
3080   // Check to see if one of the operands is an SMax. If so, expand its operands
3081   // onto our operand list, and recurse to simplify.
3082   if (Idx < Ops.size()) {
3083     bool DeletedSMax = false;
3084     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3085       Ops.erase(Ops.begin()+Idx);
3086       Ops.append(SMax->op_begin(), SMax->op_end());
3087       DeletedSMax = true;
3088     }
3089 
3090     if (DeletedSMax)
3091       return getSMaxExpr(Ops);
3092   }
3093 
3094   // Okay, check to see if the same value occurs in the operand list twice.  If
3095   // so, delete one.  Since we sorted the list, these values are required to
3096   // be adjacent.
3097   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3098     //  X smax Y smax Y  -->  X smax Y
3099     //  X smax Y         -->  X, if X is always greater than Y
3100     if (Ops[i] == Ops[i+1] ||
3101         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3102       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3103       --i; --e;
3104     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3105       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3106       --i; --e;
3107     }
3108 
3109   if (Ops.size() == 1) return Ops[0];
3110 
3111   assert(!Ops.empty() && "Reduced smax down to nothing!");
3112 
3113   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3114   // already have one, otherwise create a new one.
3115   FoldingSetNodeID ID;
3116   ID.AddInteger(scSMaxExpr);
3117   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3118     ID.AddPointer(Ops[i]);
3119   void *IP = nullptr;
3120   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3121   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3122   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3123   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3124                                              O, Ops.size());
3125   UniqueSCEVs.InsertNode(S, IP);
3126   return S;
3127 }
3128 
3129 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3130                                          const SCEV *RHS) {
3131   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3132   return getUMaxExpr(Ops);
3133 }
3134 
3135 const SCEV *
3136 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3137   assert(!Ops.empty() && "Cannot get empty umax!");
3138   if (Ops.size() == 1) return Ops[0];
3139 #ifndef NDEBUG
3140   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3141   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3142     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3143            "SCEVUMaxExpr operand types don't match!");
3144 #endif
3145 
3146   // Sort by complexity, this groups all similar expression types together.
3147   GroupByComplexity(Ops, &LI);
3148 
3149   // If there are any constants, fold them together.
3150   unsigned Idx = 0;
3151   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3152     ++Idx;
3153     assert(Idx < Ops.size());
3154     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3155       // We found two constants, fold them together!
3156       ConstantInt *Fold = ConstantInt::get(
3157           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3158       Ops[0] = getConstant(Fold);
3159       Ops.erase(Ops.begin()+1);  // Erase the folded element
3160       if (Ops.size() == 1) return Ops[0];
3161       LHSC = cast<SCEVConstant>(Ops[0]);
3162     }
3163 
3164     // If we are left with a constant minimum-int, strip it off.
3165     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3166       Ops.erase(Ops.begin());
3167       --Idx;
3168     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3169       // If we have an umax with a constant maximum-int, it will always be
3170       // maximum-int.
3171       return Ops[0];
3172     }
3173 
3174     if (Ops.size() == 1) return Ops[0];
3175   }
3176 
3177   // Find the first UMax
3178   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3179     ++Idx;
3180 
3181   // Check to see if one of the operands is a UMax. If so, expand its operands
3182   // onto our operand list, and recurse to simplify.
3183   if (Idx < Ops.size()) {
3184     bool DeletedUMax = false;
3185     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3186       Ops.erase(Ops.begin()+Idx);
3187       Ops.append(UMax->op_begin(), UMax->op_end());
3188       DeletedUMax = true;
3189     }
3190 
3191     if (DeletedUMax)
3192       return getUMaxExpr(Ops);
3193   }
3194 
3195   // Okay, check to see if the same value occurs in the operand list twice.  If
3196   // so, delete one.  Since we sorted the list, these values are required to
3197   // be adjacent.
3198   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3199     //  X umax Y umax Y  -->  X umax Y
3200     //  X umax Y         -->  X, if X is always greater than Y
3201     if (Ops[i] == Ops[i+1] ||
3202         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3203       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3204       --i; --e;
3205     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3206       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3207       --i; --e;
3208     }
3209 
3210   if (Ops.size() == 1) return Ops[0];
3211 
3212   assert(!Ops.empty() && "Reduced umax down to nothing!");
3213 
3214   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3215   // already have one, otherwise create a new one.
3216   FoldingSetNodeID ID;
3217   ID.AddInteger(scUMaxExpr);
3218   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3219     ID.AddPointer(Ops[i]);
3220   void *IP = nullptr;
3221   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3222   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3223   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3224   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3225                                              O, Ops.size());
3226   UniqueSCEVs.InsertNode(S, IP);
3227   return S;
3228 }
3229 
3230 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3231                                          const SCEV *RHS) {
3232   // ~smax(~x, ~y) == smin(x, y).
3233   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3234 }
3235 
3236 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3237                                          const SCEV *RHS) {
3238   // ~umax(~x, ~y) == umin(x, y)
3239   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3240 }
3241 
3242 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3243   // We can bypass creating a target-independent
3244   // constant expression and then folding it back into a ConstantInt.
3245   // This is just a compile-time optimization.
3246   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3247 }
3248 
3249 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3250                                              StructType *STy,
3251                                              unsigned FieldNo) {
3252   // We can bypass creating a target-independent
3253   // constant expression and then folding it back into a ConstantInt.
3254   // This is just a compile-time optimization.
3255   return getConstant(
3256       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3257 }
3258 
3259 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3260   // Don't attempt to do anything other than create a SCEVUnknown object
3261   // here.  createSCEV only calls getUnknown after checking for all other
3262   // interesting possibilities, and any other code that calls getUnknown
3263   // is doing so in order to hide a value from SCEV canonicalization.
3264 
3265   FoldingSetNodeID ID;
3266   ID.AddInteger(scUnknown);
3267   ID.AddPointer(V);
3268   void *IP = nullptr;
3269   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3270     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3271            "Stale SCEVUnknown in uniquing map!");
3272     return S;
3273   }
3274   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3275                                             FirstUnknown);
3276   FirstUnknown = cast<SCEVUnknown>(S);
3277   UniqueSCEVs.InsertNode(S, IP);
3278   return S;
3279 }
3280 
3281 //===----------------------------------------------------------------------===//
3282 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3283 //
3284 
3285 /// Test if values of the given type are analyzable within the SCEV
3286 /// framework. This primarily includes integer types, and it can optionally
3287 /// include pointer types if the ScalarEvolution class has access to
3288 /// target-specific information.
3289 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3290   // Integers and pointers are always SCEVable.
3291   return Ty->isIntegerTy() || Ty->isPointerTy();
3292 }
3293 
3294 /// Return the size in bits of the specified type, for which isSCEVable must
3295 /// return true.
3296 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3297   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3298   return getDataLayout().getTypeSizeInBits(Ty);
3299 }
3300 
3301 /// Return a type with the same bitwidth as the given type and which represents
3302 /// how SCEV will treat the given type, for which isSCEVable must return
3303 /// true. For pointer types, this is the pointer-sized integer type.
3304 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3305   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3306 
3307   if (Ty->isIntegerTy())
3308     return Ty;
3309 
3310   // The only other support type is pointer.
3311   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3312   return getDataLayout().getIntPtrType(Ty);
3313 }
3314 
3315 const SCEV *ScalarEvolution::getCouldNotCompute() {
3316   return CouldNotCompute.get();
3317 }
3318 
3319 
3320 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3321   // Helper class working with SCEVTraversal to figure out if a SCEV contains
3322   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3323   // is set iff if find such SCEVUnknown.
3324   //
3325   struct FindInvalidSCEVUnknown {
3326     bool FindOne;
3327     FindInvalidSCEVUnknown() { FindOne = false; }
3328     bool follow(const SCEV *S) {
3329       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3330       case scConstant:
3331         return false;
3332       case scUnknown:
3333         if (!cast<SCEVUnknown>(S)->getValue())
3334           FindOne = true;
3335         return false;
3336       default:
3337         return true;
3338       }
3339     }
3340     bool isDone() const { return FindOne; }
3341   };
3342 
3343   FindInvalidSCEVUnknown F;
3344   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3345   ST.visitAll(S);
3346 
3347   return !F.FindOne;
3348 }
3349 
3350 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3351   // Helper class working with SCEVTraversal to figure out if a SCEV contains a
3352   // sub SCEV of scAddRecExpr type.  FindInvalidSCEVUnknown::FoundOne is set iff
3353   // if such sub scAddRecExpr type SCEV is found.
3354   struct FindAddRecurrence {
3355     bool FoundOne;
3356     FindAddRecurrence() : FoundOne(false) {}
3357 
3358     bool follow(const SCEV *S) {
3359       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3360       case scAddRecExpr:
3361         FoundOne = true;
3362       case scConstant:
3363       case scUnknown:
3364       case scCouldNotCompute:
3365         return false;
3366       default:
3367         return true;
3368       }
3369     }
3370     bool isDone() const { return FoundOne; }
3371   };
3372 
3373   HasRecMapType::iterator I = HasRecMap.find(S);
3374   if (I != HasRecMap.end())
3375     return I->second;
3376 
3377   FindAddRecurrence F;
3378   SCEVTraversal<FindAddRecurrence> ST(F);
3379   ST.visitAll(S);
3380   HasRecMap.insert({S, F.FoundOne});
3381   return F.FoundOne;
3382 }
3383 
3384 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3385 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3386 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3387 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3388   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3389   if (!Add)
3390     return {S, nullptr};
3391 
3392   if (Add->getNumOperands() != 2)
3393     return {S, nullptr};
3394 
3395   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3396   if (!ConstOp)
3397     return {S, nullptr};
3398 
3399   return {Add->getOperand(1), ConstOp->getValue()};
3400 }
3401 
3402 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3403 /// by the value and offset from any ValueOffsetPair in the set.
3404 SetVector<ScalarEvolution::ValueOffsetPair> *
3405 ScalarEvolution::getSCEVValues(const SCEV *S) {
3406   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3407   if (SI == ExprValueMap.end())
3408     return nullptr;
3409 #ifndef NDEBUG
3410   if (VerifySCEVMap) {
3411     // Check there is no dangling Value in the set returned.
3412     for (const auto &VE : SI->second)
3413       assert(ValueExprMap.count(VE.first));
3414   }
3415 #endif
3416   return &SI->second;
3417 }
3418 
3419 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3420 /// cannot be used separately. eraseValueFromMap should be used to remove
3421 /// V from ValueExprMap and ExprValueMap at the same time.
3422 void ScalarEvolution::eraseValueFromMap(Value *V) {
3423   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3424   if (I != ValueExprMap.end()) {
3425     const SCEV *S = I->second;
3426     // Remove {V, 0} from the set of ExprValueMap[S]
3427     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3428       SV->remove({V, nullptr});
3429 
3430     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3431     const SCEV *Stripped;
3432     ConstantInt *Offset;
3433     std::tie(Stripped, Offset) = splitAddExpr(S);
3434     if (Offset != nullptr) {
3435       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3436         SV->remove({V, Offset});
3437     }
3438     ValueExprMap.erase(V);
3439   }
3440 }
3441 
3442 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3443 /// create a new one.
3444 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3445   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3446 
3447   const SCEV *S = getExistingSCEV(V);
3448   if (S == nullptr) {
3449     S = createSCEV(V);
3450     // During PHI resolution, it is possible to create two SCEVs for the same
3451     // V, so it is needed to double check whether V->S is inserted into
3452     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3453     std::pair<ValueExprMapType::iterator, bool> Pair =
3454         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3455     if (Pair.second) {
3456       ExprValueMap[S].insert({V, nullptr});
3457 
3458       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3459       // ExprValueMap.
3460       const SCEV *Stripped = S;
3461       ConstantInt *Offset = nullptr;
3462       std::tie(Stripped, Offset) = splitAddExpr(S);
3463       // If stripped is SCEVUnknown, don't bother to save
3464       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3465       // increase the complexity of the expansion code.
3466       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3467       // because it may generate add/sub instead of GEP in SCEV expansion.
3468       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3469           !isa<GetElementPtrInst>(V))
3470         ExprValueMap[Stripped].insert({V, Offset});
3471     }
3472   }
3473   return S;
3474 }
3475 
3476 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3477   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3478 
3479   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3480   if (I != ValueExprMap.end()) {
3481     const SCEV *S = I->second;
3482     if (checkValidity(S))
3483       return S;
3484     eraseValueFromMap(V);
3485     forgetMemoizedResults(S);
3486   }
3487   return nullptr;
3488 }
3489 
3490 /// Return a SCEV corresponding to -V = -1*V
3491 ///
3492 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3493                                              SCEV::NoWrapFlags Flags) {
3494   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3495     return getConstant(
3496                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3497 
3498   Type *Ty = V->getType();
3499   Ty = getEffectiveSCEVType(Ty);
3500   return getMulExpr(
3501       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3502 }
3503 
3504 /// Return a SCEV corresponding to ~V = -1-V
3505 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3506   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3507     return getConstant(
3508                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3509 
3510   Type *Ty = V->getType();
3511   Ty = getEffectiveSCEVType(Ty);
3512   const SCEV *AllOnes =
3513                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3514   return getMinusSCEV(AllOnes, V);
3515 }
3516 
3517 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3518                                           SCEV::NoWrapFlags Flags) {
3519   // Fast path: X - X --> 0.
3520   if (LHS == RHS)
3521     return getZero(LHS->getType());
3522 
3523   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3524   // makes it so that we cannot make much use of NUW.
3525   auto AddFlags = SCEV::FlagAnyWrap;
3526   const bool RHSIsNotMinSigned =
3527       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3528   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3529     // Let M be the minimum representable signed value. Then (-1)*RHS
3530     // signed-wraps if and only if RHS is M. That can happen even for
3531     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3532     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3533     // (-1)*RHS, we need to prove that RHS != M.
3534     //
3535     // If LHS is non-negative and we know that LHS - RHS does not
3536     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3537     // either by proving that RHS > M or that LHS >= 0.
3538     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3539       AddFlags = SCEV::FlagNSW;
3540     }
3541   }
3542 
3543   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3544   // RHS is NSW and LHS >= 0.
3545   //
3546   // The difficulty here is that the NSW flag may have been proven
3547   // relative to a loop that is to be found in a recurrence in LHS and
3548   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3549   // larger scope than intended.
3550   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3551 
3552   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3553 }
3554 
3555 const SCEV *
3556 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3557   Type *SrcTy = V->getType();
3558   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3559          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3560          "Cannot truncate or zero extend with non-integer arguments!");
3561   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3562     return V;  // No conversion
3563   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3564     return getTruncateExpr(V, Ty);
3565   return getZeroExtendExpr(V, Ty);
3566 }
3567 
3568 const SCEV *
3569 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3570                                          Type *Ty) {
3571   Type *SrcTy = V->getType();
3572   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3573          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3574          "Cannot truncate or zero extend with non-integer arguments!");
3575   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3576     return V;  // No conversion
3577   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3578     return getTruncateExpr(V, Ty);
3579   return getSignExtendExpr(V, Ty);
3580 }
3581 
3582 const SCEV *
3583 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3584   Type *SrcTy = V->getType();
3585   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3586          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3587          "Cannot noop or zero extend with non-integer arguments!");
3588   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3589          "getNoopOrZeroExtend cannot truncate!");
3590   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3591     return V;  // No conversion
3592   return getZeroExtendExpr(V, Ty);
3593 }
3594 
3595 const SCEV *
3596 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3597   Type *SrcTy = V->getType();
3598   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3599          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3600          "Cannot noop or sign extend with non-integer arguments!");
3601   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3602          "getNoopOrSignExtend cannot truncate!");
3603   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3604     return V;  // No conversion
3605   return getSignExtendExpr(V, Ty);
3606 }
3607 
3608 const SCEV *
3609 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3610   Type *SrcTy = V->getType();
3611   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3612          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3613          "Cannot noop or any extend with non-integer arguments!");
3614   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3615          "getNoopOrAnyExtend cannot truncate!");
3616   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3617     return V;  // No conversion
3618   return getAnyExtendExpr(V, Ty);
3619 }
3620 
3621 const SCEV *
3622 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3623   Type *SrcTy = V->getType();
3624   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3625          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3626          "Cannot truncate or noop with non-integer arguments!");
3627   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3628          "getTruncateOrNoop cannot extend!");
3629   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3630     return V;  // No conversion
3631   return getTruncateExpr(V, Ty);
3632 }
3633 
3634 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3635                                                         const SCEV *RHS) {
3636   const SCEV *PromotedLHS = LHS;
3637   const SCEV *PromotedRHS = RHS;
3638 
3639   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3640     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3641   else
3642     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3643 
3644   return getUMaxExpr(PromotedLHS, PromotedRHS);
3645 }
3646 
3647 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3648                                                         const SCEV *RHS) {
3649   const SCEV *PromotedLHS = LHS;
3650   const SCEV *PromotedRHS = RHS;
3651 
3652   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3653     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3654   else
3655     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3656 
3657   return getUMinExpr(PromotedLHS, PromotedRHS);
3658 }
3659 
3660 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3661   // A pointer operand may evaluate to a nonpointer expression, such as null.
3662   if (!V->getType()->isPointerTy())
3663     return V;
3664 
3665   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3666     return getPointerBase(Cast->getOperand());
3667   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3668     const SCEV *PtrOp = nullptr;
3669     for (const SCEV *NAryOp : NAry->operands()) {
3670       if (NAryOp->getType()->isPointerTy()) {
3671         // Cannot find the base of an expression with multiple pointer operands.
3672         if (PtrOp)
3673           return V;
3674         PtrOp = NAryOp;
3675       }
3676     }
3677     if (!PtrOp)
3678       return V;
3679     return getPointerBase(PtrOp);
3680   }
3681   return V;
3682 }
3683 
3684 /// Push users of the given Instruction onto the given Worklist.
3685 static void
3686 PushDefUseChildren(Instruction *I,
3687                    SmallVectorImpl<Instruction *> &Worklist) {
3688   // Push the def-use children onto the Worklist stack.
3689   for (User *U : I->users())
3690     Worklist.push_back(cast<Instruction>(U));
3691 }
3692 
3693 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3694   SmallVector<Instruction *, 16> Worklist;
3695   PushDefUseChildren(PN, Worklist);
3696 
3697   SmallPtrSet<Instruction *, 8> Visited;
3698   Visited.insert(PN);
3699   while (!Worklist.empty()) {
3700     Instruction *I = Worklist.pop_back_val();
3701     if (!Visited.insert(I).second)
3702       continue;
3703 
3704     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3705     if (It != ValueExprMap.end()) {
3706       const SCEV *Old = It->second;
3707 
3708       // Short-circuit the def-use traversal if the symbolic name
3709       // ceases to appear in expressions.
3710       if (Old != SymName && !hasOperand(Old, SymName))
3711         continue;
3712 
3713       // SCEVUnknown for a PHI either means that it has an unrecognized
3714       // structure, it's a PHI that's in the progress of being computed
3715       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3716       // additional loop trip count information isn't going to change anything.
3717       // In the second case, createNodeForPHI will perform the necessary
3718       // updates on its own when it gets to that point. In the third, we do
3719       // want to forget the SCEVUnknown.
3720       if (!isa<PHINode>(I) ||
3721           !isa<SCEVUnknown>(Old) ||
3722           (I != PN && Old == SymName)) {
3723         eraseValueFromMap(It->first);
3724         forgetMemoizedResults(Old);
3725       }
3726     }
3727 
3728     PushDefUseChildren(I, Worklist);
3729   }
3730 }
3731 
3732 namespace {
3733 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3734 public:
3735   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3736                              ScalarEvolution &SE) {
3737     SCEVInitRewriter Rewriter(L, SE);
3738     const SCEV *Result = Rewriter.visit(S);
3739     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3740   }
3741 
3742   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3743       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3744 
3745   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3746     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3747       Valid = false;
3748     return Expr;
3749   }
3750 
3751   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3752     // Only allow AddRecExprs for this loop.
3753     if (Expr->getLoop() == L)
3754       return Expr->getStart();
3755     Valid = false;
3756     return Expr;
3757   }
3758 
3759   bool isValid() { return Valid; }
3760 
3761 private:
3762   const Loop *L;
3763   bool Valid;
3764 };
3765 
3766 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3767 public:
3768   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3769                              ScalarEvolution &SE) {
3770     SCEVShiftRewriter Rewriter(L, SE);
3771     const SCEV *Result = Rewriter.visit(S);
3772     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3773   }
3774 
3775   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3776       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3777 
3778   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3779     // Only allow AddRecExprs for this loop.
3780     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3781       Valid = false;
3782     return Expr;
3783   }
3784 
3785   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3786     if (Expr->getLoop() == L && Expr->isAffine())
3787       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3788     Valid = false;
3789     return Expr;
3790   }
3791   bool isValid() { return Valid; }
3792 
3793 private:
3794   const Loop *L;
3795   bool Valid;
3796 };
3797 } // end anonymous namespace
3798 
3799 SCEV::NoWrapFlags
3800 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3801   if (!AR->isAffine())
3802     return SCEV::FlagAnyWrap;
3803 
3804   typedef OverflowingBinaryOperator OBO;
3805   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3806 
3807   if (!AR->hasNoSignedWrap()) {
3808     ConstantRange AddRecRange = getSignedRange(AR);
3809     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3810 
3811     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3812         Instruction::Add, IncRange, OBO::NoSignedWrap);
3813     if (NSWRegion.contains(AddRecRange))
3814       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3815   }
3816 
3817   if (!AR->hasNoUnsignedWrap()) {
3818     ConstantRange AddRecRange = getUnsignedRange(AR);
3819     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3820 
3821     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3822         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3823     if (NUWRegion.contains(AddRecRange))
3824       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3825   }
3826 
3827   return Result;
3828 }
3829 
3830 namespace {
3831 /// Represents an abstract binary operation.  This may exist as a
3832 /// normal instruction or constant expression, or may have been
3833 /// derived from an expression tree.
3834 struct BinaryOp {
3835   unsigned Opcode;
3836   Value *LHS;
3837   Value *RHS;
3838   bool IsNSW;
3839   bool IsNUW;
3840 
3841   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3842   /// constant expression.
3843   Operator *Op;
3844 
3845   explicit BinaryOp(Operator *Op)
3846       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3847         IsNSW(false), IsNUW(false), Op(Op) {
3848     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3849       IsNSW = OBO->hasNoSignedWrap();
3850       IsNUW = OBO->hasNoUnsignedWrap();
3851     }
3852   }
3853 
3854   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3855                     bool IsNUW = false)
3856       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3857         Op(nullptr) {}
3858 };
3859 }
3860 
3861 
3862 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3863 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3864   auto *Op = dyn_cast<Operator>(V);
3865   if (!Op)
3866     return None;
3867 
3868   // Implementation detail: all the cleverness here should happen without
3869   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3870   // SCEV expressions when possible, and we should not break that.
3871 
3872   switch (Op->getOpcode()) {
3873   case Instruction::Add:
3874   case Instruction::Sub:
3875   case Instruction::Mul:
3876   case Instruction::UDiv:
3877   case Instruction::And:
3878   case Instruction::Or:
3879   case Instruction::AShr:
3880   case Instruction::Shl:
3881     return BinaryOp(Op);
3882 
3883   case Instruction::Xor:
3884     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3885       // If the RHS of the xor is a signbit, then this is just an add.
3886       // Instcombine turns add of signbit into xor as a strength reduction step.
3887       if (RHSC->getValue().isSignBit())
3888         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3889     return BinaryOp(Op);
3890 
3891   case Instruction::LShr:
3892     // Turn logical shift right of a constant into a unsigned divide.
3893     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3894       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3895 
3896       // If the shift count is not less than the bitwidth, the result of
3897       // the shift is undefined. Don't try to analyze it, because the
3898       // resolution chosen here may differ from the resolution chosen in
3899       // other parts of the compiler.
3900       if (SA->getValue().ult(BitWidth)) {
3901         Constant *X =
3902             ConstantInt::get(SA->getContext(),
3903                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3904         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3905       }
3906     }
3907     return BinaryOp(Op);
3908 
3909   case Instruction::ExtractValue: {
3910     auto *EVI = cast<ExtractValueInst>(Op);
3911     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3912       break;
3913 
3914     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3915     if (!CI)
3916       break;
3917 
3918     if (auto *F = CI->getCalledFunction())
3919       switch (F->getIntrinsicID()) {
3920       case Intrinsic::sadd_with_overflow:
3921       case Intrinsic::uadd_with_overflow: {
3922         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3923           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3924                           CI->getArgOperand(1));
3925 
3926         // Now that we know that all uses of the arithmetic-result component of
3927         // CI are guarded by the overflow check, we can go ahead and pretend
3928         // that the arithmetic is non-overflowing.
3929         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3930           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3931                           CI->getArgOperand(1), /* IsNSW = */ true,
3932                           /* IsNUW = */ false);
3933         else
3934           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3935                           CI->getArgOperand(1), /* IsNSW = */ false,
3936                           /* IsNUW*/ true);
3937       }
3938 
3939       case Intrinsic::ssub_with_overflow:
3940       case Intrinsic::usub_with_overflow:
3941         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3942                         CI->getArgOperand(1));
3943 
3944       case Intrinsic::smul_with_overflow:
3945       case Intrinsic::umul_with_overflow:
3946         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3947                         CI->getArgOperand(1));
3948       default:
3949         break;
3950       }
3951   }
3952 
3953   default:
3954     break;
3955   }
3956 
3957   return None;
3958 }
3959 
3960 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3961   const Loop *L = LI.getLoopFor(PN->getParent());
3962   if (!L || L->getHeader() != PN->getParent())
3963     return nullptr;
3964 
3965   // The loop may have multiple entrances or multiple exits; we can analyze
3966   // this phi as an addrec if it has a unique entry value and a unique
3967   // backedge value.
3968   Value *BEValueV = nullptr, *StartValueV = nullptr;
3969   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3970     Value *V = PN->getIncomingValue(i);
3971     if (L->contains(PN->getIncomingBlock(i))) {
3972       if (!BEValueV) {
3973         BEValueV = V;
3974       } else if (BEValueV != V) {
3975         BEValueV = nullptr;
3976         break;
3977       }
3978     } else if (!StartValueV) {
3979       StartValueV = V;
3980     } else if (StartValueV != V) {
3981       StartValueV = nullptr;
3982       break;
3983     }
3984   }
3985   if (BEValueV && StartValueV) {
3986     // While we are analyzing this PHI node, handle its value symbolically.
3987     const SCEV *SymbolicName = getUnknown(PN);
3988     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3989            "PHI node already processed?");
3990     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
3991 
3992     // Using this symbolic name for the PHI, analyze the value coming around
3993     // the back-edge.
3994     const SCEV *BEValue = getSCEV(BEValueV);
3995 
3996     // NOTE: If BEValue is loop invariant, we know that the PHI node just
3997     // has a special value for the first iteration of the loop.
3998 
3999     // If the value coming around the backedge is an add with the symbolic
4000     // value we just inserted, then we found a simple induction variable!
4001     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4002       // If there is a single occurrence of the symbolic value, replace it
4003       // with a recurrence.
4004       unsigned FoundIndex = Add->getNumOperands();
4005       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4006         if (Add->getOperand(i) == SymbolicName)
4007           if (FoundIndex == e) {
4008             FoundIndex = i;
4009             break;
4010           }
4011 
4012       if (FoundIndex != Add->getNumOperands()) {
4013         // Create an add with everything but the specified operand.
4014         SmallVector<const SCEV *, 8> Ops;
4015         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4016           if (i != FoundIndex)
4017             Ops.push_back(Add->getOperand(i));
4018         const SCEV *Accum = getAddExpr(Ops);
4019 
4020         // This is not a valid addrec if the step amount is varying each
4021         // loop iteration, but is not itself an addrec in this loop.
4022         if (isLoopInvariant(Accum, L) ||
4023             (isa<SCEVAddRecExpr>(Accum) &&
4024              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4025           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4026 
4027           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4028             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4029               if (BO->IsNUW)
4030                 Flags = setFlags(Flags, SCEV::FlagNUW);
4031               if (BO->IsNSW)
4032                 Flags = setFlags(Flags, SCEV::FlagNSW);
4033             }
4034           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4035             // If the increment is an inbounds GEP, then we know the address
4036             // space cannot be wrapped around. We cannot make any guarantee
4037             // about signed or unsigned overflow because pointers are
4038             // unsigned but we may have a negative index from the base
4039             // pointer. We can guarantee that no unsigned wrap occurs if the
4040             // indices form a positive value.
4041             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4042               Flags = setFlags(Flags, SCEV::FlagNW);
4043 
4044               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4045               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4046                 Flags = setFlags(Flags, SCEV::FlagNUW);
4047             }
4048 
4049             // We cannot transfer nuw and nsw flags from subtraction
4050             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4051             // for instance.
4052           }
4053 
4054           const SCEV *StartVal = getSCEV(StartValueV);
4055           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4056 
4057           // Okay, for the entire analysis of this edge we assumed the PHI
4058           // to be symbolic.  We now need to go back and purge all of the
4059           // entries for the scalars that use the symbolic expression.
4060           forgetSymbolicName(PN, SymbolicName);
4061           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4062 
4063           // We can add Flags to the post-inc expression only if we
4064           // know that it us *undefined behavior* for BEValueV to
4065           // overflow.
4066           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4067             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4068               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4069 
4070           return PHISCEV;
4071         }
4072       }
4073     } else {
4074       // Otherwise, this could be a loop like this:
4075       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4076       // In this case, j = {1,+,1}  and BEValue is j.
4077       // Because the other in-value of i (0) fits the evolution of BEValue
4078       // i really is an addrec evolution.
4079       //
4080       // We can generalize this saying that i is the shifted value of BEValue
4081       // by one iteration:
4082       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4083       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4084       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4085       if (Shifted != getCouldNotCompute() &&
4086           Start != getCouldNotCompute()) {
4087         const SCEV *StartVal = getSCEV(StartValueV);
4088         if (Start == StartVal) {
4089           // Okay, for the entire analysis of this edge we assumed the PHI
4090           // to be symbolic.  We now need to go back and purge all of the
4091           // entries for the scalars that use the symbolic expression.
4092           forgetSymbolicName(PN, SymbolicName);
4093           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4094           return Shifted;
4095         }
4096       }
4097     }
4098 
4099     // Remove the temporary PHI node SCEV that has been inserted while intending
4100     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4101     // as it will prevent later (possibly simpler) SCEV expressions to be added
4102     // to the ValueExprMap.
4103     eraseValueFromMap(PN);
4104   }
4105 
4106   return nullptr;
4107 }
4108 
4109 // Checks if the SCEV S is available at BB.  S is considered available at BB
4110 // if S can be materialized at BB without introducing a fault.
4111 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4112                                BasicBlock *BB) {
4113   struct CheckAvailable {
4114     bool TraversalDone = false;
4115     bool Available = true;
4116 
4117     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4118     BasicBlock *BB = nullptr;
4119     DominatorTree &DT;
4120 
4121     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4122       : L(L), BB(BB), DT(DT) {}
4123 
4124     bool setUnavailable() {
4125       TraversalDone = true;
4126       Available = false;
4127       return false;
4128     }
4129 
4130     bool follow(const SCEV *S) {
4131       switch (S->getSCEVType()) {
4132       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4133       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4134         // These expressions are available if their operand(s) is/are.
4135         return true;
4136 
4137       case scAddRecExpr: {
4138         // We allow add recurrences that are on the loop BB is in, or some
4139         // outer loop.  This guarantees availability because the value of the
4140         // add recurrence at BB is simply the "current" value of the induction
4141         // variable.  We can relax this in the future; for instance an add
4142         // recurrence on a sibling dominating loop is also available at BB.
4143         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4144         if (L && (ARLoop == L || ARLoop->contains(L)))
4145           return true;
4146 
4147         return setUnavailable();
4148       }
4149 
4150       case scUnknown: {
4151         // For SCEVUnknown, we check for simple dominance.
4152         const auto *SU = cast<SCEVUnknown>(S);
4153         Value *V = SU->getValue();
4154 
4155         if (isa<Argument>(V))
4156           return false;
4157 
4158         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4159           return false;
4160 
4161         return setUnavailable();
4162       }
4163 
4164       case scUDivExpr:
4165       case scCouldNotCompute:
4166         // We do not try to smart about these at all.
4167         return setUnavailable();
4168       }
4169       llvm_unreachable("switch should be fully covered!");
4170     }
4171 
4172     bool isDone() { return TraversalDone; }
4173   };
4174 
4175   CheckAvailable CA(L, BB, DT);
4176   SCEVTraversal<CheckAvailable> ST(CA);
4177 
4178   ST.visitAll(S);
4179   return CA.Available;
4180 }
4181 
4182 // Try to match a control flow sequence that branches out at BI and merges back
4183 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4184 // match.
4185 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4186                           Value *&C, Value *&LHS, Value *&RHS) {
4187   C = BI->getCondition();
4188 
4189   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4190   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4191 
4192   if (!LeftEdge.isSingleEdge())
4193     return false;
4194 
4195   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4196 
4197   Use &LeftUse = Merge->getOperandUse(0);
4198   Use &RightUse = Merge->getOperandUse(1);
4199 
4200   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4201     LHS = LeftUse;
4202     RHS = RightUse;
4203     return true;
4204   }
4205 
4206   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4207     LHS = RightUse;
4208     RHS = LeftUse;
4209     return true;
4210   }
4211 
4212   return false;
4213 }
4214 
4215 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4216   auto IsReachable =
4217       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4218   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4219     const Loop *L = LI.getLoopFor(PN->getParent());
4220 
4221     // We don't want to break LCSSA, even in a SCEV expression tree.
4222     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4223       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4224         return nullptr;
4225 
4226     // Try to match
4227     //
4228     //  br %cond, label %left, label %right
4229     // left:
4230     //  br label %merge
4231     // right:
4232     //  br label %merge
4233     // merge:
4234     //  V = phi [ %x, %left ], [ %y, %right ]
4235     //
4236     // as "select %cond, %x, %y"
4237 
4238     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4239     assert(IDom && "At least the entry block should dominate PN");
4240 
4241     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4242     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4243 
4244     if (BI && BI->isConditional() &&
4245         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4246         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4247         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4248       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4249   }
4250 
4251   return nullptr;
4252 }
4253 
4254 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4255   if (const SCEV *S = createAddRecFromPHI(PN))
4256     return S;
4257 
4258   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4259     return S;
4260 
4261   // If the PHI has a single incoming value, follow that value, unless the
4262   // PHI's incoming blocks are in a different loop, in which case doing so
4263   // risks breaking LCSSA form. Instcombine would normally zap these, but
4264   // it doesn't have DominatorTree information, so it may miss cases.
4265   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4266     if (LI.replacementPreservesLCSSAForm(PN, V))
4267       return getSCEV(V);
4268 
4269   // If it's not a loop phi, we can't handle it yet.
4270   return getUnknown(PN);
4271 }
4272 
4273 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4274                                                       Value *Cond,
4275                                                       Value *TrueVal,
4276                                                       Value *FalseVal) {
4277   // Handle "constant" branch or select. This can occur for instance when a
4278   // loop pass transforms an inner loop and moves on to process the outer loop.
4279   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4280     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4281 
4282   // Try to match some simple smax or umax patterns.
4283   auto *ICI = dyn_cast<ICmpInst>(Cond);
4284   if (!ICI)
4285     return getUnknown(I);
4286 
4287   Value *LHS = ICI->getOperand(0);
4288   Value *RHS = ICI->getOperand(1);
4289 
4290   switch (ICI->getPredicate()) {
4291   case ICmpInst::ICMP_SLT:
4292   case ICmpInst::ICMP_SLE:
4293     std::swap(LHS, RHS);
4294     LLVM_FALLTHROUGH;
4295   case ICmpInst::ICMP_SGT:
4296   case ICmpInst::ICMP_SGE:
4297     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4298     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4299     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4300       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4301       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4302       const SCEV *LA = getSCEV(TrueVal);
4303       const SCEV *RA = getSCEV(FalseVal);
4304       const SCEV *LDiff = getMinusSCEV(LA, LS);
4305       const SCEV *RDiff = getMinusSCEV(RA, RS);
4306       if (LDiff == RDiff)
4307         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4308       LDiff = getMinusSCEV(LA, RS);
4309       RDiff = getMinusSCEV(RA, LS);
4310       if (LDiff == RDiff)
4311         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4312     }
4313     break;
4314   case ICmpInst::ICMP_ULT:
4315   case ICmpInst::ICMP_ULE:
4316     std::swap(LHS, RHS);
4317     LLVM_FALLTHROUGH;
4318   case ICmpInst::ICMP_UGT:
4319   case ICmpInst::ICMP_UGE:
4320     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4321     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4322     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4323       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4324       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4325       const SCEV *LA = getSCEV(TrueVal);
4326       const SCEV *RA = getSCEV(FalseVal);
4327       const SCEV *LDiff = getMinusSCEV(LA, LS);
4328       const SCEV *RDiff = getMinusSCEV(RA, RS);
4329       if (LDiff == RDiff)
4330         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4331       LDiff = getMinusSCEV(LA, RS);
4332       RDiff = getMinusSCEV(RA, LS);
4333       if (LDiff == RDiff)
4334         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4335     }
4336     break;
4337   case ICmpInst::ICMP_NE:
4338     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4339     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4340         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4341       const SCEV *One = getOne(I->getType());
4342       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4343       const SCEV *LA = getSCEV(TrueVal);
4344       const SCEV *RA = getSCEV(FalseVal);
4345       const SCEV *LDiff = getMinusSCEV(LA, LS);
4346       const SCEV *RDiff = getMinusSCEV(RA, One);
4347       if (LDiff == RDiff)
4348         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4349     }
4350     break;
4351   case ICmpInst::ICMP_EQ:
4352     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4353     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4354         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4355       const SCEV *One = getOne(I->getType());
4356       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4357       const SCEV *LA = getSCEV(TrueVal);
4358       const SCEV *RA = getSCEV(FalseVal);
4359       const SCEV *LDiff = getMinusSCEV(LA, One);
4360       const SCEV *RDiff = getMinusSCEV(RA, LS);
4361       if (LDiff == RDiff)
4362         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4363     }
4364     break;
4365   default:
4366     break;
4367   }
4368 
4369   return getUnknown(I);
4370 }
4371 
4372 /// Expand GEP instructions into add and multiply operations. This allows them
4373 /// to be analyzed by regular SCEV code.
4374 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4375   // Don't attempt to analyze GEPs over unsized objects.
4376   if (!GEP->getSourceElementType()->isSized())
4377     return getUnknown(GEP);
4378 
4379   SmallVector<const SCEV *, 4> IndexExprs;
4380   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4381     IndexExprs.push_back(getSCEV(*Index));
4382   return getGEPExpr(GEP->getSourceElementType(),
4383                     getSCEV(GEP->getPointerOperand()),
4384                     IndexExprs, GEP->isInBounds());
4385 }
4386 
4387 uint32_t
4388 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4389   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4390     return C->getAPInt().countTrailingZeros();
4391 
4392   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4393     return std::min(GetMinTrailingZeros(T->getOperand()),
4394                     (uint32_t)getTypeSizeInBits(T->getType()));
4395 
4396   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4397     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4398     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4399              getTypeSizeInBits(E->getType()) : OpRes;
4400   }
4401 
4402   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4403     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4404     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4405              getTypeSizeInBits(E->getType()) : OpRes;
4406   }
4407 
4408   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4409     // The result is the min of all operands results.
4410     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4411     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4412       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4413     return MinOpRes;
4414   }
4415 
4416   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4417     // The result is the sum of all operands results.
4418     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4419     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4420     for (unsigned i = 1, e = M->getNumOperands();
4421          SumOpRes != BitWidth && i != e; ++i)
4422       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
4423                           BitWidth);
4424     return SumOpRes;
4425   }
4426 
4427   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4428     // The result is the min of all operands results.
4429     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4430     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4431       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4432     return MinOpRes;
4433   }
4434 
4435   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4436     // The result is the min of all operands results.
4437     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4438     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4439       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4440     return MinOpRes;
4441   }
4442 
4443   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4444     // The result is the min of all operands results.
4445     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4446     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4447       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4448     return MinOpRes;
4449   }
4450 
4451   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4452     // For a SCEVUnknown, ask ValueTracking.
4453     unsigned BitWidth = getTypeSizeInBits(U->getType());
4454     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4455     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4456                      nullptr, &DT);
4457     return Zeros.countTrailingOnes();
4458   }
4459 
4460   // SCEVUDivExpr
4461   return 0;
4462 }
4463 
4464 /// Helper method to assign a range to V from metadata present in the IR.
4465 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4466   if (Instruction *I = dyn_cast<Instruction>(V))
4467     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4468       return getConstantRangeFromMetadata(*MD);
4469 
4470   return None;
4471 }
4472 
4473 /// Determine the range for a particular SCEV.  If SignHint is
4474 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4475 /// with a "cleaner" unsigned (resp. signed) representation.
4476 ConstantRange
4477 ScalarEvolution::getRange(const SCEV *S,
4478                           ScalarEvolution::RangeSignHint SignHint) {
4479   DenseMap<const SCEV *, ConstantRange> &Cache =
4480       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4481                                                        : SignedRanges;
4482 
4483   // See if we've computed this range already.
4484   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4485   if (I != Cache.end())
4486     return I->second;
4487 
4488   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4489     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4490 
4491   unsigned BitWidth = getTypeSizeInBits(S->getType());
4492   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4493 
4494   // If the value has known zeros, the maximum value will have those known zeros
4495   // as well.
4496   uint32_t TZ = GetMinTrailingZeros(S);
4497   if (TZ != 0) {
4498     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4499       ConservativeResult =
4500           ConstantRange(APInt::getMinValue(BitWidth),
4501                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4502     else
4503       ConservativeResult = ConstantRange(
4504           APInt::getSignedMinValue(BitWidth),
4505           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4506   }
4507 
4508   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4509     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4510     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4511       X = X.add(getRange(Add->getOperand(i), SignHint));
4512     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4513   }
4514 
4515   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4516     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4517     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4518       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4519     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4520   }
4521 
4522   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4523     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4524     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4525       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4526     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4527   }
4528 
4529   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4530     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4531     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4532       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4533     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4534   }
4535 
4536   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4537     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4538     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4539     return setRange(UDiv, SignHint,
4540                     ConservativeResult.intersectWith(X.udiv(Y)));
4541   }
4542 
4543   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4544     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4545     return setRange(ZExt, SignHint,
4546                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4547   }
4548 
4549   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4550     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4551     return setRange(SExt, SignHint,
4552                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4553   }
4554 
4555   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4556     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4557     return setRange(Trunc, SignHint,
4558                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4559   }
4560 
4561   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4562     // If there's no unsigned wrap, the value will never be less than its
4563     // initial value.
4564     if (AddRec->hasNoUnsignedWrap())
4565       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4566         if (!C->getValue()->isZero())
4567           ConservativeResult = ConservativeResult.intersectWith(
4568               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4569 
4570     // If there's no signed wrap, and all the operands have the same sign or
4571     // zero, the value won't ever change sign.
4572     if (AddRec->hasNoSignedWrap()) {
4573       bool AllNonNeg = true;
4574       bool AllNonPos = true;
4575       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4576         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4577         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4578       }
4579       if (AllNonNeg)
4580         ConservativeResult = ConservativeResult.intersectWith(
4581           ConstantRange(APInt(BitWidth, 0),
4582                         APInt::getSignedMinValue(BitWidth)));
4583       else if (AllNonPos)
4584         ConservativeResult = ConservativeResult.intersectWith(
4585           ConstantRange(APInt::getSignedMinValue(BitWidth),
4586                         APInt(BitWidth, 1)));
4587     }
4588 
4589     // TODO: non-affine addrec
4590     if (AddRec->isAffine()) {
4591       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4592       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4593           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4594         auto RangeFromAffine = getRangeForAffineAR(
4595             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4596             BitWidth);
4597         if (!RangeFromAffine.isFullSet())
4598           ConservativeResult =
4599               ConservativeResult.intersectWith(RangeFromAffine);
4600 
4601         auto RangeFromFactoring = getRangeViaFactoring(
4602             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4603             BitWidth);
4604         if (!RangeFromFactoring.isFullSet())
4605           ConservativeResult =
4606               ConservativeResult.intersectWith(RangeFromFactoring);
4607       }
4608     }
4609 
4610     return setRange(AddRec, SignHint, ConservativeResult);
4611   }
4612 
4613   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4614     // Check if the IR explicitly contains !range metadata.
4615     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4616     if (MDRange.hasValue())
4617       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4618 
4619     // Split here to avoid paying the compile-time cost of calling both
4620     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4621     // if needed.
4622     const DataLayout &DL = getDataLayout();
4623     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4624       // For a SCEVUnknown, ask ValueTracking.
4625       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4626       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4627       if (Ones != ~Zeros + 1)
4628         ConservativeResult =
4629             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4630     } else {
4631       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4632              "generalize as needed!");
4633       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4634       if (NS > 1)
4635         ConservativeResult = ConservativeResult.intersectWith(
4636             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4637                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4638     }
4639 
4640     return setRange(U, SignHint, ConservativeResult);
4641   }
4642 
4643   return setRange(S, SignHint, ConservativeResult);
4644 }
4645 
4646 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4647                                                    const SCEV *Step,
4648                                                    const SCEV *MaxBECount,
4649                                                    unsigned BitWidth) {
4650   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4651          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4652          "Precondition!");
4653 
4654   ConstantRange Result(BitWidth, /* isFullSet = */ true);
4655 
4656   // Check for overflow.  This must be done with ConstantRange arithmetic
4657   // because we could be called from within the ScalarEvolution overflow
4658   // checking code.
4659 
4660   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4661   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4662   ConstantRange ZExtMaxBECountRange =
4663       MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4664 
4665   ConstantRange StepSRange = getSignedRange(Step);
4666   ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4667 
4668   ConstantRange StartURange = getUnsignedRange(Start);
4669   ConstantRange EndURange =
4670       StartURange.add(MaxBECountRange.multiply(StepSRange));
4671 
4672   // Check for unsigned overflow.
4673   ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4674   ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4675   if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4676       ZExtEndURange) {
4677     APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4678                                EndURange.getUnsignedMin());
4679     APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4680                                EndURange.getUnsignedMax());
4681     bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4682     if (!IsFullRange)
4683       Result =
4684           Result.intersectWith(ConstantRange(Min, Max + 1));
4685   }
4686 
4687   ConstantRange StartSRange = getSignedRange(Start);
4688   ConstantRange EndSRange =
4689       StartSRange.add(MaxBECountRange.multiply(StepSRange));
4690 
4691   // Check for signed overflow. This must be done with ConstantRange
4692   // arithmetic because we could be called from within the ScalarEvolution
4693   // overflow checking code.
4694   ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4695   ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4696   if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4697       SExtEndSRange) {
4698     APInt Min =
4699         APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4700     APInt Max =
4701         APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4702     bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4703     if (!IsFullRange)
4704       Result =
4705           Result.intersectWith(ConstantRange(Min, Max + 1));
4706   }
4707 
4708   return Result;
4709 }
4710 
4711 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4712                                                     const SCEV *Step,
4713                                                     const SCEV *MaxBECount,
4714                                                     unsigned BitWidth) {
4715   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4716   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4717 
4718   struct SelectPattern {
4719     Value *Condition = nullptr;
4720     APInt TrueValue;
4721     APInt FalseValue;
4722 
4723     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4724                            const SCEV *S) {
4725       Optional<unsigned> CastOp;
4726       APInt Offset(BitWidth, 0);
4727 
4728       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4729              "Should be!");
4730 
4731       // Peel off a constant offset:
4732       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4733         // In the future we could consider being smarter here and handle
4734         // {Start+Step,+,Step} too.
4735         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4736           return;
4737 
4738         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4739         S = SA->getOperand(1);
4740       }
4741 
4742       // Peel off a cast operation
4743       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4744         CastOp = SCast->getSCEVType();
4745         S = SCast->getOperand();
4746       }
4747 
4748       using namespace llvm::PatternMatch;
4749 
4750       auto *SU = dyn_cast<SCEVUnknown>(S);
4751       const APInt *TrueVal, *FalseVal;
4752       if (!SU ||
4753           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4754                                           m_APInt(FalseVal)))) {
4755         Condition = nullptr;
4756         return;
4757       }
4758 
4759       TrueValue = *TrueVal;
4760       FalseValue = *FalseVal;
4761 
4762       // Re-apply the cast we peeled off earlier
4763       if (CastOp.hasValue())
4764         switch (*CastOp) {
4765         default:
4766           llvm_unreachable("Unknown SCEV cast type!");
4767 
4768         case scTruncate:
4769           TrueValue = TrueValue.trunc(BitWidth);
4770           FalseValue = FalseValue.trunc(BitWidth);
4771           break;
4772         case scZeroExtend:
4773           TrueValue = TrueValue.zext(BitWidth);
4774           FalseValue = FalseValue.zext(BitWidth);
4775           break;
4776         case scSignExtend:
4777           TrueValue = TrueValue.sext(BitWidth);
4778           FalseValue = FalseValue.sext(BitWidth);
4779           break;
4780         }
4781 
4782       // Re-apply the constant offset we peeled off earlier
4783       TrueValue += Offset;
4784       FalseValue += Offset;
4785     }
4786 
4787     bool isRecognized() { return Condition != nullptr; }
4788   };
4789 
4790   SelectPattern StartPattern(*this, BitWidth, Start);
4791   if (!StartPattern.isRecognized())
4792     return ConstantRange(BitWidth, /* isFullSet = */ true);
4793 
4794   SelectPattern StepPattern(*this, BitWidth, Step);
4795   if (!StepPattern.isRecognized())
4796     return ConstantRange(BitWidth, /* isFullSet = */ true);
4797 
4798   if (StartPattern.Condition != StepPattern.Condition) {
4799     // We don't handle this case today; but we could, by considering four
4800     // possibilities below instead of two. I'm not sure if there are cases where
4801     // that will help over what getRange already does, though.
4802     return ConstantRange(BitWidth, /* isFullSet = */ true);
4803   }
4804 
4805   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4806   // construct arbitrary general SCEV expressions here.  This function is called
4807   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4808   // say) can end up caching a suboptimal value.
4809 
4810   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4811   // C2352 and C2512 (otherwise it isn't needed).
4812 
4813   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4814   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4815   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4816   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4817 
4818   ConstantRange TrueRange =
4819       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4820   ConstantRange FalseRange =
4821       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4822 
4823   return TrueRange.unionWith(FalseRange);
4824 }
4825 
4826 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4827   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4828   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4829 
4830   // Return early if there are no flags to propagate to the SCEV.
4831   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4832   if (BinOp->hasNoUnsignedWrap())
4833     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4834   if (BinOp->hasNoSignedWrap())
4835     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4836   if (Flags == SCEV::FlagAnyWrap)
4837     return SCEV::FlagAnyWrap;
4838 
4839   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4840 }
4841 
4842 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4843   // Here we check that I is in the header of the innermost loop containing I,
4844   // since we only deal with instructions in the loop header. The actual loop we
4845   // need to check later will come from an add recurrence, but getting that
4846   // requires computing the SCEV of the operands, which can be expensive. This
4847   // check we can do cheaply to rule out some cases early.
4848   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
4849   if (InnermostContainingLoop == nullptr ||
4850       InnermostContainingLoop->getHeader() != I->getParent())
4851     return false;
4852 
4853   // Only proceed if we can prove that I does not yield poison.
4854   if (!isKnownNotFullPoison(I)) return false;
4855 
4856   // At this point we know that if I is executed, then it does not wrap
4857   // according to at least one of NSW or NUW. If I is not executed, then we do
4858   // not know if the calculation that I represents would wrap. Multiple
4859   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
4860   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4861   // derived from other instructions that map to the same SCEV. We cannot make
4862   // that guarantee for cases where I is not executed. So we need to find the
4863   // loop that I is considered in relation to and prove that I is executed for
4864   // every iteration of that loop. That implies that the value that I
4865   // calculates does not wrap anywhere in the loop, so then we can apply the
4866   // flags to the SCEV.
4867   //
4868   // We check isLoopInvariant to disambiguate in case we are adding recurrences
4869   // from different loops, so that we know which loop to prove that I is
4870   // executed in.
4871   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4872     // I could be an extractvalue from a call to an overflow intrinsic.
4873     // TODO: We can do better here in some cases.
4874     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4875       return false;
4876     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
4877     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4878       bool AllOtherOpsLoopInvariant = true;
4879       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4880            ++OtherOpIndex) {
4881         if (OtherOpIndex != OpIndex) {
4882           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4883           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4884             AllOtherOpsLoopInvariant = false;
4885             break;
4886           }
4887         }
4888       }
4889       if (AllOtherOpsLoopInvariant &&
4890           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4891         return true;
4892     }
4893   }
4894   return false;
4895 }
4896 
4897 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4898   // If we know that \c I can never be poison period, then that's enough.
4899   if (isSCEVExprNeverPoison(I))
4900     return true;
4901 
4902   // For an add recurrence specifically, we assume that infinite loops without
4903   // side effects are undefined behavior, and then reason as follows:
4904   //
4905   // If the add recurrence is poison in any iteration, it is poison on all
4906   // future iterations (since incrementing poison yields poison). If the result
4907   // of the add recurrence is fed into the loop latch condition and the loop
4908   // does not contain any throws or exiting blocks other than the latch, we now
4909   // have the ability to "choose" whether the backedge is taken or not (by
4910   // choosing a sufficiently evil value for the poison feeding into the branch)
4911   // for every iteration including and after the one in which \p I first became
4912   // poison.  There are two possibilities (let's call the iteration in which \p
4913   // I first became poison as K):
4914   //
4915   //  1. In the set of iterations including and after K, the loop body executes
4916   //     no side effects.  In this case executing the backege an infinte number
4917   //     of times will yield undefined behavior.
4918   //
4919   //  2. In the set of iterations including and after K, the loop body executes
4920   //     at least one side effect.  In this case, that specific instance of side
4921   //     effect is control dependent on poison, which also yields undefined
4922   //     behavior.
4923 
4924   auto *ExitingBB = L->getExitingBlock();
4925   auto *LatchBB = L->getLoopLatch();
4926   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4927     return false;
4928 
4929   SmallPtrSet<const Instruction *, 16> Pushed;
4930   SmallVector<const Instruction *, 8> PoisonStack;
4931 
4932   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
4933   // things that are known to be fully poison under that assumption go on the
4934   // PoisonStack.
4935   Pushed.insert(I);
4936   PoisonStack.push_back(I);
4937 
4938   bool LatchControlDependentOnPoison = false;
4939   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
4940     const Instruction *Poison = PoisonStack.pop_back_val();
4941 
4942     for (auto *PoisonUser : Poison->users()) {
4943       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4944         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4945           PoisonStack.push_back(cast<Instruction>(PoisonUser));
4946       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
4947         assert(BI->isConditional() && "Only possibility!");
4948         if (BI->getParent() == LatchBB) {
4949           LatchControlDependentOnPoison = true;
4950           break;
4951         }
4952       }
4953     }
4954   }
4955 
4956   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4957 }
4958 
4959 ScalarEvolution::LoopProperties
4960 ScalarEvolution::getLoopProperties(const Loop *L) {
4961   typedef ScalarEvolution::LoopProperties LoopProperties;
4962 
4963   auto Itr = LoopPropertiesCache.find(L);
4964   if (Itr == LoopPropertiesCache.end()) {
4965     auto HasSideEffects = [](Instruction *I) {
4966       if (auto *SI = dyn_cast<StoreInst>(I))
4967         return !SI->isSimple();
4968 
4969       return I->mayHaveSideEffects();
4970     };
4971 
4972     LoopProperties LP = {/* HasNoAbnormalExits */ true,
4973                          /*HasNoSideEffects*/ true};
4974 
4975     for (auto *BB : L->getBlocks())
4976       for (auto &I : *BB) {
4977         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4978           LP.HasNoAbnormalExits = false;
4979         if (HasSideEffects(&I))
4980           LP.HasNoSideEffects = false;
4981         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
4982           break; // We're already as pessimistic as we can get.
4983       }
4984 
4985     auto InsertPair = LoopPropertiesCache.insert({L, LP});
4986     assert(InsertPair.second && "We just checked!");
4987     Itr = InsertPair.first;
4988   }
4989 
4990   return Itr->second;
4991 }
4992 
4993 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4994   if (!isSCEVable(V->getType()))
4995     return getUnknown(V);
4996 
4997   if (Instruction *I = dyn_cast<Instruction>(V)) {
4998     // Don't attempt to analyze instructions in blocks that aren't
4999     // reachable. Such instructions don't matter, and they aren't required
5000     // to obey basic rules for definitions dominating uses which this
5001     // analysis depends on.
5002     if (!DT.isReachableFromEntry(I->getParent()))
5003       return getUnknown(V);
5004   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5005     return getConstant(CI);
5006   else if (isa<ConstantPointerNull>(V))
5007     return getZero(V->getType());
5008   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5009     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5010   else if (!isa<ConstantExpr>(V))
5011     return getUnknown(V);
5012 
5013   Operator *U = cast<Operator>(V);
5014   if (auto BO = MatchBinaryOp(U, DT)) {
5015     switch (BO->Opcode) {
5016     case Instruction::Add: {
5017       // The simple thing to do would be to just call getSCEV on both operands
5018       // and call getAddExpr with the result. However if we're looking at a
5019       // bunch of things all added together, this can be quite inefficient,
5020       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5021       // Instead, gather up all the operands and make a single getAddExpr call.
5022       // LLVM IR canonical form means we need only traverse the left operands.
5023       SmallVector<const SCEV *, 4> AddOps;
5024       do {
5025         if (BO->Op) {
5026           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5027             AddOps.push_back(OpSCEV);
5028             break;
5029           }
5030 
5031           // If a NUW or NSW flag can be applied to the SCEV for this
5032           // addition, then compute the SCEV for this addition by itself
5033           // with a separate call to getAddExpr. We need to do that
5034           // instead of pushing the operands of the addition onto AddOps,
5035           // since the flags are only known to apply to this particular
5036           // addition - they may not apply to other additions that can be
5037           // formed with operands from AddOps.
5038           const SCEV *RHS = getSCEV(BO->RHS);
5039           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5040           if (Flags != SCEV::FlagAnyWrap) {
5041             const SCEV *LHS = getSCEV(BO->LHS);
5042             if (BO->Opcode == Instruction::Sub)
5043               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5044             else
5045               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5046             break;
5047           }
5048         }
5049 
5050         if (BO->Opcode == Instruction::Sub)
5051           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5052         else
5053           AddOps.push_back(getSCEV(BO->RHS));
5054 
5055         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5056         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5057                        NewBO->Opcode != Instruction::Sub)) {
5058           AddOps.push_back(getSCEV(BO->LHS));
5059           break;
5060         }
5061         BO = NewBO;
5062       } while (true);
5063 
5064       return getAddExpr(AddOps);
5065     }
5066 
5067     case Instruction::Mul: {
5068       SmallVector<const SCEV *, 4> MulOps;
5069       do {
5070         if (BO->Op) {
5071           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5072             MulOps.push_back(OpSCEV);
5073             break;
5074           }
5075 
5076           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5077           if (Flags != SCEV::FlagAnyWrap) {
5078             MulOps.push_back(
5079                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5080             break;
5081           }
5082         }
5083 
5084         MulOps.push_back(getSCEV(BO->RHS));
5085         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5086         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5087           MulOps.push_back(getSCEV(BO->LHS));
5088           break;
5089         }
5090         BO = NewBO;
5091       } while (true);
5092 
5093       return getMulExpr(MulOps);
5094     }
5095     case Instruction::UDiv:
5096       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5097     case Instruction::Sub: {
5098       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5099       if (BO->Op)
5100         Flags = getNoWrapFlagsFromUB(BO->Op);
5101       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5102     }
5103     case Instruction::And:
5104       // For an expression like x&255 that merely masks off the high bits,
5105       // use zext(trunc(x)) as the SCEV expression.
5106       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5107         if (CI->isNullValue())
5108           return getSCEV(BO->RHS);
5109         if (CI->isAllOnesValue())
5110           return getSCEV(BO->LHS);
5111         const APInt &A = CI->getValue();
5112 
5113         // Instcombine's ShrinkDemandedConstant may strip bits out of
5114         // constants, obscuring what would otherwise be a low-bits mask.
5115         // Use computeKnownBits to compute what ShrinkDemandedConstant
5116         // knew about to reconstruct a low-bits mask value.
5117         unsigned LZ = A.countLeadingZeros();
5118         unsigned TZ = A.countTrailingZeros();
5119         unsigned BitWidth = A.getBitWidth();
5120         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5121         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5122                          0, &AC, nullptr, &DT);
5123 
5124         APInt EffectiveMask =
5125             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5126         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5127           const SCEV *MulCount = getConstant(ConstantInt::get(
5128               getContext(), APInt::getOneBitSet(BitWidth, TZ)));
5129           return getMulExpr(
5130               getZeroExtendExpr(
5131                   getTruncateExpr(
5132                       getUDivExactExpr(getSCEV(BO->LHS), MulCount),
5133                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5134                   BO->LHS->getType()),
5135               MulCount);
5136         }
5137       }
5138       break;
5139 
5140     case Instruction::Or:
5141       // If the RHS of the Or is a constant, we may have something like:
5142       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5143       // optimizations will transparently handle this case.
5144       //
5145       // In order for this transformation to be safe, the LHS must be of the
5146       // form X*(2^n) and the Or constant must be less than 2^n.
5147       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5148         const SCEV *LHS = getSCEV(BO->LHS);
5149         const APInt &CIVal = CI->getValue();
5150         if (GetMinTrailingZeros(LHS) >=
5151             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5152           // Build a plain add SCEV.
5153           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5154           // If the LHS of the add was an addrec and it has no-wrap flags,
5155           // transfer the no-wrap flags, since an or won't introduce a wrap.
5156           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5157             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5158             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5159                 OldAR->getNoWrapFlags());
5160           }
5161           return S;
5162         }
5163       }
5164       break;
5165 
5166     case Instruction::Xor:
5167       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5168         // If the RHS of xor is -1, then this is a not operation.
5169         if (CI->isAllOnesValue())
5170           return getNotSCEV(getSCEV(BO->LHS));
5171 
5172         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5173         // This is a variant of the check for xor with -1, and it handles
5174         // the case where instcombine has trimmed non-demanded bits out
5175         // of an xor with -1.
5176         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5177           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5178             if (LBO->getOpcode() == Instruction::And &&
5179                 LCI->getValue() == CI->getValue())
5180               if (const SCEVZeroExtendExpr *Z =
5181                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5182                 Type *UTy = BO->LHS->getType();
5183                 const SCEV *Z0 = Z->getOperand();
5184                 Type *Z0Ty = Z0->getType();
5185                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5186 
5187                 // If C is a low-bits mask, the zero extend is serving to
5188                 // mask off the high bits. Complement the operand and
5189                 // re-apply the zext.
5190                 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5191                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5192 
5193                 // If C is a single bit, it may be in the sign-bit position
5194                 // before the zero-extend. In this case, represent the xor
5195                 // using an add, which is equivalent, and re-apply the zext.
5196                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5197                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5198                     Trunc.isSignBit())
5199                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5200                                            UTy);
5201               }
5202       }
5203       break;
5204 
5205   case Instruction::Shl:
5206     // Turn shift left of a constant amount into a multiply.
5207     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5208       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5209 
5210       // If the shift count is not less than the bitwidth, the result of
5211       // the shift is undefined. Don't try to analyze it, because the
5212       // resolution chosen here may differ from the resolution chosen in
5213       // other parts of the compiler.
5214       if (SA->getValue().uge(BitWidth))
5215         break;
5216 
5217       // It is currently not resolved how to interpret NSW for left
5218       // shift by BitWidth - 1, so we avoid applying flags in that
5219       // case. Remove this check (or this comment) once the situation
5220       // is resolved. See
5221       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5222       // and http://reviews.llvm.org/D8890 .
5223       auto Flags = SCEV::FlagAnyWrap;
5224       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5225         Flags = getNoWrapFlagsFromUB(BO->Op);
5226 
5227       Constant *X = ConstantInt::get(getContext(),
5228         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5229       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5230     }
5231     break;
5232 
5233     case Instruction::AShr:
5234       // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5235       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5236         if (Operator *L = dyn_cast<Operator>(BO->LHS))
5237           if (L->getOpcode() == Instruction::Shl &&
5238               L->getOperand(1) == BO->RHS) {
5239             uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
5240 
5241             // If the shift count is not less than the bitwidth, the result of
5242             // the shift is undefined. Don't try to analyze it, because the
5243             // resolution chosen here may differ from the resolution chosen in
5244             // other parts of the compiler.
5245             if (CI->getValue().uge(BitWidth))
5246               break;
5247 
5248             uint64_t Amt = BitWidth - CI->getZExtValue();
5249             if (Amt == BitWidth)
5250               return getSCEV(L->getOperand(0)); // shift by zero --> noop
5251             return getSignExtendExpr(
5252                 getTruncateExpr(getSCEV(L->getOperand(0)),
5253                                 IntegerType::get(getContext(), Amt)),
5254                 BO->LHS->getType());
5255           }
5256       break;
5257     }
5258   }
5259 
5260   switch (U->getOpcode()) {
5261   case Instruction::Trunc:
5262     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5263 
5264   case Instruction::ZExt:
5265     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5266 
5267   case Instruction::SExt:
5268     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5269 
5270   case Instruction::BitCast:
5271     // BitCasts are no-op casts so we just eliminate the cast.
5272     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5273       return getSCEV(U->getOperand(0));
5274     break;
5275 
5276   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5277   // lead to pointer expressions which cannot safely be expanded to GEPs,
5278   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5279   // simplifying integer expressions.
5280 
5281   case Instruction::GetElementPtr:
5282     return createNodeForGEP(cast<GEPOperator>(U));
5283 
5284   case Instruction::PHI:
5285     return createNodeForPHI(cast<PHINode>(U));
5286 
5287   case Instruction::Select:
5288     // U can also be a select constant expr, which let fall through.  Since
5289     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5290     // constant expressions cannot have instructions as operands, we'd have
5291     // returned getUnknown for a select constant expressions anyway.
5292     if (isa<Instruction>(U))
5293       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5294                                       U->getOperand(1), U->getOperand(2));
5295     break;
5296 
5297   case Instruction::Call:
5298   case Instruction::Invoke:
5299     if (Value *RV = CallSite(U).getReturnedArgOperand())
5300       return getSCEV(RV);
5301     break;
5302   }
5303 
5304   return getUnknown(V);
5305 }
5306 
5307 
5308 
5309 //===----------------------------------------------------------------------===//
5310 //                   Iteration Count Computation Code
5311 //
5312 
5313 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5314   if (!ExitCount)
5315     return 0;
5316 
5317   ConstantInt *ExitConst = ExitCount->getValue();
5318 
5319   // Guard against huge trip counts.
5320   if (ExitConst->getValue().getActiveBits() > 32)
5321     return 0;
5322 
5323   // In case of integer overflow, this returns 0, which is correct.
5324   return ((unsigned)ExitConst->getZExtValue()) + 1;
5325 }
5326 
5327 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5328   if (BasicBlock *ExitingBB = L->getExitingBlock())
5329     return getSmallConstantTripCount(L, ExitingBB);
5330 
5331   // No trip count information for multiple exits.
5332   return 0;
5333 }
5334 
5335 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5336                                                     BasicBlock *ExitingBlock) {
5337   assert(ExitingBlock && "Must pass a non-null exiting block!");
5338   assert(L->isLoopExiting(ExitingBlock) &&
5339          "Exiting block must actually branch out of the loop!");
5340   const SCEVConstant *ExitCount =
5341       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5342   return getConstantTripCount(ExitCount);
5343 }
5344 
5345 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) {
5346   const auto *MaxExitCount =
5347       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5348   return getConstantTripCount(MaxExitCount);
5349 }
5350 
5351 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5352   if (BasicBlock *ExitingBB = L->getExitingBlock())
5353     return getSmallConstantTripMultiple(L, ExitingBB);
5354 
5355   // No trip multiple information for multiple exits.
5356   return 0;
5357 }
5358 
5359 /// Returns the largest constant divisor of the trip count of this loop as a
5360 /// normal unsigned value, if possible. This means that the actual trip count is
5361 /// always a multiple of the returned value (don't forget the trip count could
5362 /// very well be zero as well!).
5363 ///
5364 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5365 /// multiple of a constant (which is also the case if the trip count is simply
5366 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5367 /// if the trip count is very large (>= 2^32).
5368 ///
5369 /// As explained in the comments for getSmallConstantTripCount, this assumes
5370 /// that control exits the loop via ExitingBlock.
5371 unsigned
5372 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5373                                               BasicBlock *ExitingBlock) {
5374   assert(ExitingBlock && "Must pass a non-null exiting block!");
5375   assert(L->isLoopExiting(ExitingBlock) &&
5376          "Exiting block must actually branch out of the loop!");
5377   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5378   if (ExitCount == getCouldNotCompute())
5379     return 1;
5380 
5381   // Get the trip count from the BE count by adding 1.
5382   const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5383   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5384   // to factor simple cases.
5385   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5386     TCMul = Mul->getOperand(0);
5387 
5388   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5389   if (!MulC)
5390     return 1;
5391 
5392   ConstantInt *Result = MulC->getValue();
5393 
5394   // Guard against huge trip counts (this requires checking
5395   // for zero to handle the case where the trip count == -1 and the
5396   // addition wraps).
5397   if (!Result || Result->getValue().getActiveBits() > 32 ||
5398       Result->getValue().getActiveBits() == 0)
5399     return 1;
5400 
5401   return (unsigned)Result->getZExtValue();
5402 }
5403 
5404 /// Get the expression for the number of loop iterations for which this loop is
5405 /// guaranteed not to exit via ExitingBlock. Otherwise return
5406 /// SCEVCouldNotCompute.
5407 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5408   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5409 }
5410 
5411 const SCEV *
5412 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5413                                                  SCEVUnionPredicate &Preds) {
5414   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5415 }
5416 
5417 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5418   return getBackedgeTakenInfo(L).getExact(this);
5419 }
5420 
5421 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5422 /// known never to be less than the actual backedge taken count.
5423 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5424   return getBackedgeTakenInfo(L).getMax(this);
5425 }
5426 
5427 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5428 static void
5429 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5430   BasicBlock *Header = L->getHeader();
5431 
5432   // Push all Loop-header PHIs onto the Worklist stack.
5433   for (BasicBlock::iterator I = Header->begin();
5434        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5435     Worklist.push_back(PN);
5436 }
5437 
5438 const ScalarEvolution::BackedgeTakenInfo &
5439 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5440   auto &BTI = getBackedgeTakenInfo(L);
5441   if (BTI.hasFullInfo())
5442     return BTI;
5443 
5444   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5445 
5446   if (!Pair.second)
5447     return Pair.first->second;
5448 
5449   BackedgeTakenInfo Result =
5450       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5451 
5452   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5453 }
5454 
5455 const ScalarEvolution::BackedgeTakenInfo &
5456 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5457   // Initially insert an invalid entry for this loop. If the insertion
5458   // succeeds, proceed to actually compute a backedge-taken count and
5459   // update the value. The temporary CouldNotCompute value tells SCEV
5460   // code elsewhere that it shouldn't attempt to request a new
5461   // backedge-taken count, which could result in infinite recursion.
5462   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5463       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5464   if (!Pair.second)
5465     return Pair.first->second;
5466 
5467   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5468   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5469   // must be cleared in this scope.
5470   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5471 
5472   if (Result.getExact(this) != getCouldNotCompute()) {
5473     assert(isLoopInvariant(Result.getExact(this), L) &&
5474            isLoopInvariant(Result.getMax(this), L) &&
5475            "Computed backedge-taken count isn't loop invariant for loop!");
5476     ++NumTripCountsComputed;
5477   }
5478   else if (Result.getMax(this) == getCouldNotCompute() &&
5479            isa<PHINode>(L->getHeader()->begin())) {
5480     // Only count loops that have phi nodes as not being computable.
5481     ++NumTripCountsNotComputed;
5482   }
5483 
5484   // Now that we know more about the trip count for this loop, forget any
5485   // existing SCEV values for PHI nodes in this loop since they are only
5486   // conservative estimates made without the benefit of trip count
5487   // information. This is similar to the code in forgetLoop, except that
5488   // it handles SCEVUnknown PHI nodes specially.
5489   if (Result.hasAnyInfo()) {
5490     SmallVector<Instruction *, 16> Worklist;
5491     PushLoopPHIs(L, Worklist);
5492 
5493     SmallPtrSet<Instruction *, 8> Visited;
5494     while (!Worklist.empty()) {
5495       Instruction *I = Worklist.pop_back_val();
5496       if (!Visited.insert(I).second)
5497         continue;
5498 
5499       ValueExprMapType::iterator It =
5500         ValueExprMap.find_as(static_cast<Value *>(I));
5501       if (It != ValueExprMap.end()) {
5502         const SCEV *Old = It->second;
5503 
5504         // SCEVUnknown for a PHI either means that it has an unrecognized
5505         // structure, or it's a PHI that's in the progress of being computed
5506         // by createNodeForPHI.  In the former case, additional loop trip
5507         // count information isn't going to change anything. In the later
5508         // case, createNodeForPHI will perform the necessary updates on its
5509         // own when it gets to that point.
5510         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5511           eraseValueFromMap(It->first);
5512           forgetMemoizedResults(Old);
5513         }
5514         if (PHINode *PN = dyn_cast<PHINode>(I))
5515           ConstantEvolutionLoopExitValue.erase(PN);
5516       }
5517 
5518       PushDefUseChildren(I, Worklist);
5519     }
5520   }
5521 
5522   // Re-lookup the insert position, since the call to
5523   // computeBackedgeTakenCount above could result in a
5524   // recusive call to getBackedgeTakenInfo (on a different
5525   // loop), which would invalidate the iterator computed
5526   // earlier.
5527   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5528 }
5529 
5530 void ScalarEvolution::forgetLoop(const Loop *L) {
5531   // Drop any stored trip count value.
5532   auto RemoveLoopFromBackedgeMap =
5533       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5534         auto BTCPos = Map.find(L);
5535         if (BTCPos != Map.end()) {
5536           BTCPos->second.clear();
5537           Map.erase(BTCPos);
5538         }
5539       };
5540 
5541   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5542   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5543 
5544   // Drop information about expressions based on loop-header PHIs.
5545   SmallVector<Instruction *, 16> Worklist;
5546   PushLoopPHIs(L, Worklist);
5547 
5548   SmallPtrSet<Instruction *, 8> Visited;
5549   while (!Worklist.empty()) {
5550     Instruction *I = Worklist.pop_back_val();
5551     if (!Visited.insert(I).second)
5552       continue;
5553 
5554     ValueExprMapType::iterator It =
5555       ValueExprMap.find_as(static_cast<Value *>(I));
5556     if (It != ValueExprMap.end()) {
5557       eraseValueFromMap(It->first);
5558       forgetMemoizedResults(It->second);
5559       if (PHINode *PN = dyn_cast<PHINode>(I))
5560         ConstantEvolutionLoopExitValue.erase(PN);
5561     }
5562 
5563     PushDefUseChildren(I, Worklist);
5564   }
5565 
5566   // Forget all contained loops too, to avoid dangling entries in the
5567   // ValuesAtScopes map.
5568   for (Loop *I : *L)
5569     forgetLoop(I);
5570 
5571   LoopPropertiesCache.erase(L);
5572 }
5573 
5574 void ScalarEvolution::forgetValue(Value *V) {
5575   Instruction *I = dyn_cast<Instruction>(V);
5576   if (!I) return;
5577 
5578   // Drop information about expressions based on loop-header PHIs.
5579   SmallVector<Instruction *, 16> Worklist;
5580   Worklist.push_back(I);
5581 
5582   SmallPtrSet<Instruction *, 8> Visited;
5583   while (!Worklist.empty()) {
5584     I = Worklist.pop_back_val();
5585     if (!Visited.insert(I).second)
5586       continue;
5587 
5588     ValueExprMapType::iterator It =
5589       ValueExprMap.find_as(static_cast<Value *>(I));
5590     if (It != ValueExprMap.end()) {
5591       eraseValueFromMap(It->first);
5592       forgetMemoizedResults(It->second);
5593       if (PHINode *PN = dyn_cast<PHINode>(I))
5594         ConstantEvolutionLoopExitValue.erase(PN);
5595     }
5596 
5597     PushDefUseChildren(I, Worklist);
5598   }
5599 }
5600 
5601 /// Get the exact loop backedge taken count considering all loop exits. A
5602 /// computable result can only be returned for loops with a single exit.
5603 /// Returning the minimum taken count among all exits is incorrect because one
5604 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5605 /// the limit of each loop test is never skipped. This is a valid assumption as
5606 /// long as the loop exits via that test. For precise results, it is the
5607 /// caller's responsibility to specify the relevant loop exit using
5608 /// getExact(ExitingBlock, SE).
5609 const SCEV *
5610 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5611                                              SCEVUnionPredicate *Preds) const {
5612   // If any exits were not computable, the loop is not computable.
5613   if (!isComplete() || ExitNotTaken.empty())
5614     return SE->getCouldNotCompute();
5615 
5616   const SCEV *BECount = nullptr;
5617   for (auto &ENT : ExitNotTaken) {
5618     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5619 
5620     if (!BECount)
5621       BECount = ENT.ExactNotTaken;
5622     else if (BECount != ENT.ExactNotTaken)
5623       return SE->getCouldNotCompute();
5624     if (Preds && !ENT.hasAlwaysTruePredicate())
5625       Preds->add(ENT.Predicate.get());
5626 
5627     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5628            "Predicate should be always true!");
5629   }
5630 
5631   assert(BECount && "Invalid not taken count for loop exit");
5632   return BECount;
5633 }
5634 
5635 /// Get the exact not taken count for this loop exit.
5636 const SCEV *
5637 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5638                                              ScalarEvolution *SE) const {
5639   for (auto &ENT : ExitNotTaken)
5640     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5641       return ENT.ExactNotTaken;
5642 
5643   return SE->getCouldNotCompute();
5644 }
5645 
5646 /// getMax - Get the max backedge taken count for the loop.
5647 const SCEV *
5648 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5649   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5650     return !ENT.hasAlwaysTruePredicate();
5651   };
5652 
5653   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5654     return SE->getCouldNotCompute();
5655 
5656   return getMax();
5657 }
5658 
5659 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5660                                                     ScalarEvolution *SE) const {
5661   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5662       SE->hasOperand(getMax(), S))
5663     return true;
5664 
5665   for (auto &ENT : ExitNotTaken)
5666     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5667         SE->hasOperand(ENT.ExactNotTaken, S))
5668       return true;
5669 
5670   return false;
5671 }
5672 
5673 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5674 /// computable exit into a persistent ExitNotTakenInfo array.
5675 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5676     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5677         &&ExitCounts,
5678     bool Complete, const SCEV *MaxCount)
5679     : MaxAndComplete(MaxCount, Complete) {
5680   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5681   ExitNotTaken.reserve(ExitCounts.size());
5682   std::transform(
5683       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5684       [&](const EdgeExitInfo &EEI) {
5685         BasicBlock *ExitBB = EEI.first;
5686         const ExitLimit &EL = EEI.second;
5687         if (EL.Predicates.empty())
5688           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5689 
5690         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5691         for (auto *Pred : EL.Predicates)
5692           Predicate->add(Pred);
5693 
5694         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5695       });
5696 }
5697 
5698 /// Invalidate this result and free the ExitNotTakenInfo array.
5699 void ScalarEvolution::BackedgeTakenInfo::clear() {
5700   ExitNotTaken.clear();
5701 }
5702 
5703 /// Compute the number of times the backedge of the specified loop will execute.
5704 ScalarEvolution::BackedgeTakenInfo
5705 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5706                                            bool AllowPredicates) {
5707   SmallVector<BasicBlock *, 8> ExitingBlocks;
5708   L->getExitingBlocks(ExitingBlocks);
5709 
5710   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5711 
5712   SmallVector<EdgeExitInfo, 4> ExitCounts;
5713   bool CouldComputeBECount = true;
5714   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5715   const SCEV *MustExitMaxBECount = nullptr;
5716   const SCEV *MayExitMaxBECount = nullptr;
5717 
5718   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5719   // and compute maxBECount.
5720   // Do a union of all the predicates here.
5721   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5722     BasicBlock *ExitBB = ExitingBlocks[i];
5723     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5724 
5725     assert((AllowPredicates || EL.Predicates.empty()) &&
5726            "Predicated exit limit when predicates are not allowed!");
5727 
5728     // 1. For each exit that can be computed, add an entry to ExitCounts.
5729     // CouldComputeBECount is true only if all exits can be computed.
5730     if (EL.ExactNotTaken == getCouldNotCompute())
5731       // We couldn't compute an exact value for this exit, so
5732       // we won't be able to compute an exact value for the loop.
5733       CouldComputeBECount = false;
5734     else
5735       ExitCounts.emplace_back(ExitBB, EL);
5736 
5737     // 2. Derive the loop's MaxBECount from each exit's max number of
5738     // non-exiting iterations. Partition the loop exits into two kinds:
5739     // LoopMustExits and LoopMayExits.
5740     //
5741     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5742     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5743     // MaxBECount is the minimum EL.MaxNotTaken of computable
5744     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5745     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5746     // computable EL.MaxNotTaken.
5747     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5748         DT.dominates(ExitBB, Latch)) {
5749       if (!MustExitMaxBECount)
5750         MustExitMaxBECount = EL.MaxNotTaken;
5751       else {
5752         MustExitMaxBECount =
5753             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5754       }
5755     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5756       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5757         MayExitMaxBECount = EL.MaxNotTaken;
5758       else {
5759         MayExitMaxBECount =
5760             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5761       }
5762     }
5763   }
5764   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5765     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5766   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5767                            MaxBECount);
5768 }
5769 
5770 ScalarEvolution::ExitLimit
5771 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5772                                   bool AllowPredicates) {
5773 
5774   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5775   // at this block and remember the exit block and whether all other targets
5776   // lead to the loop header.
5777   bool MustExecuteLoopHeader = true;
5778   BasicBlock *Exit = nullptr;
5779   for (auto *SBB : successors(ExitingBlock))
5780     if (!L->contains(SBB)) {
5781       if (Exit) // Multiple exit successors.
5782         return getCouldNotCompute();
5783       Exit = SBB;
5784     } else if (SBB != L->getHeader()) {
5785       MustExecuteLoopHeader = false;
5786     }
5787 
5788   // At this point, we know we have a conditional branch that determines whether
5789   // the loop is exited.  However, we don't know if the branch is executed each
5790   // time through the loop.  If not, then the execution count of the branch will
5791   // not be equal to the trip count of the loop.
5792   //
5793   // Currently we check for this by checking to see if the Exit branch goes to
5794   // the loop header.  If so, we know it will always execute the same number of
5795   // times as the loop.  We also handle the case where the exit block *is* the
5796   // loop header.  This is common for un-rotated loops.
5797   //
5798   // If both of those tests fail, walk up the unique predecessor chain to the
5799   // header, stopping if there is an edge that doesn't exit the loop. If the
5800   // header is reached, the execution count of the branch will be equal to the
5801   // trip count of the loop.
5802   //
5803   //  More extensive analysis could be done to handle more cases here.
5804   //
5805   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5806     // The simple checks failed, try climbing the unique predecessor chain
5807     // up to the header.
5808     bool Ok = false;
5809     for (BasicBlock *BB = ExitingBlock; BB; ) {
5810       BasicBlock *Pred = BB->getUniquePredecessor();
5811       if (!Pred)
5812         return getCouldNotCompute();
5813       TerminatorInst *PredTerm = Pred->getTerminator();
5814       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5815         if (PredSucc == BB)
5816           continue;
5817         // If the predecessor has a successor that isn't BB and isn't
5818         // outside the loop, assume the worst.
5819         if (L->contains(PredSucc))
5820           return getCouldNotCompute();
5821       }
5822       if (Pred == L->getHeader()) {
5823         Ok = true;
5824         break;
5825       }
5826       BB = Pred;
5827     }
5828     if (!Ok)
5829       return getCouldNotCompute();
5830   }
5831 
5832   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
5833   TerminatorInst *Term = ExitingBlock->getTerminator();
5834   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5835     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5836     // Proceed to the next level to examine the exit condition expression.
5837     return computeExitLimitFromCond(
5838         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5839         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
5840   }
5841 
5842   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
5843     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
5844                                                 /*ControlsExit=*/IsOnlyExit);
5845 
5846   return getCouldNotCompute();
5847 }
5848 
5849 ScalarEvolution::ExitLimit
5850 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
5851                                           Value *ExitCond,
5852                                           BasicBlock *TBB,
5853                                           BasicBlock *FBB,
5854                                           bool ControlsExit,
5855                                           bool AllowPredicates) {
5856   // Check if the controlling expression for this loop is an And or Or.
5857   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5858     if (BO->getOpcode() == Instruction::And) {
5859       // Recurse on the operands of the and.
5860       bool EitherMayExit = L->contains(TBB);
5861       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5862                                                ControlsExit && !EitherMayExit,
5863                                                AllowPredicates);
5864       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5865                                                ControlsExit && !EitherMayExit,
5866                                                AllowPredicates);
5867       const SCEV *BECount = getCouldNotCompute();
5868       const SCEV *MaxBECount = getCouldNotCompute();
5869       if (EitherMayExit) {
5870         // Both conditions must be true for the loop to continue executing.
5871         // Choose the less conservative count.
5872         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5873             EL1.ExactNotTaken == getCouldNotCompute())
5874           BECount = getCouldNotCompute();
5875         else
5876           BECount =
5877               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5878         if (EL0.MaxNotTaken == getCouldNotCompute())
5879           MaxBECount = EL1.MaxNotTaken;
5880         else if (EL1.MaxNotTaken == getCouldNotCompute())
5881           MaxBECount = EL0.MaxNotTaken;
5882         else
5883           MaxBECount =
5884               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5885       } else {
5886         // Both conditions must be true at the same time for the loop to exit.
5887         // For now, be conservative.
5888         assert(L->contains(FBB) && "Loop block has no successor in loop!");
5889         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5890           MaxBECount = EL0.MaxNotTaken;
5891         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5892           BECount = EL0.ExactNotTaken;
5893       }
5894 
5895       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5896       // to be more aggressive when computing BECount than when computing
5897       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
5898       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5899       // to not.
5900       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5901           !isa<SCEVCouldNotCompute>(BECount))
5902         MaxBECount = BECount;
5903 
5904       return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates});
5905     }
5906     if (BO->getOpcode() == Instruction::Or) {
5907       // Recurse on the operands of the or.
5908       bool EitherMayExit = L->contains(FBB);
5909       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5910                                                ControlsExit && !EitherMayExit,
5911                                                AllowPredicates);
5912       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5913                                                ControlsExit && !EitherMayExit,
5914                                                AllowPredicates);
5915       const SCEV *BECount = getCouldNotCompute();
5916       const SCEV *MaxBECount = getCouldNotCompute();
5917       if (EitherMayExit) {
5918         // Both conditions must be false for the loop to continue executing.
5919         // Choose the less conservative count.
5920         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5921             EL1.ExactNotTaken == getCouldNotCompute())
5922           BECount = getCouldNotCompute();
5923         else
5924           BECount =
5925               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5926         if (EL0.MaxNotTaken == getCouldNotCompute())
5927           MaxBECount = EL1.MaxNotTaken;
5928         else if (EL1.MaxNotTaken == getCouldNotCompute())
5929           MaxBECount = EL0.MaxNotTaken;
5930         else
5931           MaxBECount =
5932               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5933       } else {
5934         // Both conditions must be false at the same time for the loop to exit.
5935         // For now, be conservative.
5936         assert(L->contains(TBB) && "Loop block has no successor in loop!");
5937         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5938           MaxBECount = EL0.MaxNotTaken;
5939         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5940           BECount = EL0.ExactNotTaken;
5941       }
5942 
5943       return ExitLimit(BECount, MaxBECount, {&EL0.Predicates, &EL1.Predicates});
5944     }
5945   }
5946 
5947   // With an icmp, it may be feasible to compute an exact backedge-taken count.
5948   // Proceed to the next level to examine the icmp.
5949   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5950     ExitLimit EL =
5951         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5952     if (EL.hasFullInfo() || !AllowPredicates)
5953       return EL;
5954 
5955     // Try again, but use SCEV predicates this time.
5956     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5957                                     /*AllowPredicates=*/true);
5958   }
5959 
5960   // Check for a constant condition. These are normally stripped out by
5961   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5962   // preserve the CFG and is temporarily leaving constant conditions
5963   // in place.
5964   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5965     if (L->contains(FBB) == !CI->getZExtValue())
5966       // The backedge is always taken.
5967       return getCouldNotCompute();
5968     else
5969       // The backedge is never taken.
5970       return getZero(CI->getType());
5971   }
5972 
5973   // If it's not an integer or pointer comparison then compute it the hard way.
5974   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5975 }
5976 
5977 ScalarEvolution::ExitLimit
5978 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
5979                                           ICmpInst *ExitCond,
5980                                           BasicBlock *TBB,
5981                                           BasicBlock *FBB,
5982                                           bool ControlsExit,
5983                                           bool AllowPredicates) {
5984 
5985   // If the condition was exit on true, convert the condition to exit on false
5986   ICmpInst::Predicate Cond;
5987   if (!L->contains(FBB))
5988     Cond = ExitCond->getPredicate();
5989   else
5990     Cond = ExitCond->getInversePredicate();
5991 
5992   // Handle common loops like: for (X = "string"; *X; ++X)
5993   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5994     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5995       ExitLimit ItCnt =
5996         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5997       if (ItCnt.hasAnyInfo())
5998         return ItCnt;
5999     }
6000 
6001   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6002   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6003 
6004   // Try to evaluate any dependencies out of the loop.
6005   LHS = getSCEVAtScope(LHS, L);
6006   RHS = getSCEVAtScope(RHS, L);
6007 
6008   // At this point, we would like to compute how many iterations of the
6009   // loop the predicate will return true for these inputs.
6010   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6011     // If there is a loop-invariant, force it into the RHS.
6012     std::swap(LHS, RHS);
6013     Cond = ICmpInst::getSwappedPredicate(Cond);
6014   }
6015 
6016   // Simplify the operands before analyzing them.
6017   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6018 
6019   // If we have a comparison of a chrec against a constant, try to use value
6020   // ranges to answer this query.
6021   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6022     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6023       if (AddRec->getLoop() == L) {
6024         // Form the constant range.
6025         ConstantRange CompRange =
6026             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6027 
6028         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6029         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6030       }
6031 
6032   switch (Cond) {
6033   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6034     // Convert to: while (X-Y != 0)
6035     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6036                                 AllowPredicates);
6037     if (EL.hasAnyInfo()) return EL;
6038     break;
6039   }
6040   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6041     // Convert to: while (X-Y == 0)
6042     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6043     if (EL.hasAnyInfo()) return EL;
6044     break;
6045   }
6046   case ICmpInst::ICMP_SLT:
6047   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6048     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6049     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6050                                     AllowPredicates);
6051     if (EL.hasAnyInfo()) return EL;
6052     break;
6053   }
6054   case ICmpInst::ICMP_SGT:
6055   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6056     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6057     ExitLimit EL =
6058         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6059                             AllowPredicates);
6060     if (EL.hasAnyInfo()) return EL;
6061     break;
6062   }
6063   default:
6064     break;
6065   }
6066 
6067   auto *ExhaustiveCount =
6068       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6069 
6070   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6071     return ExhaustiveCount;
6072 
6073   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6074                                       ExitCond->getOperand(1), L, Cond);
6075 }
6076 
6077 ScalarEvolution::ExitLimit
6078 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6079                                                       SwitchInst *Switch,
6080                                                       BasicBlock *ExitingBlock,
6081                                                       bool ControlsExit) {
6082   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6083 
6084   // Give up if the exit is the default dest of a switch.
6085   if (Switch->getDefaultDest() == ExitingBlock)
6086     return getCouldNotCompute();
6087 
6088   assert(L->contains(Switch->getDefaultDest()) &&
6089          "Default case must not exit the loop!");
6090   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6091   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6092 
6093   // while (X != Y) --> while (X-Y != 0)
6094   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6095   if (EL.hasAnyInfo())
6096     return EL;
6097 
6098   return getCouldNotCompute();
6099 }
6100 
6101 static ConstantInt *
6102 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6103                                 ScalarEvolution &SE) {
6104   const SCEV *InVal = SE.getConstant(C);
6105   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6106   assert(isa<SCEVConstant>(Val) &&
6107          "Evaluation of SCEV at constant didn't fold correctly?");
6108   return cast<SCEVConstant>(Val)->getValue();
6109 }
6110 
6111 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6112 /// compute the backedge execution count.
6113 ScalarEvolution::ExitLimit
6114 ScalarEvolution::computeLoadConstantCompareExitLimit(
6115   LoadInst *LI,
6116   Constant *RHS,
6117   const Loop *L,
6118   ICmpInst::Predicate predicate) {
6119 
6120   if (LI->isVolatile()) return getCouldNotCompute();
6121 
6122   // Check to see if the loaded pointer is a getelementptr of a global.
6123   // TODO: Use SCEV instead of manually grubbing with GEPs.
6124   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6125   if (!GEP) return getCouldNotCompute();
6126 
6127   // Make sure that it is really a constant global we are gepping, with an
6128   // initializer, and make sure the first IDX is really 0.
6129   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6130   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6131       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6132       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6133     return getCouldNotCompute();
6134 
6135   // Okay, we allow one non-constant index into the GEP instruction.
6136   Value *VarIdx = nullptr;
6137   std::vector<Constant*> Indexes;
6138   unsigned VarIdxNum = 0;
6139   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6140     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6141       Indexes.push_back(CI);
6142     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6143       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6144       VarIdx = GEP->getOperand(i);
6145       VarIdxNum = i-2;
6146       Indexes.push_back(nullptr);
6147     }
6148 
6149   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6150   if (!VarIdx)
6151     return getCouldNotCompute();
6152 
6153   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6154   // Check to see if X is a loop variant variable value now.
6155   const SCEV *Idx = getSCEV(VarIdx);
6156   Idx = getSCEVAtScope(Idx, L);
6157 
6158   // We can only recognize very limited forms of loop index expressions, in
6159   // particular, only affine AddRec's like {C1,+,C2}.
6160   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6161   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6162       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6163       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6164     return getCouldNotCompute();
6165 
6166   unsigned MaxSteps = MaxBruteForceIterations;
6167   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6168     ConstantInt *ItCst = ConstantInt::get(
6169                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6170     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6171 
6172     // Form the GEP offset.
6173     Indexes[VarIdxNum] = Val;
6174 
6175     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6176                                                          Indexes);
6177     if (!Result) break;  // Cannot compute!
6178 
6179     // Evaluate the condition for this iteration.
6180     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6181     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6182     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6183       ++NumArrayLenItCounts;
6184       return getConstant(ItCst);   // Found terminating iteration!
6185     }
6186   }
6187   return getCouldNotCompute();
6188 }
6189 
6190 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6191     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6192   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6193   if (!RHS)
6194     return getCouldNotCompute();
6195 
6196   const BasicBlock *Latch = L->getLoopLatch();
6197   if (!Latch)
6198     return getCouldNotCompute();
6199 
6200   const BasicBlock *Predecessor = L->getLoopPredecessor();
6201   if (!Predecessor)
6202     return getCouldNotCompute();
6203 
6204   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6205   // Return LHS in OutLHS and shift_opt in OutOpCode.
6206   auto MatchPositiveShift =
6207       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6208 
6209     using namespace PatternMatch;
6210 
6211     ConstantInt *ShiftAmt;
6212     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6213       OutOpCode = Instruction::LShr;
6214     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6215       OutOpCode = Instruction::AShr;
6216     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6217       OutOpCode = Instruction::Shl;
6218     else
6219       return false;
6220 
6221     return ShiftAmt->getValue().isStrictlyPositive();
6222   };
6223 
6224   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6225   //
6226   // loop:
6227   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6228   //   %iv.shifted = lshr i32 %iv, <positive constant>
6229   //
6230   // Return true on a succesful match.  Return the corresponding PHI node (%iv
6231   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6232   auto MatchShiftRecurrence =
6233       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6234     Optional<Instruction::BinaryOps> PostShiftOpCode;
6235 
6236     {
6237       Instruction::BinaryOps OpC;
6238       Value *V;
6239 
6240       // If we encounter a shift instruction, "peel off" the shift operation,
6241       // and remember that we did so.  Later when we inspect %iv's backedge
6242       // value, we will make sure that the backedge value uses the same
6243       // operation.
6244       //
6245       // Note: the peeled shift operation does not have to be the same
6246       // instruction as the one feeding into the PHI's backedge value.  We only
6247       // really care about it being the same *kind* of shift instruction --
6248       // that's all that is required for our later inferences to hold.
6249       if (MatchPositiveShift(LHS, V, OpC)) {
6250         PostShiftOpCode = OpC;
6251         LHS = V;
6252       }
6253     }
6254 
6255     PNOut = dyn_cast<PHINode>(LHS);
6256     if (!PNOut || PNOut->getParent() != L->getHeader())
6257       return false;
6258 
6259     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6260     Value *OpLHS;
6261 
6262     return
6263         // The backedge value for the PHI node must be a shift by a positive
6264         // amount
6265         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6266 
6267         // of the PHI node itself
6268         OpLHS == PNOut &&
6269 
6270         // and the kind of shift should be match the kind of shift we peeled
6271         // off, if any.
6272         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6273   };
6274 
6275   PHINode *PN;
6276   Instruction::BinaryOps OpCode;
6277   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6278     return getCouldNotCompute();
6279 
6280   const DataLayout &DL = getDataLayout();
6281 
6282   // The key rationale for this optimization is that for some kinds of shift
6283   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6284   // within a finite number of iterations.  If the condition guarding the
6285   // backedge (in the sense that the backedge is taken if the condition is true)
6286   // is false for the value the shift recurrence stabilizes to, then we know
6287   // that the backedge is taken only a finite number of times.
6288 
6289   ConstantInt *StableValue = nullptr;
6290   switch (OpCode) {
6291   default:
6292     llvm_unreachable("Impossible case!");
6293 
6294   case Instruction::AShr: {
6295     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6296     // bitwidth(K) iterations.
6297     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6298     bool KnownZero, KnownOne;
6299     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6300                    Predecessor->getTerminator(), &DT);
6301     auto *Ty = cast<IntegerType>(RHS->getType());
6302     if (KnownZero)
6303       StableValue = ConstantInt::get(Ty, 0);
6304     else if (KnownOne)
6305       StableValue = ConstantInt::get(Ty, -1, true);
6306     else
6307       return getCouldNotCompute();
6308 
6309     break;
6310   }
6311   case Instruction::LShr:
6312   case Instruction::Shl:
6313     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6314     // stabilize to 0 in at most bitwidth(K) iterations.
6315     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6316     break;
6317   }
6318 
6319   auto *Result =
6320       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6321   assert(Result->getType()->isIntegerTy(1) &&
6322          "Otherwise cannot be an operand to a branch instruction");
6323 
6324   if (Result->isZeroValue()) {
6325     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6326     const SCEV *UpperBound =
6327         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6328     return ExitLimit(getCouldNotCompute(), UpperBound);
6329   }
6330 
6331   return getCouldNotCompute();
6332 }
6333 
6334 /// Return true if we can constant fold an instruction of the specified type,
6335 /// assuming that all operands were constants.
6336 static bool CanConstantFold(const Instruction *I) {
6337   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6338       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6339       isa<LoadInst>(I))
6340     return true;
6341 
6342   if (const CallInst *CI = dyn_cast<CallInst>(I))
6343     if (const Function *F = CI->getCalledFunction())
6344       return canConstantFoldCallTo(F);
6345   return false;
6346 }
6347 
6348 /// Determine whether this instruction can constant evolve within this loop
6349 /// assuming its operands can all constant evolve.
6350 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6351   // An instruction outside of the loop can't be derived from a loop PHI.
6352   if (!L->contains(I)) return false;
6353 
6354   if (isa<PHINode>(I)) {
6355     // We don't currently keep track of the control flow needed to evaluate
6356     // PHIs, so we cannot handle PHIs inside of loops.
6357     return L->getHeader() == I->getParent();
6358   }
6359 
6360   // If we won't be able to constant fold this expression even if the operands
6361   // are constants, bail early.
6362   return CanConstantFold(I);
6363 }
6364 
6365 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6366 /// recursing through each instruction operand until reaching a loop header phi.
6367 static PHINode *
6368 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6369                                DenseMap<Instruction *, PHINode *> &PHIMap) {
6370 
6371   // Otherwise, we can evaluate this instruction if all of its operands are
6372   // constant or derived from a PHI node themselves.
6373   PHINode *PHI = nullptr;
6374   for (Value *Op : UseInst->operands()) {
6375     if (isa<Constant>(Op)) continue;
6376 
6377     Instruction *OpInst = dyn_cast<Instruction>(Op);
6378     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6379 
6380     PHINode *P = dyn_cast<PHINode>(OpInst);
6381     if (!P)
6382       // If this operand is already visited, reuse the prior result.
6383       // We may have P != PHI if this is the deepest point at which the
6384       // inconsistent paths meet.
6385       P = PHIMap.lookup(OpInst);
6386     if (!P) {
6387       // Recurse and memoize the results, whether a phi is found or not.
6388       // This recursive call invalidates pointers into PHIMap.
6389       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6390       PHIMap[OpInst] = P;
6391     }
6392     if (!P)
6393       return nullptr;  // Not evolving from PHI
6394     if (PHI && PHI != P)
6395       return nullptr;  // Evolving from multiple different PHIs.
6396     PHI = P;
6397   }
6398   // This is a expression evolving from a constant PHI!
6399   return PHI;
6400 }
6401 
6402 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6403 /// in the loop that V is derived from.  We allow arbitrary operations along the
6404 /// way, but the operands of an operation must either be constants or a value
6405 /// derived from a constant PHI.  If this expression does not fit with these
6406 /// constraints, return null.
6407 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6408   Instruction *I = dyn_cast<Instruction>(V);
6409   if (!I || !canConstantEvolve(I, L)) return nullptr;
6410 
6411   if (PHINode *PN = dyn_cast<PHINode>(I))
6412     return PN;
6413 
6414   // Record non-constant instructions contained by the loop.
6415   DenseMap<Instruction *, PHINode *> PHIMap;
6416   return getConstantEvolvingPHIOperands(I, L, PHIMap);
6417 }
6418 
6419 /// EvaluateExpression - Given an expression that passes the
6420 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6421 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6422 /// reason, return null.
6423 static Constant *EvaluateExpression(Value *V, const Loop *L,
6424                                     DenseMap<Instruction *, Constant *> &Vals,
6425                                     const DataLayout &DL,
6426                                     const TargetLibraryInfo *TLI) {
6427   // Convenient constant check, but redundant for recursive calls.
6428   if (Constant *C = dyn_cast<Constant>(V)) return C;
6429   Instruction *I = dyn_cast<Instruction>(V);
6430   if (!I) return nullptr;
6431 
6432   if (Constant *C = Vals.lookup(I)) return C;
6433 
6434   // An instruction inside the loop depends on a value outside the loop that we
6435   // weren't given a mapping for, or a value such as a call inside the loop.
6436   if (!canConstantEvolve(I, L)) return nullptr;
6437 
6438   // An unmapped PHI can be due to a branch or another loop inside this loop,
6439   // or due to this not being the initial iteration through a loop where we
6440   // couldn't compute the evolution of this particular PHI last time.
6441   if (isa<PHINode>(I)) return nullptr;
6442 
6443   std::vector<Constant*> Operands(I->getNumOperands());
6444 
6445   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6446     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6447     if (!Operand) {
6448       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6449       if (!Operands[i]) return nullptr;
6450       continue;
6451     }
6452     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6453     Vals[Operand] = C;
6454     if (!C) return nullptr;
6455     Operands[i] = C;
6456   }
6457 
6458   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6459     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6460                                            Operands[1], DL, TLI);
6461   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6462     if (!LI->isVolatile())
6463       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6464   }
6465   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6466 }
6467 
6468 
6469 // If every incoming value to PN except the one for BB is a specific Constant,
6470 // return that, else return nullptr.
6471 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6472   Constant *IncomingVal = nullptr;
6473 
6474   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6475     if (PN->getIncomingBlock(i) == BB)
6476       continue;
6477 
6478     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6479     if (!CurrentVal)
6480       return nullptr;
6481 
6482     if (IncomingVal != CurrentVal) {
6483       if (IncomingVal)
6484         return nullptr;
6485       IncomingVal = CurrentVal;
6486     }
6487   }
6488 
6489   return IncomingVal;
6490 }
6491 
6492 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6493 /// in the header of its containing loop, we know the loop executes a
6494 /// constant number of times, and the PHI node is just a recurrence
6495 /// involving constants, fold it.
6496 Constant *
6497 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6498                                                    const APInt &BEs,
6499                                                    const Loop *L) {
6500   auto I = ConstantEvolutionLoopExitValue.find(PN);
6501   if (I != ConstantEvolutionLoopExitValue.end())
6502     return I->second;
6503 
6504   if (BEs.ugt(MaxBruteForceIterations))
6505     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6506 
6507   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6508 
6509   DenseMap<Instruction *, Constant *> CurrentIterVals;
6510   BasicBlock *Header = L->getHeader();
6511   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6512 
6513   BasicBlock *Latch = L->getLoopLatch();
6514   if (!Latch)
6515     return nullptr;
6516 
6517   for (auto &I : *Header) {
6518     PHINode *PHI = dyn_cast<PHINode>(&I);
6519     if (!PHI) break;
6520     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6521     if (!StartCST) continue;
6522     CurrentIterVals[PHI] = StartCST;
6523   }
6524   if (!CurrentIterVals.count(PN))
6525     return RetVal = nullptr;
6526 
6527   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6528 
6529   // Execute the loop symbolically to determine the exit value.
6530   if (BEs.getActiveBits() >= 32)
6531     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6532 
6533   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6534   unsigned IterationNum = 0;
6535   const DataLayout &DL = getDataLayout();
6536   for (; ; ++IterationNum) {
6537     if (IterationNum == NumIterations)
6538       return RetVal = CurrentIterVals[PN];  // Got exit value!
6539 
6540     // Compute the value of the PHIs for the next iteration.
6541     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6542     DenseMap<Instruction *, Constant *> NextIterVals;
6543     Constant *NextPHI =
6544         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6545     if (!NextPHI)
6546       return nullptr;        // Couldn't evaluate!
6547     NextIterVals[PN] = NextPHI;
6548 
6549     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6550 
6551     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6552     // cease to be able to evaluate one of them or if they stop evolving,
6553     // because that doesn't necessarily prevent us from computing PN.
6554     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6555     for (const auto &I : CurrentIterVals) {
6556       PHINode *PHI = dyn_cast<PHINode>(I.first);
6557       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6558       PHIsToCompute.emplace_back(PHI, I.second);
6559     }
6560     // We use two distinct loops because EvaluateExpression may invalidate any
6561     // iterators into CurrentIterVals.
6562     for (const auto &I : PHIsToCompute) {
6563       PHINode *PHI = I.first;
6564       Constant *&NextPHI = NextIterVals[PHI];
6565       if (!NextPHI) {   // Not already computed.
6566         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6567         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6568       }
6569       if (NextPHI != I.second)
6570         StoppedEvolving = false;
6571     }
6572 
6573     // If all entries in CurrentIterVals == NextIterVals then we can stop
6574     // iterating, the loop can't continue to change.
6575     if (StoppedEvolving)
6576       return RetVal = CurrentIterVals[PN];
6577 
6578     CurrentIterVals.swap(NextIterVals);
6579   }
6580 }
6581 
6582 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6583                                                           Value *Cond,
6584                                                           bool ExitWhen) {
6585   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6586   if (!PN) return getCouldNotCompute();
6587 
6588   // If the loop is canonicalized, the PHI will have exactly two entries.
6589   // That's the only form we support here.
6590   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6591 
6592   DenseMap<Instruction *, Constant *> CurrentIterVals;
6593   BasicBlock *Header = L->getHeader();
6594   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6595 
6596   BasicBlock *Latch = L->getLoopLatch();
6597   assert(Latch && "Should follow from NumIncomingValues == 2!");
6598 
6599   for (auto &I : *Header) {
6600     PHINode *PHI = dyn_cast<PHINode>(&I);
6601     if (!PHI)
6602       break;
6603     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6604     if (!StartCST) continue;
6605     CurrentIterVals[PHI] = StartCST;
6606   }
6607   if (!CurrentIterVals.count(PN))
6608     return getCouldNotCompute();
6609 
6610   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6611   // the loop symbolically to determine when the condition gets a value of
6612   // "ExitWhen".
6613   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6614   const DataLayout &DL = getDataLayout();
6615   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6616     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6617         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6618 
6619     // Couldn't symbolically evaluate.
6620     if (!CondVal) return getCouldNotCompute();
6621 
6622     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6623       ++NumBruteForceTripCountsComputed;
6624       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6625     }
6626 
6627     // Update all the PHI nodes for the next iteration.
6628     DenseMap<Instruction *, Constant *> NextIterVals;
6629 
6630     // Create a list of which PHIs we need to compute. We want to do this before
6631     // calling EvaluateExpression on them because that may invalidate iterators
6632     // into CurrentIterVals.
6633     SmallVector<PHINode *, 8> PHIsToCompute;
6634     for (const auto &I : CurrentIterVals) {
6635       PHINode *PHI = dyn_cast<PHINode>(I.first);
6636       if (!PHI || PHI->getParent() != Header) continue;
6637       PHIsToCompute.push_back(PHI);
6638     }
6639     for (PHINode *PHI : PHIsToCompute) {
6640       Constant *&NextPHI = NextIterVals[PHI];
6641       if (NextPHI) continue;    // Already computed!
6642 
6643       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6644       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6645     }
6646     CurrentIterVals.swap(NextIterVals);
6647   }
6648 
6649   // Too many iterations were needed to evaluate.
6650   return getCouldNotCompute();
6651 }
6652 
6653 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6654   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6655       ValuesAtScopes[V];
6656   // Check to see if we've folded this expression at this loop before.
6657   for (auto &LS : Values)
6658     if (LS.first == L)
6659       return LS.second ? LS.second : V;
6660 
6661   Values.emplace_back(L, nullptr);
6662 
6663   // Otherwise compute it.
6664   const SCEV *C = computeSCEVAtScope(V, L);
6665   for (auto &LS : reverse(ValuesAtScopes[V]))
6666     if (LS.first == L) {
6667       LS.second = C;
6668       break;
6669     }
6670   return C;
6671 }
6672 
6673 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6674 /// will return Constants for objects which aren't represented by a
6675 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6676 /// Returns NULL if the SCEV isn't representable as a Constant.
6677 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6678   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6679     case scCouldNotCompute:
6680     case scAddRecExpr:
6681       break;
6682     case scConstant:
6683       return cast<SCEVConstant>(V)->getValue();
6684     case scUnknown:
6685       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6686     case scSignExtend: {
6687       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6688       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6689         return ConstantExpr::getSExt(CastOp, SS->getType());
6690       break;
6691     }
6692     case scZeroExtend: {
6693       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6694       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6695         return ConstantExpr::getZExt(CastOp, SZ->getType());
6696       break;
6697     }
6698     case scTruncate: {
6699       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6700       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6701         return ConstantExpr::getTrunc(CastOp, ST->getType());
6702       break;
6703     }
6704     case scAddExpr: {
6705       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6706       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6707         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6708           unsigned AS = PTy->getAddressSpace();
6709           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6710           C = ConstantExpr::getBitCast(C, DestPtrTy);
6711         }
6712         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6713           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6714           if (!C2) return nullptr;
6715 
6716           // First pointer!
6717           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6718             unsigned AS = C2->getType()->getPointerAddressSpace();
6719             std::swap(C, C2);
6720             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6721             // The offsets have been converted to bytes.  We can add bytes to an
6722             // i8* by GEP with the byte count in the first index.
6723             C = ConstantExpr::getBitCast(C, DestPtrTy);
6724           }
6725 
6726           // Don't bother trying to sum two pointers. We probably can't
6727           // statically compute a load that results from it anyway.
6728           if (C2->getType()->isPointerTy())
6729             return nullptr;
6730 
6731           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6732             if (PTy->getElementType()->isStructTy())
6733               C2 = ConstantExpr::getIntegerCast(
6734                   C2, Type::getInt32Ty(C->getContext()), true);
6735             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6736           } else
6737             C = ConstantExpr::getAdd(C, C2);
6738         }
6739         return C;
6740       }
6741       break;
6742     }
6743     case scMulExpr: {
6744       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6745       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6746         // Don't bother with pointers at all.
6747         if (C->getType()->isPointerTy()) return nullptr;
6748         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6749           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6750           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6751           C = ConstantExpr::getMul(C, C2);
6752         }
6753         return C;
6754       }
6755       break;
6756     }
6757     case scUDivExpr: {
6758       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6759       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6760         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6761           if (LHS->getType() == RHS->getType())
6762             return ConstantExpr::getUDiv(LHS, RHS);
6763       break;
6764     }
6765     case scSMaxExpr:
6766     case scUMaxExpr:
6767       break; // TODO: smax, umax.
6768   }
6769   return nullptr;
6770 }
6771 
6772 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6773   if (isa<SCEVConstant>(V)) return V;
6774 
6775   // If this instruction is evolved from a constant-evolving PHI, compute the
6776   // exit value from the loop without using SCEVs.
6777   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6778     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6779       const Loop *LI = this->LI[I->getParent()];
6780       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6781         if (PHINode *PN = dyn_cast<PHINode>(I))
6782           if (PN->getParent() == LI->getHeader()) {
6783             // Okay, there is no closed form solution for the PHI node.  Check
6784             // to see if the loop that contains it has a known backedge-taken
6785             // count.  If so, we may be able to force computation of the exit
6786             // value.
6787             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6788             if (const SCEVConstant *BTCC =
6789                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6790               // Okay, we know how many times the containing loop executes.  If
6791               // this is a constant evolving PHI node, get the final value at
6792               // the specified iteration number.
6793               Constant *RV =
6794                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
6795               if (RV) return getSCEV(RV);
6796             }
6797           }
6798 
6799       // Okay, this is an expression that we cannot symbolically evaluate
6800       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6801       // the arguments into constants, and if so, try to constant propagate the
6802       // result.  This is particularly useful for computing loop exit values.
6803       if (CanConstantFold(I)) {
6804         SmallVector<Constant *, 4> Operands;
6805         bool MadeImprovement = false;
6806         for (Value *Op : I->operands()) {
6807           if (Constant *C = dyn_cast<Constant>(Op)) {
6808             Operands.push_back(C);
6809             continue;
6810           }
6811 
6812           // If any of the operands is non-constant and if they are
6813           // non-integer and non-pointer, don't even try to analyze them
6814           // with scev techniques.
6815           if (!isSCEVable(Op->getType()))
6816             return V;
6817 
6818           const SCEV *OrigV = getSCEV(Op);
6819           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6820           MadeImprovement |= OrigV != OpV;
6821 
6822           Constant *C = BuildConstantFromSCEV(OpV);
6823           if (!C) return V;
6824           if (C->getType() != Op->getType())
6825             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6826                                                               Op->getType(),
6827                                                               false),
6828                                       C, Op->getType());
6829           Operands.push_back(C);
6830         }
6831 
6832         // Check to see if getSCEVAtScope actually made an improvement.
6833         if (MadeImprovement) {
6834           Constant *C = nullptr;
6835           const DataLayout &DL = getDataLayout();
6836           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
6837             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6838                                                 Operands[1], DL, &TLI);
6839           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6840             if (!LI->isVolatile())
6841               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6842           } else
6843             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
6844           if (!C) return V;
6845           return getSCEV(C);
6846         }
6847       }
6848     }
6849 
6850     // This is some other type of SCEVUnknown, just return it.
6851     return V;
6852   }
6853 
6854   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
6855     // Avoid performing the look-up in the common case where the specified
6856     // expression has no loop-variant portions.
6857     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
6858       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6859       if (OpAtScope != Comm->getOperand(i)) {
6860         // Okay, at least one of these operands is loop variant but might be
6861         // foldable.  Build a new instance of the folded commutative expression.
6862         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6863                                             Comm->op_begin()+i);
6864         NewOps.push_back(OpAtScope);
6865 
6866         for (++i; i != e; ++i) {
6867           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6868           NewOps.push_back(OpAtScope);
6869         }
6870         if (isa<SCEVAddExpr>(Comm))
6871           return getAddExpr(NewOps);
6872         if (isa<SCEVMulExpr>(Comm))
6873           return getMulExpr(NewOps);
6874         if (isa<SCEVSMaxExpr>(Comm))
6875           return getSMaxExpr(NewOps);
6876         if (isa<SCEVUMaxExpr>(Comm))
6877           return getUMaxExpr(NewOps);
6878         llvm_unreachable("Unknown commutative SCEV type!");
6879       }
6880     }
6881     // If we got here, all operands are loop invariant.
6882     return Comm;
6883   }
6884 
6885   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
6886     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6887     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
6888     if (LHS == Div->getLHS() && RHS == Div->getRHS())
6889       return Div;   // must be loop invariant
6890     return getUDivExpr(LHS, RHS);
6891   }
6892 
6893   // If this is a loop recurrence for a loop that does not contain L, then we
6894   // are dealing with the final value computed by the loop.
6895   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
6896     // First, attempt to evaluate each operand.
6897     // Avoid performing the look-up in the common case where the specified
6898     // expression has no loop-variant portions.
6899     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6900       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6901       if (OpAtScope == AddRec->getOperand(i))
6902         continue;
6903 
6904       // Okay, at least one of these operands is loop variant but might be
6905       // foldable.  Build a new instance of the folded commutative expression.
6906       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6907                                           AddRec->op_begin()+i);
6908       NewOps.push_back(OpAtScope);
6909       for (++i; i != e; ++i)
6910         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6911 
6912       const SCEV *FoldedRec =
6913         getAddRecExpr(NewOps, AddRec->getLoop(),
6914                       AddRec->getNoWrapFlags(SCEV::FlagNW));
6915       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
6916       // The addrec may be folded to a nonrecurrence, for example, if the
6917       // induction variable is multiplied by zero after constant folding. Go
6918       // ahead and return the folded value.
6919       if (!AddRec)
6920         return FoldedRec;
6921       break;
6922     }
6923 
6924     // If the scope is outside the addrec's loop, evaluate it by using the
6925     // loop exit value of the addrec.
6926     if (!AddRec->getLoop()->contains(L)) {
6927       // To evaluate this recurrence, we need to know how many times the AddRec
6928       // loop iterates.  Compute this now.
6929       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
6930       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
6931 
6932       // Then, evaluate the AddRec.
6933       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
6934     }
6935 
6936     return AddRec;
6937   }
6938 
6939   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
6940     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6941     if (Op == Cast->getOperand())
6942       return Cast;  // must be loop invariant
6943     return getZeroExtendExpr(Op, Cast->getType());
6944   }
6945 
6946   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
6947     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6948     if (Op == Cast->getOperand())
6949       return Cast;  // must be loop invariant
6950     return getSignExtendExpr(Op, Cast->getType());
6951   }
6952 
6953   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
6954     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6955     if (Op == Cast->getOperand())
6956       return Cast;  // must be loop invariant
6957     return getTruncateExpr(Op, Cast->getType());
6958   }
6959 
6960   llvm_unreachable("Unknown SCEV type!");
6961 }
6962 
6963 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
6964   return getSCEVAtScope(getSCEV(V), L);
6965 }
6966 
6967 /// Finds the minimum unsigned root of the following equation:
6968 ///
6969 ///     A * X = B (mod N)
6970 ///
6971 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6972 /// A and B isn't important.
6973 ///
6974 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
6975 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
6976                                                ScalarEvolution &SE) {
6977   uint32_t BW = A.getBitWidth();
6978   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6979   assert(A != 0 && "A must be non-zero.");
6980 
6981   // 1. D = gcd(A, N)
6982   //
6983   // The gcd of A and N may have only one prime factor: 2. The number of
6984   // trailing zeros in A is its multiplicity
6985   uint32_t Mult2 = A.countTrailingZeros();
6986   // D = 2^Mult2
6987 
6988   // 2. Check if B is divisible by D.
6989   //
6990   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6991   // is not less than multiplicity of this prime factor for D.
6992   if (B.countTrailingZeros() < Mult2)
6993     return SE.getCouldNotCompute();
6994 
6995   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6996   // modulo (N / D).
6997   //
6998   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
6999   // bit width during computations.
7000   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7001   APInt Mod(BW + 1, 0);
7002   Mod.setBit(BW - Mult2);  // Mod = N / D
7003   APInt I = AD.multiplicativeInverse(Mod);
7004 
7005   // 4. Compute the minimum unsigned root of the equation:
7006   // I * (B / D) mod (N / D)
7007   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
7008 
7009   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
7010   // bits.
7011   return SE.getConstant(Result.trunc(BW));
7012 }
7013 
7014 /// Find the roots of the quadratic equation for the given quadratic chrec
7015 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7016 /// two SCEVCouldNotCompute objects.
7017 ///
7018 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7019 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7020   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7021   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7022   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7023   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7024 
7025   // We currently can only solve this if the coefficients are constants.
7026   if (!LC || !MC || !NC)
7027     return None;
7028 
7029   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7030   const APInt &L = LC->getAPInt();
7031   const APInt &M = MC->getAPInt();
7032   const APInt &N = NC->getAPInt();
7033   APInt Two(BitWidth, 2);
7034   APInt Four(BitWidth, 4);
7035 
7036   {
7037     using namespace APIntOps;
7038     const APInt& C = L;
7039     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7040     // The B coefficient is M-N/2
7041     APInt B(M);
7042     B -= sdiv(N,Two);
7043 
7044     // The A coefficient is N/2
7045     APInt A(N.sdiv(Two));
7046 
7047     // Compute the B^2-4ac term.
7048     APInt SqrtTerm(B);
7049     SqrtTerm *= B;
7050     SqrtTerm -= Four * (A * C);
7051 
7052     if (SqrtTerm.isNegative()) {
7053       // The loop is provably infinite.
7054       return None;
7055     }
7056 
7057     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7058     // integer value or else APInt::sqrt() will assert.
7059     APInt SqrtVal(SqrtTerm.sqrt());
7060 
7061     // Compute the two solutions for the quadratic formula.
7062     // The divisions must be performed as signed divisions.
7063     APInt NegB(-B);
7064     APInt TwoA(A << 1);
7065     if (TwoA.isMinValue())
7066       return None;
7067 
7068     LLVMContext &Context = SE.getContext();
7069 
7070     ConstantInt *Solution1 =
7071       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7072     ConstantInt *Solution2 =
7073       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7074 
7075     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7076                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7077   } // end APIntOps namespace
7078 }
7079 
7080 ScalarEvolution::ExitLimit
7081 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7082                               bool AllowPredicates) {
7083 
7084   // This is only used for loops with a "x != y" exit test. The exit condition
7085   // is now expressed as a single expression, V = x-y. So the exit test is
7086   // effectively V != 0.  We know and take advantage of the fact that this
7087   // expression only being used in a comparison by zero context.
7088 
7089   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7090   // If the value is a constant
7091   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7092     // If the value is already zero, the branch will execute zero times.
7093     if (C->getValue()->isZero()) return C;
7094     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7095   }
7096 
7097   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7098   if (!AddRec && AllowPredicates)
7099     // Try to make this an AddRec using runtime tests, in the first X
7100     // iterations of this loop, where X is the SCEV expression found by the
7101     // algorithm below.
7102     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7103 
7104   if (!AddRec || AddRec->getLoop() != L)
7105     return getCouldNotCompute();
7106 
7107   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7108   // the quadratic equation to solve it.
7109   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7110     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7111       const SCEVConstant *R1 = Roots->first;
7112       const SCEVConstant *R2 = Roots->second;
7113       // Pick the smallest positive root value.
7114       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7115               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7116         if (!CB->getZExtValue())
7117           std::swap(R1, R2); // R1 is the minimum root now.
7118 
7119         // We can only use this value if the chrec ends up with an exact zero
7120         // value at this index.  When solving for "X*X != 5", for example, we
7121         // should not accept a root of 2.
7122         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7123         if (Val->isZero())
7124           return ExitLimit(R1, R1, Predicates); // We found a quadratic root!
7125       }
7126     }
7127     return getCouldNotCompute();
7128   }
7129 
7130   // Otherwise we can only handle this if it is affine.
7131   if (!AddRec->isAffine())
7132     return getCouldNotCompute();
7133 
7134   // If this is an affine expression, the execution count of this branch is
7135   // the minimum unsigned root of the following equation:
7136   //
7137   //     Start + Step*N = 0 (mod 2^BW)
7138   //
7139   // equivalent to:
7140   //
7141   //             Step*N = -Start (mod 2^BW)
7142   //
7143   // where BW is the common bit width of Start and Step.
7144 
7145   // Get the initial value for the loop.
7146   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7147   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7148 
7149   // For now we handle only constant steps.
7150   //
7151   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7152   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7153   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7154   // We have not yet seen any such cases.
7155   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7156   if (!StepC || StepC->getValue()->equalsInt(0))
7157     return getCouldNotCompute();
7158 
7159   // For positive steps (counting up until unsigned overflow):
7160   //   N = -Start/Step (as unsigned)
7161   // For negative steps (counting down to zero):
7162   //   N = Start/-Step
7163   // First compute the unsigned distance from zero in the direction of Step.
7164   bool CountDown = StepC->getAPInt().isNegative();
7165   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7166 
7167   // Handle unitary steps, which cannot wraparound.
7168   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7169   //   N = Distance (as unsigned)
7170   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7171     ConstantRange CR = getUnsignedRange(Start);
7172     const SCEV *MaxBECount;
7173     if (!CountDown && CR.getUnsignedMin().isMinValue())
7174       // When counting up, the worst starting value is 1, not 0.
7175       MaxBECount = CR.getUnsignedMax().isMinValue()
7176         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7177         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7178     else
7179       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7180                                          : -CR.getUnsignedMin());
7181     return ExitLimit(Distance, MaxBECount, Predicates);
7182   }
7183 
7184   // As a special case, handle the instance where Step is a positive power of
7185   // two. In this case, determining whether Step divides Distance evenly can be
7186   // done by counting and comparing the number of trailing zeros of Step and
7187   // Distance.
7188   if (!CountDown) {
7189     const APInt &StepV = StepC->getAPInt();
7190     // StepV.isPowerOf2() returns true if StepV is an positive power of two.  It
7191     // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7192     // case is not handled as this code is guarded by !CountDown.
7193     if (StepV.isPowerOf2() &&
7194         GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7195       // Here we've constrained the equation to be of the form
7196       //
7197       //   2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W)  ... (0)
7198       //
7199       // where we're operating on a W bit wide integer domain and k is
7200       // non-negative.  The smallest unsigned solution for X is the trip count.
7201       //
7202       // (0) is equivalent to:
7203       //
7204       //      2^(N + k) * Distance' - 2^N * X = L * 2^W
7205       // <=>  2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7206       // <=>  2^k * Distance' - X = L * 2^(W - N)
7207       // <=>  2^k * Distance'     = L * 2^(W - N) + X    ... (1)
7208       //
7209       // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7210       // by 2^(W - N).
7211       //
7212       // <=>  X = 2^k * Distance' URem 2^(W - N)   ... (2)
7213       //
7214       // E.g. say we're solving
7215       //
7216       //   2 * Val = 2 * X  (in i8)   ... (3)
7217       //
7218       // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7219       //
7220       // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7221       // necessarily the smallest unsigned value of X that satisfies (3).
7222       // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7223       // is i8 1, not i8 -127
7224 
7225       const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7226 
7227       // Since SCEV does not have a URem node, we construct one using a truncate
7228       // and a zero extend.
7229 
7230       unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7231       auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7232       auto *WideTy = Distance->getType();
7233 
7234       const SCEV *Limit =
7235           getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7236       return ExitLimit(Limit, Limit, Predicates);
7237     }
7238   }
7239 
7240   // If the condition controls loop exit (the loop exits only if the expression
7241   // is true) and the addition is no-wrap we can use unsigned divide to
7242   // compute the backedge count.  In this case, the step may not divide the
7243   // distance, but we don't care because if the condition is "missed" the loop
7244   // will have undefined behavior due to wrapping.
7245   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7246       loopHasNoAbnormalExits(AddRec->getLoop())) {
7247     const SCEV *Exact =
7248         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7249     return ExitLimit(Exact, Exact, Predicates);
7250   }
7251 
7252   // Then, try to solve the above equation provided that Start is constant.
7253   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7254     const SCEV *E = SolveLinEquationWithOverflow(
7255         StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7256     return ExitLimit(E, E, Predicates);
7257   }
7258   return getCouldNotCompute();
7259 }
7260 
7261 ScalarEvolution::ExitLimit
7262 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7263   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7264   // handle them yet except for the trivial case.  This could be expanded in the
7265   // future as needed.
7266 
7267   // If the value is a constant, check to see if it is known to be non-zero
7268   // already.  If so, the backedge will execute zero times.
7269   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7270     if (!C->getValue()->isNullValue())
7271       return getZero(C->getType());
7272     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7273   }
7274 
7275   // We could implement others, but I really doubt anyone writes loops like
7276   // this, and if they did, they would already be constant folded.
7277   return getCouldNotCompute();
7278 }
7279 
7280 std::pair<BasicBlock *, BasicBlock *>
7281 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7282   // If the block has a unique predecessor, then there is no path from the
7283   // predecessor to the block that does not go through the direct edge
7284   // from the predecessor to the block.
7285   if (BasicBlock *Pred = BB->getSinglePredecessor())
7286     return {Pred, BB};
7287 
7288   // A loop's header is defined to be a block that dominates the loop.
7289   // If the header has a unique predecessor outside the loop, it must be
7290   // a block that has exactly one successor that can reach the loop.
7291   if (Loop *L = LI.getLoopFor(BB))
7292     return {L->getLoopPredecessor(), L->getHeader()};
7293 
7294   return {nullptr, nullptr};
7295 }
7296 
7297 /// SCEV structural equivalence is usually sufficient for testing whether two
7298 /// expressions are equal, however for the purposes of looking for a condition
7299 /// guarding a loop, it can be useful to be a little more general, since a
7300 /// front-end may have replicated the controlling expression.
7301 ///
7302 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7303   // Quick check to see if they are the same SCEV.
7304   if (A == B) return true;
7305 
7306   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7307     // Not all instructions that are "identical" compute the same value.  For
7308     // instance, two distinct alloca instructions allocating the same type are
7309     // identical and do not read memory; but compute distinct values.
7310     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7311   };
7312 
7313   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7314   // two different instructions with the same value. Check for this case.
7315   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7316     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7317       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7318         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7319           if (ComputesEqualValues(AI, BI))
7320             return true;
7321 
7322   // Otherwise assume they may have a different value.
7323   return false;
7324 }
7325 
7326 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7327                                            const SCEV *&LHS, const SCEV *&RHS,
7328                                            unsigned Depth) {
7329   bool Changed = false;
7330 
7331   // If we hit the max recursion limit bail out.
7332   if (Depth >= 3)
7333     return false;
7334 
7335   // Canonicalize a constant to the right side.
7336   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7337     // Check for both operands constant.
7338     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7339       if (ConstantExpr::getICmp(Pred,
7340                                 LHSC->getValue(),
7341                                 RHSC->getValue())->isNullValue())
7342         goto trivially_false;
7343       else
7344         goto trivially_true;
7345     }
7346     // Otherwise swap the operands to put the constant on the right.
7347     std::swap(LHS, RHS);
7348     Pred = ICmpInst::getSwappedPredicate(Pred);
7349     Changed = true;
7350   }
7351 
7352   // If we're comparing an addrec with a value which is loop-invariant in the
7353   // addrec's loop, put the addrec on the left. Also make a dominance check,
7354   // as both operands could be addrecs loop-invariant in each other's loop.
7355   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7356     const Loop *L = AR->getLoop();
7357     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7358       std::swap(LHS, RHS);
7359       Pred = ICmpInst::getSwappedPredicate(Pred);
7360       Changed = true;
7361     }
7362   }
7363 
7364   // If there's a constant operand, canonicalize comparisons with boundary
7365   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7366   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7367     const APInt &RA = RC->getAPInt();
7368 
7369     bool SimplifiedByConstantRange = false;
7370 
7371     if (!ICmpInst::isEquality(Pred)) {
7372       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7373       if (ExactCR.isFullSet())
7374         goto trivially_true;
7375       else if (ExactCR.isEmptySet())
7376         goto trivially_false;
7377 
7378       APInt NewRHS;
7379       CmpInst::Predicate NewPred;
7380       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7381           ICmpInst::isEquality(NewPred)) {
7382         // We were able to convert an inequality to an equality.
7383         Pred = NewPred;
7384         RHS = getConstant(NewRHS);
7385         Changed = SimplifiedByConstantRange = true;
7386       }
7387     }
7388 
7389     if (!SimplifiedByConstantRange) {
7390       switch (Pred) {
7391       default:
7392         break;
7393       case ICmpInst::ICMP_EQ:
7394       case ICmpInst::ICMP_NE:
7395         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7396         if (!RA)
7397           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7398             if (const SCEVMulExpr *ME =
7399                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7400               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7401                   ME->getOperand(0)->isAllOnesValue()) {
7402                 RHS = AE->getOperand(1);
7403                 LHS = ME->getOperand(1);
7404                 Changed = true;
7405               }
7406         break;
7407 
7408 
7409         // The "Should have been caught earlier!" messages refer to the fact
7410         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7411         // should have fired on the corresponding cases, and canonicalized the
7412         // check to trivially_true or trivially_false.
7413 
7414       case ICmpInst::ICMP_UGE:
7415         assert(!RA.isMinValue() && "Should have been caught earlier!");
7416         Pred = ICmpInst::ICMP_UGT;
7417         RHS = getConstant(RA - 1);
7418         Changed = true;
7419         break;
7420       case ICmpInst::ICMP_ULE:
7421         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7422         Pred = ICmpInst::ICMP_ULT;
7423         RHS = getConstant(RA + 1);
7424         Changed = true;
7425         break;
7426       case ICmpInst::ICMP_SGE:
7427         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7428         Pred = ICmpInst::ICMP_SGT;
7429         RHS = getConstant(RA - 1);
7430         Changed = true;
7431         break;
7432       case ICmpInst::ICMP_SLE:
7433         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7434         Pred = ICmpInst::ICMP_SLT;
7435         RHS = getConstant(RA + 1);
7436         Changed = true;
7437         break;
7438       }
7439     }
7440   }
7441 
7442   // Check for obvious equality.
7443   if (HasSameValue(LHS, RHS)) {
7444     if (ICmpInst::isTrueWhenEqual(Pred))
7445       goto trivially_true;
7446     if (ICmpInst::isFalseWhenEqual(Pred))
7447       goto trivially_false;
7448   }
7449 
7450   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7451   // adding or subtracting 1 from one of the operands.
7452   switch (Pred) {
7453   case ICmpInst::ICMP_SLE:
7454     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7455       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7456                        SCEV::FlagNSW);
7457       Pred = ICmpInst::ICMP_SLT;
7458       Changed = true;
7459     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7460       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7461                        SCEV::FlagNSW);
7462       Pred = ICmpInst::ICMP_SLT;
7463       Changed = true;
7464     }
7465     break;
7466   case ICmpInst::ICMP_SGE:
7467     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7468       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7469                        SCEV::FlagNSW);
7470       Pred = ICmpInst::ICMP_SGT;
7471       Changed = true;
7472     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7473       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7474                        SCEV::FlagNSW);
7475       Pred = ICmpInst::ICMP_SGT;
7476       Changed = true;
7477     }
7478     break;
7479   case ICmpInst::ICMP_ULE:
7480     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7481       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7482                        SCEV::FlagNUW);
7483       Pred = ICmpInst::ICMP_ULT;
7484       Changed = true;
7485     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7486       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7487       Pred = ICmpInst::ICMP_ULT;
7488       Changed = true;
7489     }
7490     break;
7491   case ICmpInst::ICMP_UGE:
7492     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7493       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7494       Pred = ICmpInst::ICMP_UGT;
7495       Changed = true;
7496     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7497       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7498                        SCEV::FlagNUW);
7499       Pred = ICmpInst::ICMP_UGT;
7500       Changed = true;
7501     }
7502     break;
7503   default:
7504     break;
7505   }
7506 
7507   // TODO: More simplifications are possible here.
7508 
7509   // Recursively simplify until we either hit a recursion limit or nothing
7510   // changes.
7511   if (Changed)
7512     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7513 
7514   return Changed;
7515 
7516 trivially_true:
7517   // Return 0 == 0.
7518   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7519   Pred = ICmpInst::ICMP_EQ;
7520   return true;
7521 
7522 trivially_false:
7523   // Return 0 != 0.
7524   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7525   Pred = ICmpInst::ICMP_NE;
7526   return true;
7527 }
7528 
7529 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7530   return getSignedRange(S).getSignedMax().isNegative();
7531 }
7532 
7533 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7534   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7535 }
7536 
7537 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7538   return !getSignedRange(S).getSignedMin().isNegative();
7539 }
7540 
7541 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7542   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7543 }
7544 
7545 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7546   return isKnownNegative(S) || isKnownPositive(S);
7547 }
7548 
7549 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7550                                        const SCEV *LHS, const SCEV *RHS) {
7551   // Canonicalize the inputs first.
7552   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7553 
7554   // If LHS or RHS is an addrec, check to see if the condition is true in
7555   // every iteration of the loop.
7556   // If LHS and RHS are both addrec, both conditions must be true in
7557   // every iteration of the loop.
7558   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7559   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7560   bool LeftGuarded = false;
7561   bool RightGuarded = false;
7562   if (LAR) {
7563     const Loop *L = LAR->getLoop();
7564     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7565         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7566       if (!RAR) return true;
7567       LeftGuarded = true;
7568     }
7569   }
7570   if (RAR) {
7571     const Loop *L = RAR->getLoop();
7572     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7573         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7574       if (!LAR) return true;
7575       RightGuarded = true;
7576     }
7577   }
7578   if (LeftGuarded && RightGuarded)
7579     return true;
7580 
7581   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7582     return true;
7583 
7584   // Otherwise see what can be done with known constant ranges.
7585   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7586 }
7587 
7588 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7589                                            ICmpInst::Predicate Pred,
7590                                            bool &Increasing) {
7591   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7592 
7593 #ifndef NDEBUG
7594   // Verify an invariant: inverting the predicate should turn a monotonically
7595   // increasing change to a monotonically decreasing one, and vice versa.
7596   bool IncreasingSwapped;
7597   bool ResultSwapped = isMonotonicPredicateImpl(
7598       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7599 
7600   assert(Result == ResultSwapped && "should be able to analyze both!");
7601   if (ResultSwapped)
7602     assert(Increasing == !IncreasingSwapped &&
7603            "monotonicity should flip as we flip the predicate");
7604 #endif
7605 
7606   return Result;
7607 }
7608 
7609 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7610                                                ICmpInst::Predicate Pred,
7611                                                bool &Increasing) {
7612 
7613   // A zero step value for LHS means the induction variable is essentially a
7614   // loop invariant value. We don't really depend on the predicate actually
7615   // flipping from false to true (for increasing predicates, and the other way
7616   // around for decreasing predicates), all we care about is that *if* the
7617   // predicate changes then it only changes from false to true.
7618   //
7619   // A zero step value in itself is not very useful, but there may be places
7620   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7621   // as general as possible.
7622 
7623   switch (Pred) {
7624   default:
7625     return false; // Conservative answer
7626 
7627   case ICmpInst::ICMP_UGT:
7628   case ICmpInst::ICMP_UGE:
7629   case ICmpInst::ICMP_ULT:
7630   case ICmpInst::ICMP_ULE:
7631     if (!LHS->hasNoUnsignedWrap())
7632       return false;
7633 
7634     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7635     return true;
7636 
7637   case ICmpInst::ICMP_SGT:
7638   case ICmpInst::ICMP_SGE:
7639   case ICmpInst::ICMP_SLT:
7640   case ICmpInst::ICMP_SLE: {
7641     if (!LHS->hasNoSignedWrap())
7642       return false;
7643 
7644     const SCEV *Step = LHS->getStepRecurrence(*this);
7645 
7646     if (isKnownNonNegative(Step)) {
7647       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7648       return true;
7649     }
7650 
7651     if (isKnownNonPositive(Step)) {
7652       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7653       return true;
7654     }
7655 
7656     return false;
7657   }
7658 
7659   }
7660 
7661   llvm_unreachable("switch has default clause!");
7662 }
7663 
7664 bool ScalarEvolution::isLoopInvariantPredicate(
7665     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7666     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7667     const SCEV *&InvariantRHS) {
7668 
7669   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7670   if (!isLoopInvariant(RHS, L)) {
7671     if (!isLoopInvariant(LHS, L))
7672       return false;
7673 
7674     std::swap(LHS, RHS);
7675     Pred = ICmpInst::getSwappedPredicate(Pred);
7676   }
7677 
7678   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7679   if (!ArLHS || ArLHS->getLoop() != L)
7680     return false;
7681 
7682   bool Increasing;
7683   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7684     return false;
7685 
7686   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7687   // true as the loop iterates, and the backedge is control dependent on
7688   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7689   //
7690   //   * if the predicate was false in the first iteration then the predicate
7691   //     is never evaluated again, since the loop exits without taking the
7692   //     backedge.
7693   //   * if the predicate was true in the first iteration then it will
7694   //     continue to be true for all future iterations since it is
7695   //     monotonically increasing.
7696   //
7697   // For both the above possibilities, we can replace the loop varying
7698   // predicate with its value on the first iteration of the loop (which is
7699   // loop invariant).
7700   //
7701   // A similar reasoning applies for a monotonically decreasing predicate, by
7702   // replacing true with false and false with true in the above two bullets.
7703 
7704   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7705 
7706   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7707     return false;
7708 
7709   InvariantPred = Pred;
7710   InvariantLHS = ArLHS->getStart();
7711   InvariantRHS = RHS;
7712   return true;
7713 }
7714 
7715 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7716     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7717   if (HasSameValue(LHS, RHS))
7718     return ICmpInst::isTrueWhenEqual(Pred);
7719 
7720   // This code is split out from isKnownPredicate because it is called from
7721   // within isLoopEntryGuardedByCond.
7722 
7723   auto CheckRanges =
7724       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7725     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7726         .contains(RangeLHS);
7727   };
7728 
7729   // The check at the top of the function catches the case where the values are
7730   // known to be equal.
7731   if (Pred == CmpInst::ICMP_EQ)
7732     return false;
7733 
7734   if (Pred == CmpInst::ICMP_NE)
7735     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7736            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7737            isKnownNonZero(getMinusSCEV(LHS, RHS));
7738 
7739   if (CmpInst::isSigned(Pred))
7740     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7741 
7742   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7743 }
7744 
7745 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7746                                                     const SCEV *LHS,
7747                                                     const SCEV *RHS) {
7748 
7749   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7750   // Return Y via OutY.
7751   auto MatchBinaryAddToConst =
7752       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7753              SCEV::NoWrapFlags ExpectedFlags) {
7754     const SCEV *NonConstOp, *ConstOp;
7755     SCEV::NoWrapFlags FlagsPresent;
7756 
7757     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7758         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7759       return false;
7760 
7761     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7762     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7763   };
7764 
7765   APInt C;
7766 
7767   switch (Pred) {
7768   default:
7769     break;
7770 
7771   case ICmpInst::ICMP_SGE:
7772     std::swap(LHS, RHS);
7773   case ICmpInst::ICMP_SLE:
7774     // X s<= (X + C)<nsw> if C >= 0
7775     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7776       return true;
7777 
7778     // (X + C)<nsw> s<= X if C <= 0
7779     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7780         !C.isStrictlyPositive())
7781       return true;
7782     break;
7783 
7784   case ICmpInst::ICMP_SGT:
7785     std::swap(LHS, RHS);
7786   case ICmpInst::ICMP_SLT:
7787     // X s< (X + C)<nsw> if C > 0
7788     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7789         C.isStrictlyPositive())
7790       return true;
7791 
7792     // (X + C)<nsw> s< X if C < 0
7793     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7794       return true;
7795     break;
7796   }
7797 
7798   return false;
7799 }
7800 
7801 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7802                                                    const SCEV *LHS,
7803                                                    const SCEV *RHS) {
7804   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7805     return false;
7806 
7807   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7808   // the stack can result in exponential time complexity.
7809   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7810 
7811   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7812   //
7813   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7814   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7815   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7816   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7817   // use isKnownPredicate later if needed.
7818   return isKnownNonNegative(RHS) &&
7819          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7820          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7821 }
7822 
7823 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7824                                         ICmpInst::Predicate Pred,
7825                                         const SCEV *LHS, const SCEV *RHS) {
7826   // No need to even try if we know the module has no guards.
7827   if (!HasGuards)
7828     return false;
7829 
7830   return any_of(*BB, [&](Instruction &I) {
7831     using namespace llvm::PatternMatch;
7832 
7833     Value *Condition;
7834     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7835                          m_Value(Condition))) &&
7836            isImpliedCond(Pred, LHS, RHS, Condition, false);
7837   });
7838 }
7839 
7840 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7841 /// protected by a conditional between LHS and RHS.  This is used to
7842 /// to eliminate casts.
7843 bool
7844 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7845                                              ICmpInst::Predicate Pred,
7846                                              const SCEV *LHS, const SCEV *RHS) {
7847   // Interpret a null as meaning no loop, where there is obviously no guard
7848   // (interprocedural conditions notwithstanding).
7849   if (!L) return true;
7850 
7851   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7852     return true;
7853 
7854   BasicBlock *Latch = L->getLoopLatch();
7855   if (!Latch)
7856     return false;
7857 
7858   BranchInst *LoopContinuePredicate =
7859     dyn_cast<BranchInst>(Latch->getTerminator());
7860   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7861       isImpliedCond(Pred, LHS, RHS,
7862                     LoopContinuePredicate->getCondition(),
7863                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7864     return true;
7865 
7866   // We don't want more than one activation of the following loops on the stack
7867   // -- that can lead to O(n!) time complexity.
7868   if (WalkingBEDominatingConds)
7869     return false;
7870 
7871   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7872 
7873   // See if we can exploit a trip count to prove the predicate.
7874   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7875   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7876   if (LatchBECount != getCouldNotCompute()) {
7877     // We know that Latch branches back to the loop header exactly
7878     // LatchBECount times.  This means the backdege condition at Latch is
7879     // equivalent to  "{0,+,1} u< LatchBECount".
7880     Type *Ty = LatchBECount->getType();
7881     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7882     const SCEV *LoopCounter =
7883       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7884     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7885                       LatchBECount))
7886       return true;
7887   }
7888 
7889   // Check conditions due to any @llvm.assume intrinsics.
7890   for (auto &AssumeVH : AC.assumptions()) {
7891     if (!AssumeVH)
7892       continue;
7893     auto *CI = cast<CallInst>(AssumeVH);
7894     if (!DT.dominates(CI, Latch->getTerminator()))
7895       continue;
7896 
7897     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7898       return true;
7899   }
7900 
7901   // If the loop is not reachable from the entry block, we risk running into an
7902   // infinite loop as we walk up into the dom tree.  These loops do not matter
7903   // anyway, so we just return a conservative answer when we see them.
7904   if (!DT.isReachableFromEntry(L->getHeader()))
7905     return false;
7906 
7907   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7908     return true;
7909 
7910   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7911        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7912 
7913     assert(DTN && "should reach the loop header before reaching the root!");
7914 
7915     BasicBlock *BB = DTN->getBlock();
7916     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7917       return true;
7918 
7919     BasicBlock *PBB = BB->getSinglePredecessor();
7920     if (!PBB)
7921       continue;
7922 
7923     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7924     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7925       continue;
7926 
7927     Value *Condition = ContinuePredicate->getCondition();
7928 
7929     // If we have an edge `E` within the loop body that dominates the only
7930     // latch, the condition guarding `E` also guards the backedge.  This
7931     // reasoning works only for loops with a single latch.
7932 
7933     BasicBlockEdge DominatingEdge(PBB, BB);
7934     if (DominatingEdge.isSingleEdge()) {
7935       // We're constructively (and conservatively) enumerating edges within the
7936       // loop body that dominate the latch.  The dominator tree better agree
7937       // with us on this:
7938       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
7939 
7940       if (isImpliedCond(Pred, LHS, RHS, Condition,
7941                         BB != ContinuePredicate->getSuccessor(0)))
7942         return true;
7943     }
7944   }
7945 
7946   return false;
7947 }
7948 
7949 bool
7950 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7951                                           ICmpInst::Predicate Pred,
7952                                           const SCEV *LHS, const SCEV *RHS) {
7953   // Interpret a null as meaning no loop, where there is obviously no guard
7954   // (interprocedural conditions notwithstanding).
7955   if (!L) return false;
7956 
7957   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7958     return true;
7959 
7960   // Starting at the loop predecessor, climb up the predecessor chain, as long
7961   // as there are predecessors that can be found that have unique successors
7962   // leading to the original header.
7963   for (std::pair<BasicBlock *, BasicBlock *>
7964          Pair(L->getLoopPredecessor(), L->getHeader());
7965        Pair.first;
7966        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
7967 
7968     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
7969       return true;
7970 
7971     BranchInst *LoopEntryPredicate =
7972       dyn_cast<BranchInst>(Pair.first->getTerminator());
7973     if (!LoopEntryPredicate ||
7974         LoopEntryPredicate->isUnconditional())
7975       continue;
7976 
7977     if (isImpliedCond(Pred, LHS, RHS,
7978                       LoopEntryPredicate->getCondition(),
7979                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
7980       return true;
7981   }
7982 
7983   // Check conditions due to any @llvm.assume intrinsics.
7984   for (auto &AssumeVH : AC.assumptions()) {
7985     if (!AssumeVH)
7986       continue;
7987     auto *CI = cast<CallInst>(AssumeVH);
7988     if (!DT.dominates(CI, L->getHeader()))
7989       continue;
7990 
7991     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7992       return true;
7993   }
7994 
7995   return false;
7996 }
7997 
7998 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
7999                                     const SCEV *LHS, const SCEV *RHS,
8000                                     Value *FoundCondValue,
8001                                     bool Inverse) {
8002   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8003     return false;
8004 
8005   auto ClearOnExit =
8006       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8007 
8008   // Recursively handle And and Or conditions.
8009   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8010     if (BO->getOpcode() == Instruction::And) {
8011       if (!Inverse)
8012         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8013                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8014     } else if (BO->getOpcode() == Instruction::Or) {
8015       if (Inverse)
8016         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8017                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8018     }
8019   }
8020 
8021   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8022   if (!ICI) return false;
8023 
8024   // Now that we found a conditional branch that dominates the loop or controls
8025   // the loop latch. Check to see if it is the comparison we are looking for.
8026   ICmpInst::Predicate FoundPred;
8027   if (Inverse)
8028     FoundPred = ICI->getInversePredicate();
8029   else
8030     FoundPred = ICI->getPredicate();
8031 
8032   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8033   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8034 
8035   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8036 }
8037 
8038 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8039                                     const SCEV *RHS,
8040                                     ICmpInst::Predicate FoundPred,
8041                                     const SCEV *FoundLHS,
8042                                     const SCEV *FoundRHS) {
8043   // Balance the types.
8044   if (getTypeSizeInBits(LHS->getType()) <
8045       getTypeSizeInBits(FoundLHS->getType())) {
8046     if (CmpInst::isSigned(Pred)) {
8047       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8048       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8049     } else {
8050       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8051       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8052     }
8053   } else if (getTypeSizeInBits(LHS->getType()) >
8054       getTypeSizeInBits(FoundLHS->getType())) {
8055     if (CmpInst::isSigned(FoundPred)) {
8056       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8057       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8058     } else {
8059       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8060       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8061     }
8062   }
8063 
8064   // Canonicalize the query to match the way instcombine will have
8065   // canonicalized the comparison.
8066   if (SimplifyICmpOperands(Pred, LHS, RHS))
8067     if (LHS == RHS)
8068       return CmpInst::isTrueWhenEqual(Pred);
8069   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8070     if (FoundLHS == FoundRHS)
8071       return CmpInst::isFalseWhenEqual(FoundPred);
8072 
8073   // Check to see if we can make the LHS or RHS match.
8074   if (LHS == FoundRHS || RHS == FoundLHS) {
8075     if (isa<SCEVConstant>(RHS)) {
8076       std::swap(FoundLHS, FoundRHS);
8077       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8078     } else {
8079       std::swap(LHS, RHS);
8080       Pred = ICmpInst::getSwappedPredicate(Pred);
8081     }
8082   }
8083 
8084   // Check whether the found predicate is the same as the desired predicate.
8085   if (FoundPred == Pred)
8086     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8087 
8088   // Check whether swapping the found predicate makes it the same as the
8089   // desired predicate.
8090   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8091     if (isa<SCEVConstant>(RHS))
8092       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8093     else
8094       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8095                                    RHS, LHS, FoundLHS, FoundRHS);
8096   }
8097 
8098   // Unsigned comparison is the same as signed comparison when both the operands
8099   // are non-negative.
8100   if (CmpInst::isUnsigned(FoundPred) &&
8101       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8102       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8103     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8104 
8105   // Check if we can make progress by sharpening ranges.
8106   if (FoundPred == ICmpInst::ICMP_NE &&
8107       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8108 
8109     const SCEVConstant *C = nullptr;
8110     const SCEV *V = nullptr;
8111 
8112     if (isa<SCEVConstant>(FoundLHS)) {
8113       C = cast<SCEVConstant>(FoundLHS);
8114       V = FoundRHS;
8115     } else {
8116       C = cast<SCEVConstant>(FoundRHS);
8117       V = FoundLHS;
8118     }
8119 
8120     // The guarding predicate tells us that C != V. If the known range
8121     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8122     // range we consider has to correspond to same signedness as the
8123     // predicate we're interested in folding.
8124 
8125     APInt Min = ICmpInst::isSigned(Pred) ?
8126         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8127 
8128     if (Min == C->getAPInt()) {
8129       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8130       // This is true even if (Min + 1) wraps around -- in case of
8131       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8132 
8133       APInt SharperMin = Min + 1;
8134 
8135       switch (Pred) {
8136         case ICmpInst::ICMP_SGE:
8137         case ICmpInst::ICMP_UGE:
8138           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8139           // RHS, we're done.
8140           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8141                                     getConstant(SharperMin)))
8142             return true;
8143 
8144         case ICmpInst::ICMP_SGT:
8145         case ICmpInst::ICMP_UGT:
8146           // We know from the range information that (V `Pred` Min ||
8147           // V == Min).  We know from the guarding condition that !(V
8148           // == Min).  This gives us
8149           //
8150           //       V `Pred` Min || V == Min && !(V == Min)
8151           //   =>  V `Pred` Min
8152           //
8153           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8154 
8155           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8156             return true;
8157 
8158         default:
8159           // No change
8160           break;
8161       }
8162     }
8163   }
8164 
8165   // Check whether the actual condition is beyond sufficient.
8166   if (FoundPred == ICmpInst::ICMP_EQ)
8167     if (ICmpInst::isTrueWhenEqual(Pred))
8168       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8169         return true;
8170   if (Pred == ICmpInst::ICMP_NE)
8171     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8172       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8173         return true;
8174 
8175   // Otherwise assume the worst.
8176   return false;
8177 }
8178 
8179 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8180                                      const SCEV *&L, const SCEV *&R,
8181                                      SCEV::NoWrapFlags &Flags) {
8182   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8183   if (!AE || AE->getNumOperands() != 2)
8184     return false;
8185 
8186   L = AE->getOperand(0);
8187   R = AE->getOperand(1);
8188   Flags = AE->getNoWrapFlags();
8189   return true;
8190 }
8191 
8192 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8193                                                            const SCEV *Less) {
8194   // We avoid subtracting expressions here because this function is usually
8195   // fairly deep in the call stack (i.e. is called many times).
8196 
8197   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8198     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8199     const auto *MAR = cast<SCEVAddRecExpr>(More);
8200 
8201     if (LAR->getLoop() != MAR->getLoop())
8202       return None;
8203 
8204     // We look at affine expressions only; not for correctness but to keep
8205     // getStepRecurrence cheap.
8206     if (!LAR->isAffine() || !MAR->isAffine())
8207       return None;
8208 
8209     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8210       return None;
8211 
8212     Less = LAR->getStart();
8213     More = MAR->getStart();
8214 
8215     // fall through
8216   }
8217 
8218   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8219     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8220     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8221     return M - L;
8222   }
8223 
8224   const SCEV *L, *R;
8225   SCEV::NoWrapFlags Flags;
8226   if (splitBinaryAdd(Less, L, R, Flags))
8227     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8228       if (R == More)
8229         return -(LC->getAPInt());
8230 
8231   if (splitBinaryAdd(More, L, R, Flags))
8232     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8233       if (R == Less)
8234         return LC->getAPInt();
8235 
8236   return None;
8237 }
8238 
8239 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8240     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8241     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8242   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8243     return false;
8244 
8245   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8246   if (!AddRecLHS)
8247     return false;
8248 
8249   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8250   if (!AddRecFoundLHS)
8251     return false;
8252 
8253   // We'd like to let SCEV reason about control dependencies, so we constrain
8254   // both the inequalities to be about add recurrences on the same loop.  This
8255   // way we can use isLoopEntryGuardedByCond later.
8256 
8257   const Loop *L = AddRecFoundLHS->getLoop();
8258   if (L != AddRecLHS->getLoop())
8259     return false;
8260 
8261   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8262   //
8263   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8264   //                                                                  ... (2)
8265   //
8266   // Informal proof for (2), assuming (1) [*]:
8267   //
8268   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8269   //
8270   // Then
8271   //
8272   //       FoundLHS s< FoundRHS s< INT_MIN - C
8273   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8274   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8275   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8276   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8277   // <=>  FoundLHS + C s< FoundRHS + C
8278   //
8279   // [*]: (1) can be proved by ruling out overflow.
8280   //
8281   // [**]: This can be proved by analyzing all the four possibilities:
8282   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8283   //    (A s>= 0, B s>= 0).
8284   //
8285   // Note:
8286   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8287   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8288   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8289   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8290   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8291   // C)".
8292 
8293   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8294   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8295   if (!LDiff || !RDiff || *LDiff != *RDiff)
8296     return false;
8297 
8298   if (LDiff->isMinValue())
8299     return true;
8300 
8301   APInt FoundRHSLimit;
8302 
8303   if (Pred == CmpInst::ICMP_ULT) {
8304     FoundRHSLimit = -(*RDiff);
8305   } else {
8306     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8307     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8308   }
8309 
8310   // Try to prove (1) or (2), as needed.
8311   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8312                                   getConstant(FoundRHSLimit));
8313 }
8314 
8315 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8316                                             const SCEV *LHS, const SCEV *RHS,
8317                                             const SCEV *FoundLHS,
8318                                             const SCEV *FoundRHS) {
8319   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8320     return true;
8321 
8322   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8323     return true;
8324 
8325   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8326                                      FoundLHS, FoundRHS) ||
8327          // ~x < ~y --> x > y
8328          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8329                                      getNotSCEV(FoundRHS),
8330                                      getNotSCEV(FoundLHS));
8331 }
8332 
8333 
8334 /// If Expr computes ~A, return A else return nullptr
8335 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8336   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8337   if (!Add || Add->getNumOperands() != 2 ||
8338       !Add->getOperand(0)->isAllOnesValue())
8339     return nullptr;
8340 
8341   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8342   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8343       !AddRHS->getOperand(0)->isAllOnesValue())
8344     return nullptr;
8345 
8346   return AddRHS->getOperand(1);
8347 }
8348 
8349 
8350 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8351 template<typename MaxExprType>
8352 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8353                               const SCEV *Candidate) {
8354   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8355   if (!MaxExpr) return false;
8356 
8357   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8358 }
8359 
8360 
8361 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8362 template<typename MaxExprType>
8363 static bool IsMinConsistingOf(ScalarEvolution &SE,
8364                               const SCEV *MaybeMinExpr,
8365                               const SCEV *Candidate) {
8366   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8367   if (!MaybeMaxExpr)
8368     return false;
8369 
8370   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8371 }
8372 
8373 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8374                                            ICmpInst::Predicate Pred,
8375                                            const SCEV *LHS, const SCEV *RHS) {
8376 
8377   // If both sides are affine addrecs for the same loop, with equal
8378   // steps, and we know the recurrences don't wrap, then we only
8379   // need to check the predicate on the starting values.
8380 
8381   if (!ICmpInst::isRelational(Pred))
8382     return false;
8383 
8384   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8385   if (!LAR)
8386     return false;
8387   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8388   if (!RAR)
8389     return false;
8390   if (LAR->getLoop() != RAR->getLoop())
8391     return false;
8392   if (!LAR->isAffine() || !RAR->isAffine())
8393     return false;
8394 
8395   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8396     return false;
8397 
8398   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8399                          SCEV::FlagNSW : SCEV::FlagNUW;
8400   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8401     return false;
8402 
8403   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8404 }
8405 
8406 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8407 /// expression?
8408 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8409                                         ICmpInst::Predicate Pred,
8410                                         const SCEV *LHS, const SCEV *RHS) {
8411   switch (Pred) {
8412   default:
8413     return false;
8414 
8415   case ICmpInst::ICMP_SGE:
8416     std::swap(LHS, RHS);
8417     LLVM_FALLTHROUGH;
8418   case ICmpInst::ICMP_SLE:
8419     return
8420       // min(A, ...) <= A
8421       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8422       // A <= max(A, ...)
8423       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8424 
8425   case ICmpInst::ICMP_UGE:
8426     std::swap(LHS, RHS);
8427     LLVM_FALLTHROUGH;
8428   case ICmpInst::ICMP_ULE:
8429     return
8430       // min(A, ...) <= A
8431       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8432       // A <= max(A, ...)
8433       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8434   }
8435 
8436   llvm_unreachable("covered switch fell through?!");
8437 }
8438 
8439 bool
8440 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8441                                              const SCEV *LHS, const SCEV *RHS,
8442                                              const SCEV *FoundLHS,
8443                                              const SCEV *FoundRHS) {
8444   auto IsKnownPredicateFull =
8445       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8446     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8447            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8448            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8449            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8450   };
8451 
8452   switch (Pred) {
8453   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8454   case ICmpInst::ICMP_EQ:
8455   case ICmpInst::ICMP_NE:
8456     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8457       return true;
8458     break;
8459   case ICmpInst::ICMP_SLT:
8460   case ICmpInst::ICMP_SLE:
8461     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8462         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8463       return true;
8464     break;
8465   case ICmpInst::ICMP_SGT:
8466   case ICmpInst::ICMP_SGE:
8467     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8468         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8469       return true;
8470     break;
8471   case ICmpInst::ICMP_ULT:
8472   case ICmpInst::ICMP_ULE:
8473     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8474         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8475       return true;
8476     break;
8477   case ICmpInst::ICMP_UGT:
8478   case ICmpInst::ICMP_UGE:
8479     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8480         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8481       return true;
8482     break;
8483   }
8484 
8485   return false;
8486 }
8487 
8488 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8489                                                      const SCEV *LHS,
8490                                                      const SCEV *RHS,
8491                                                      const SCEV *FoundLHS,
8492                                                      const SCEV *FoundRHS) {
8493   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8494     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8495     // reduce the compile time impact of this optimization.
8496     return false;
8497 
8498   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8499   if (!Addend)
8500     return false;
8501 
8502   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8503 
8504   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8505   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8506   ConstantRange FoundLHSRange =
8507       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8508 
8509   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8510   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8511 
8512   // We can also compute the range of values for `LHS` that satisfy the
8513   // consequent, "`LHS` `Pred` `RHS`":
8514   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8515   ConstantRange SatisfyingLHSRange =
8516       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8517 
8518   // The antecedent implies the consequent if every value of `LHS` that
8519   // satisfies the antecedent also satisfies the consequent.
8520   return SatisfyingLHSRange.contains(LHSRange);
8521 }
8522 
8523 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8524                                          bool IsSigned, bool NoWrap) {
8525   assert(isKnownPositive(Stride) && "Positive stride expected!");
8526 
8527   if (NoWrap) return false;
8528 
8529   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8530   const SCEV *One = getOne(Stride->getType());
8531 
8532   if (IsSigned) {
8533     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8534     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8535     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8536                                 .getSignedMax();
8537 
8538     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8539     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8540   }
8541 
8542   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8543   APInt MaxValue = APInt::getMaxValue(BitWidth);
8544   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8545                               .getUnsignedMax();
8546 
8547   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8548   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8549 }
8550 
8551 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8552                                          bool IsSigned, bool NoWrap) {
8553   if (NoWrap) return false;
8554 
8555   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8556   const SCEV *One = getOne(Stride->getType());
8557 
8558   if (IsSigned) {
8559     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8560     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8561     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8562                                .getSignedMax();
8563 
8564     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8565     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8566   }
8567 
8568   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8569   APInt MinValue = APInt::getMinValue(BitWidth);
8570   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8571                             .getUnsignedMax();
8572 
8573   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8574   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8575 }
8576 
8577 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8578                                             bool Equality) {
8579   const SCEV *One = getOne(Step->getType());
8580   Delta = Equality ? getAddExpr(Delta, Step)
8581                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8582   return getUDivExpr(Delta, Step);
8583 }
8584 
8585 ScalarEvolution::ExitLimit
8586 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8587                                   const Loop *L, bool IsSigned,
8588                                   bool ControlsExit, bool AllowPredicates) {
8589   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8590   // We handle only IV < Invariant
8591   if (!isLoopInvariant(RHS, L))
8592     return getCouldNotCompute();
8593 
8594   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8595   bool PredicatedIV = false;
8596 
8597   if (!IV && AllowPredicates) {
8598     // Try to make this an AddRec using runtime tests, in the first X
8599     // iterations of this loop, where X is the SCEV expression found by the
8600     // algorithm below.
8601     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8602     PredicatedIV = true;
8603   }
8604 
8605   // Avoid weird loops
8606   if (!IV || IV->getLoop() != L || !IV->isAffine())
8607     return getCouldNotCompute();
8608 
8609   bool NoWrap = ControlsExit &&
8610                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8611 
8612   const SCEV *Stride = IV->getStepRecurrence(*this);
8613 
8614   bool PositiveStride = isKnownPositive(Stride);
8615 
8616   // Avoid negative or zero stride values.
8617   if (!PositiveStride) {
8618     // We can compute the correct backedge taken count for loops with unknown
8619     // strides if we can prove that the loop is not an infinite loop with side
8620     // effects. Here's the loop structure we are trying to handle -
8621     //
8622     // i = start
8623     // do {
8624     //   A[i] = i;
8625     //   i += s;
8626     // } while (i < end);
8627     //
8628     // The backedge taken count for such loops is evaluated as -
8629     // (max(end, start + stride) - start - 1) /u stride
8630     //
8631     // The additional preconditions that we need to check to prove correctness
8632     // of the above formula is as follows -
8633     //
8634     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8635     //    NoWrap flag).
8636     // b) loop is single exit with no side effects.
8637     //
8638     //
8639     // Precondition a) implies that if the stride is negative, this is a single
8640     // trip loop. The backedge taken count formula reduces to zero in this case.
8641     //
8642     // Precondition b) implies that the unknown stride cannot be zero otherwise
8643     // we have UB.
8644     //
8645     // The positive stride case is the same as isKnownPositive(Stride) returning
8646     // true (original behavior of the function).
8647     //
8648     // We want to make sure that the stride is truly unknown as there are edge
8649     // cases where ScalarEvolution propagates no wrap flags to the
8650     // post-increment/decrement IV even though the increment/decrement operation
8651     // itself is wrapping. The computed backedge taken count may be wrong in
8652     // such cases. This is prevented by checking that the stride is not known to
8653     // be either positive or non-positive. For example, no wrap flags are
8654     // propagated to the post-increment IV of this loop with a trip count of 2 -
8655     //
8656     // unsigned char i;
8657     // for(i=127; i<128; i+=129)
8658     //   A[i] = i;
8659     //
8660     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8661         !loopHasNoSideEffects(L))
8662       return getCouldNotCompute();
8663 
8664   } else if (!Stride->isOne() &&
8665              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8666     // Avoid proven overflow cases: this will ensure that the backedge taken
8667     // count will not generate any unsigned overflow. Relaxed no-overflow
8668     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8669     // undefined behaviors like the case of C language.
8670     return getCouldNotCompute();
8671 
8672   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8673                                       : ICmpInst::ICMP_ULT;
8674   const SCEV *Start = IV->getStart();
8675   const SCEV *End = RHS;
8676   // If the backedge is taken at least once, then it will be taken
8677   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8678   // is the LHS value of the less-than comparison the first time it is evaluated
8679   // and End is the RHS.
8680   const SCEV *BECountIfBackedgeTaken =
8681     computeBECount(getMinusSCEV(End, Start), Stride, false);
8682   // If the loop entry is guarded by the result of the backedge test of the
8683   // first loop iteration, then we know the backedge will be taken at least
8684   // once and so the backedge taken count is as above. If not then we use the
8685   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8686   // as if the backedge is taken at least once max(End,Start) is End and so the
8687   // result is as above, and if not max(End,Start) is Start so we get a backedge
8688   // count of zero.
8689   const SCEV *BECount;
8690   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8691     BECount = BECountIfBackedgeTaken;
8692   else {
8693     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
8694     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8695   }
8696 
8697   const SCEV *MaxBECount;
8698   if (isa<SCEVConstant>(BECount))
8699     MaxBECount = BECount;
8700   else if (isa<SCEVConstant>(BECountIfBackedgeTaken))
8701     // If we know exactly how many times the backedge will be taken if it's
8702     // taken at least once, then the backedge count will either be that or
8703     // zero.
8704     MaxBECount = BECountIfBackedgeTaken;
8705   else {
8706     // Calculate the maximum backedge count based on the range of values
8707     // permitted by Start, End, and Stride.
8708     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8709                               : getUnsignedRange(Start).getUnsignedMin();
8710 
8711     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8712 
8713     APInt StrideForMaxBECount;
8714 
8715     if (PositiveStride)
8716       StrideForMaxBECount =
8717         IsSigned ? getSignedRange(Stride).getSignedMin()
8718                  : getUnsignedRange(Stride).getUnsignedMin();
8719     else
8720       // Using a stride of 1 is safe when computing max backedge taken count for
8721       // a loop with unknown stride.
8722       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8723 
8724     APInt Limit =
8725       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8726                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8727 
8728     // Although End can be a MAX expression we estimate MaxEnd considering only
8729     // the case End = RHS. This is safe because in the other case (End - Start)
8730     // is zero, leading to a zero maximum backedge taken count.
8731     APInt MaxEnd =
8732       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8733                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8734 
8735     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8736                                 getConstant(StrideForMaxBECount), false);
8737   }
8738 
8739   if (isa<SCEVCouldNotCompute>(MaxBECount))
8740     MaxBECount = BECount;
8741 
8742   return ExitLimit(BECount, MaxBECount, Predicates);
8743 }
8744 
8745 ScalarEvolution::ExitLimit
8746 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8747                                      const Loop *L, bool IsSigned,
8748                                      bool ControlsExit, bool AllowPredicates) {
8749   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8750   // We handle only IV > Invariant
8751   if (!isLoopInvariant(RHS, L))
8752     return getCouldNotCompute();
8753 
8754   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8755   if (!IV && AllowPredicates)
8756     // Try to make this an AddRec using runtime tests, in the first X
8757     // iterations of this loop, where X is the SCEV expression found by the
8758     // algorithm below.
8759     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8760 
8761   // Avoid weird loops
8762   if (!IV || IV->getLoop() != L || !IV->isAffine())
8763     return getCouldNotCompute();
8764 
8765   bool NoWrap = ControlsExit &&
8766                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8767 
8768   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8769 
8770   // Avoid negative or zero stride values
8771   if (!isKnownPositive(Stride))
8772     return getCouldNotCompute();
8773 
8774   // Avoid proven overflow cases: this will ensure that the backedge taken count
8775   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8776   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8777   // behaviors like the case of C language.
8778   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8779     return getCouldNotCompute();
8780 
8781   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8782                                       : ICmpInst::ICMP_UGT;
8783 
8784   const SCEV *Start = IV->getStart();
8785   const SCEV *End = RHS;
8786   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8787     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
8788 
8789   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8790 
8791   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8792                             : getUnsignedRange(Start).getUnsignedMax();
8793 
8794   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8795                              : getUnsignedRange(Stride).getUnsignedMin();
8796 
8797   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8798   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8799                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8800 
8801   // Although End can be a MIN expression we estimate MinEnd considering only
8802   // the case End = RHS. This is safe because in the other case (Start - End)
8803   // is zero, leading to a zero maximum backedge taken count.
8804   APInt MinEnd =
8805     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8806              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8807 
8808 
8809   const SCEV *MaxBECount = getCouldNotCompute();
8810   if (isa<SCEVConstant>(BECount))
8811     MaxBECount = BECount;
8812   else
8813     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8814                                 getConstant(MinStride), false);
8815 
8816   if (isa<SCEVCouldNotCompute>(MaxBECount))
8817     MaxBECount = BECount;
8818 
8819   return ExitLimit(BECount, MaxBECount, Predicates);
8820 }
8821 
8822 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
8823                                                     ScalarEvolution &SE) const {
8824   if (Range.isFullSet())  // Infinite loop.
8825     return SE.getCouldNotCompute();
8826 
8827   // If the start is a non-zero constant, shift the range to simplify things.
8828   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8829     if (!SC->getValue()->isZero()) {
8830       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8831       Operands[0] = SE.getZero(SC->getType());
8832       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8833                                              getNoWrapFlags(FlagNW));
8834       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8835         return ShiftedAddRec->getNumIterationsInRange(
8836             Range.subtract(SC->getAPInt()), SE);
8837       // This is strange and shouldn't happen.
8838       return SE.getCouldNotCompute();
8839     }
8840 
8841   // The only time we can solve this is when we have all constant indices.
8842   // Otherwise, we cannot determine the overflow conditions.
8843   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8844     return SE.getCouldNotCompute();
8845 
8846   // Okay at this point we know that all elements of the chrec are constants and
8847   // that the start element is zero.
8848 
8849   // First check to see if the range contains zero.  If not, the first
8850   // iteration exits.
8851   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8852   if (!Range.contains(APInt(BitWidth, 0)))
8853     return SE.getZero(getType());
8854 
8855   if (isAffine()) {
8856     // If this is an affine expression then we have this situation:
8857     //   Solve {0,+,A} in Range  ===  Ax in Range
8858 
8859     // We know that zero is in the range.  If A is positive then we know that
8860     // the upper value of the range must be the first possible exit value.
8861     // If A is negative then the lower of the range is the last possible loop
8862     // value.  Also note that we already checked for a full range.
8863     APInt One(BitWidth,1);
8864     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8865     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8866 
8867     // The exit value should be (End+A)/A.
8868     APInt ExitVal = (End + A).udiv(A);
8869     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8870 
8871     // Evaluate at the exit value.  If we really did fall out of the valid
8872     // range, then we computed our trip count, otherwise wrap around or other
8873     // things must have happened.
8874     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8875     if (Range.contains(Val->getValue()))
8876       return SE.getCouldNotCompute();  // Something strange happened
8877 
8878     // Ensure that the previous value is in the range.  This is a sanity check.
8879     assert(Range.contains(
8880            EvaluateConstantChrecAtConstant(this,
8881            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8882            "Linear scev computation is off in a bad way!");
8883     return SE.getConstant(ExitValue);
8884   } else if (isQuadratic()) {
8885     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8886     // quadratic equation to solve it.  To do this, we must frame our problem in
8887     // terms of figuring out when zero is crossed, instead of when
8888     // Range.getUpper() is crossed.
8889     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8890     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8891     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
8892 
8893     // Next, solve the constructed addrec
8894     if (auto Roots =
8895             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
8896       const SCEVConstant *R1 = Roots->first;
8897       const SCEVConstant *R2 = Roots->second;
8898       // Pick the smallest positive root value.
8899       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8900               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8901         if (!CB->getZExtValue())
8902           std::swap(R1, R2); // R1 is the minimum root now.
8903 
8904         // Make sure the root is not off by one.  The returned iteration should
8905         // not be in the range, but the previous one should be.  When solving
8906         // for "X*X < 5", for example, we should not return a root of 2.
8907         ConstantInt *R1Val =
8908             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
8909         if (Range.contains(R1Val->getValue())) {
8910           // The next iteration must be out of the range...
8911           ConstantInt *NextVal =
8912               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
8913 
8914           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8915           if (!Range.contains(R1Val->getValue()))
8916             return SE.getConstant(NextVal);
8917           return SE.getCouldNotCompute(); // Something strange happened
8918         }
8919 
8920         // If R1 was not in the range, then it is a good return value.  Make
8921         // sure that R1-1 WAS in the range though, just in case.
8922         ConstantInt *NextVal =
8923             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
8924         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8925         if (Range.contains(R1Val->getValue()))
8926           return R1;
8927         return SE.getCouldNotCompute(); // Something strange happened
8928       }
8929     }
8930   }
8931 
8932   return SE.getCouldNotCompute();
8933 }
8934 
8935 namespace {
8936 struct FindUndefs {
8937   bool Found;
8938   FindUndefs() : Found(false) {}
8939 
8940   bool follow(const SCEV *S) {
8941     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8942       if (isa<UndefValue>(C->getValue()))
8943         Found = true;
8944     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8945       if (isa<UndefValue>(C->getValue()))
8946         Found = true;
8947     }
8948 
8949     // Keep looking if we haven't found it yet.
8950     return !Found;
8951   }
8952   bool isDone() const {
8953     // Stop recursion if we have found an undef.
8954     return Found;
8955   }
8956 };
8957 }
8958 
8959 // Return true when S contains at least an undef value.
8960 static inline bool
8961 containsUndefs(const SCEV *S) {
8962   FindUndefs F;
8963   SCEVTraversal<FindUndefs> ST(F);
8964   ST.visitAll(S);
8965 
8966   return F.Found;
8967 }
8968 
8969 namespace {
8970 // Collect all steps of SCEV expressions.
8971 struct SCEVCollectStrides {
8972   ScalarEvolution &SE;
8973   SmallVectorImpl<const SCEV *> &Strides;
8974 
8975   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8976       : SE(SE), Strides(S) {}
8977 
8978   bool follow(const SCEV *S) {
8979     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8980       Strides.push_back(AR->getStepRecurrence(SE));
8981     return true;
8982   }
8983   bool isDone() const { return false; }
8984 };
8985 
8986 // Collect all SCEVUnknown and SCEVMulExpr expressions.
8987 struct SCEVCollectTerms {
8988   SmallVectorImpl<const SCEV *> &Terms;
8989 
8990   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8991       : Terms(T) {}
8992 
8993   bool follow(const SCEV *S) {
8994     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
8995         isa<SCEVSignExtendExpr>(S)) {
8996       if (!containsUndefs(S))
8997         Terms.push_back(S);
8998 
8999       // Stop recursion: once we collected a term, do not walk its operands.
9000       return false;
9001     }
9002 
9003     // Keep looking.
9004     return true;
9005   }
9006   bool isDone() const { return false; }
9007 };
9008 
9009 // Check if a SCEV contains an AddRecExpr.
9010 struct SCEVHasAddRec {
9011   bool &ContainsAddRec;
9012 
9013   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9014    ContainsAddRec = false;
9015   }
9016 
9017   bool follow(const SCEV *S) {
9018     if (isa<SCEVAddRecExpr>(S)) {
9019       ContainsAddRec = true;
9020 
9021       // Stop recursion: once we collected a term, do not walk its operands.
9022       return false;
9023     }
9024 
9025     // Keep looking.
9026     return true;
9027   }
9028   bool isDone() const { return false; }
9029 };
9030 
9031 // Find factors that are multiplied with an expression that (possibly as a
9032 // subexpression) contains an AddRecExpr. In the expression:
9033 //
9034 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9035 //
9036 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9037 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9038 // parameters as they form a product with an induction variable.
9039 //
9040 // This collector expects all array size parameters to be in the same MulExpr.
9041 // It might be necessary to later add support for collecting parameters that are
9042 // spread over different nested MulExpr.
9043 struct SCEVCollectAddRecMultiplies {
9044   SmallVectorImpl<const SCEV *> &Terms;
9045   ScalarEvolution &SE;
9046 
9047   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9048       : Terms(T), SE(SE) {}
9049 
9050   bool follow(const SCEV *S) {
9051     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9052       bool HasAddRec = false;
9053       SmallVector<const SCEV *, 0> Operands;
9054       for (auto Op : Mul->operands()) {
9055         if (isa<SCEVUnknown>(Op)) {
9056           Operands.push_back(Op);
9057         } else {
9058           bool ContainsAddRec;
9059           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9060           visitAll(Op, ContiansAddRec);
9061           HasAddRec |= ContainsAddRec;
9062         }
9063       }
9064       if (Operands.size() == 0)
9065         return true;
9066 
9067       if (!HasAddRec)
9068         return false;
9069 
9070       Terms.push_back(SE.getMulExpr(Operands));
9071       // Stop recursion: once we collected a term, do not walk its operands.
9072       return false;
9073     }
9074 
9075     // Keep looking.
9076     return true;
9077   }
9078   bool isDone() const { return false; }
9079 };
9080 }
9081 
9082 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9083 /// two places:
9084 ///   1) The strides of AddRec expressions.
9085 ///   2) Unknowns that are multiplied with AddRec expressions.
9086 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9087     SmallVectorImpl<const SCEV *> &Terms) {
9088   SmallVector<const SCEV *, 4> Strides;
9089   SCEVCollectStrides StrideCollector(*this, Strides);
9090   visitAll(Expr, StrideCollector);
9091 
9092   DEBUG({
9093       dbgs() << "Strides:\n";
9094       for (const SCEV *S : Strides)
9095         dbgs() << *S << "\n";
9096     });
9097 
9098   for (const SCEV *S : Strides) {
9099     SCEVCollectTerms TermCollector(Terms);
9100     visitAll(S, TermCollector);
9101   }
9102 
9103   DEBUG({
9104       dbgs() << "Terms:\n";
9105       for (const SCEV *T : Terms)
9106         dbgs() << *T << "\n";
9107     });
9108 
9109   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9110   visitAll(Expr, MulCollector);
9111 }
9112 
9113 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9114                                    SmallVectorImpl<const SCEV *> &Terms,
9115                                    SmallVectorImpl<const SCEV *> &Sizes) {
9116   int Last = Terms.size() - 1;
9117   const SCEV *Step = Terms[Last];
9118 
9119   // End of recursion.
9120   if (Last == 0) {
9121     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9122       SmallVector<const SCEV *, 2> Qs;
9123       for (const SCEV *Op : M->operands())
9124         if (!isa<SCEVConstant>(Op))
9125           Qs.push_back(Op);
9126 
9127       Step = SE.getMulExpr(Qs);
9128     }
9129 
9130     Sizes.push_back(Step);
9131     return true;
9132   }
9133 
9134   for (const SCEV *&Term : Terms) {
9135     // Normalize the terms before the next call to findArrayDimensionsRec.
9136     const SCEV *Q, *R;
9137     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9138 
9139     // Bail out when GCD does not evenly divide one of the terms.
9140     if (!R->isZero())
9141       return false;
9142 
9143     Term = Q;
9144   }
9145 
9146   // Remove all SCEVConstants.
9147   Terms.erase(
9148       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9149       Terms.end());
9150 
9151   if (Terms.size() > 0)
9152     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9153       return false;
9154 
9155   Sizes.push_back(Step);
9156   return true;
9157 }
9158 
9159 // Returns true when S contains at least a SCEVUnknown parameter.
9160 static inline bool
9161 containsParameters(const SCEV *S) {
9162   struct FindParameter {
9163     bool FoundParameter;
9164     FindParameter() : FoundParameter(false) {}
9165 
9166     bool follow(const SCEV *S) {
9167       if (isa<SCEVUnknown>(S)) {
9168         FoundParameter = true;
9169         // Stop recursion: we found a parameter.
9170         return false;
9171       }
9172       // Keep looking.
9173       return true;
9174     }
9175     bool isDone() const {
9176       // Stop recursion if we have found a parameter.
9177       return FoundParameter;
9178     }
9179   };
9180 
9181   FindParameter F;
9182   SCEVTraversal<FindParameter> ST(F);
9183   ST.visitAll(S);
9184 
9185   return F.FoundParameter;
9186 }
9187 
9188 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9189 static inline bool
9190 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9191   for (const SCEV *T : Terms)
9192     if (containsParameters(T))
9193       return true;
9194   return false;
9195 }
9196 
9197 // Return the number of product terms in S.
9198 static inline int numberOfTerms(const SCEV *S) {
9199   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9200     return Expr->getNumOperands();
9201   return 1;
9202 }
9203 
9204 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9205   if (isa<SCEVConstant>(T))
9206     return nullptr;
9207 
9208   if (isa<SCEVUnknown>(T))
9209     return T;
9210 
9211   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9212     SmallVector<const SCEV *, 2> Factors;
9213     for (const SCEV *Op : M->operands())
9214       if (!isa<SCEVConstant>(Op))
9215         Factors.push_back(Op);
9216 
9217     return SE.getMulExpr(Factors);
9218   }
9219 
9220   return T;
9221 }
9222 
9223 /// Return the size of an element read or written by Inst.
9224 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9225   Type *Ty;
9226   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9227     Ty = Store->getValueOperand()->getType();
9228   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9229     Ty = Load->getType();
9230   else
9231     return nullptr;
9232 
9233   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9234   return getSizeOfExpr(ETy, Ty);
9235 }
9236 
9237 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9238                                           SmallVectorImpl<const SCEV *> &Sizes,
9239                                           const SCEV *ElementSize) const {
9240   if (Terms.size() < 1 || !ElementSize)
9241     return;
9242 
9243   // Early return when Terms do not contain parameters: we do not delinearize
9244   // non parametric SCEVs.
9245   if (!containsParameters(Terms))
9246     return;
9247 
9248   DEBUG({
9249       dbgs() << "Terms:\n";
9250       for (const SCEV *T : Terms)
9251         dbgs() << *T << "\n";
9252     });
9253 
9254   // Remove duplicates.
9255   std::sort(Terms.begin(), Terms.end());
9256   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9257 
9258   // Put larger terms first.
9259   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9260     return numberOfTerms(LHS) > numberOfTerms(RHS);
9261   });
9262 
9263   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9264 
9265   // Try to divide all terms by the element size. If term is not divisible by
9266   // element size, proceed with the original term.
9267   for (const SCEV *&Term : Terms) {
9268     const SCEV *Q, *R;
9269     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9270     if (!Q->isZero())
9271       Term = Q;
9272   }
9273 
9274   SmallVector<const SCEV *, 4> NewTerms;
9275 
9276   // Remove constant factors.
9277   for (const SCEV *T : Terms)
9278     if (const SCEV *NewT = removeConstantFactors(SE, T))
9279       NewTerms.push_back(NewT);
9280 
9281   DEBUG({
9282       dbgs() << "Terms after sorting:\n";
9283       for (const SCEV *T : NewTerms)
9284         dbgs() << *T << "\n";
9285     });
9286 
9287   if (NewTerms.empty() ||
9288       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9289     Sizes.clear();
9290     return;
9291   }
9292 
9293   // The last element to be pushed into Sizes is the size of an element.
9294   Sizes.push_back(ElementSize);
9295 
9296   DEBUG({
9297       dbgs() << "Sizes:\n";
9298       for (const SCEV *S : Sizes)
9299         dbgs() << *S << "\n";
9300     });
9301 }
9302 
9303 void ScalarEvolution::computeAccessFunctions(
9304     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9305     SmallVectorImpl<const SCEV *> &Sizes) {
9306 
9307   // Early exit in case this SCEV is not an affine multivariate function.
9308   if (Sizes.empty())
9309     return;
9310 
9311   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9312     if (!AR->isAffine())
9313       return;
9314 
9315   const SCEV *Res = Expr;
9316   int Last = Sizes.size() - 1;
9317   for (int i = Last; i >= 0; i--) {
9318     const SCEV *Q, *R;
9319     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9320 
9321     DEBUG({
9322         dbgs() << "Res: " << *Res << "\n";
9323         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9324         dbgs() << "Res divided by Sizes[i]:\n";
9325         dbgs() << "Quotient: " << *Q << "\n";
9326         dbgs() << "Remainder: " << *R << "\n";
9327       });
9328 
9329     Res = Q;
9330 
9331     // Do not record the last subscript corresponding to the size of elements in
9332     // the array.
9333     if (i == Last) {
9334 
9335       // Bail out if the remainder is too complex.
9336       if (isa<SCEVAddRecExpr>(R)) {
9337         Subscripts.clear();
9338         Sizes.clear();
9339         return;
9340       }
9341 
9342       continue;
9343     }
9344 
9345     // Record the access function for the current subscript.
9346     Subscripts.push_back(R);
9347   }
9348 
9349   // Also push in last position the remainder of the last division: it will be
9350   // the access function of the innermost dimension.
9351   Subscripts.push_back(Res);
9352 
9353   std::reverse(Subscripts.begin(), Subscripts.end());
9354 
9355   DEBUG({
9356       dbgs() << "Subscripts:\n";
9357       for (const SCEV *S : Subscripts)
9358         dbgs() << *S << "\n";
9359     });
9360 }
9361 
9362 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9363 /// sizes of an array access. Returns the remainder of the delinearization that
9364 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9365 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9366 /// expressions in the stride and base of a SCEV corresponding to the
9367 /// computation of a GCD (greatest common divisor) of base and stride.  When
9368 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9369 ///
9370 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9371 ///
9372 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9373 ///
9374 ///    for (long i = 0; i < n; i++)
9375 ///      for (long j = 0; j < m; j++)
9376 ///        for (long k = 0; k < o; k++)
9377 ///          A[i][j][k] = 1.0;
9378 ///  }
9379 ///
9380 /// the delinearization input is the following AddRec SCEV:
9381 ///
9382 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9383 ///
9384 /// From this SCEV, we are able to say that the base offset of the access is %A
9385 /// because it appears as an offset that does not divide any of the strides in
9386 /// the loops:
9387 ///
9388 ///  CHECK: Base offset: %A
9389 ///
9390 /// and then SCEV->delinearize determines the size of some of the dimensions of
9391 /// the array as these are the multiples by which the strides are happening:
9392 ///
9393 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9394 ///
9395 /// Note that the outermost dimension remains of UnknownSize because there are
9396 /// no strides that would help identifying the size of the last dimension: when
9397 /// the array has been statically allocated, one could compute the size of that
9398 /// dimension by dividing the overall size of the array by the size of the known
9399 /// dimensions: %m * %o * 8.
9400 ///
9401 /// Finally delinearize provides the access functions for the array reference
9402 /// that does correspond to A[i][j][k] of the above C testcase:
9403 ///
9404 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9405 ///
9406 /// The testcases are checking the output of a function pass:
9407 /// DelinearizationPass that walks through all loads and stores of a function
9408 /// asking for the SCEV of the memory access with respect to all enclosing
9409 /// loops, calling SCEV->delinearize on that and printing the results.
9410 
9411 void ScalarEvolution::delinearize(const SCEV *Expr,
9412                                  SmallVectorImpl<const SCEV *> &Subscripts,
9413                                  SmallVectorImpl<const SCEV *> &Sizes,
9414                                  const SCEV *ElementSize) {
9415   // First step: collect parametric terms.
9416   SmallVector<const SCEV *, 4> Terms;
9417   collectParametricTerms(Expr, Terms);
9418 
9419   if (Terms.empty())
9420     return;
9421 
9422   // Second step: find subscript sizes.
9423   findArrayDimensions(Terms, Sizes, ElementSize);
9424 
9425   if (Sizes.empty())
9426     return;
9427 
9428   // Third step: compute the access functions for each subscript.
9429   computeAccessFunctions(Expr, Subscripts, Sizes);
9430 
9431   if (Subscripts.empty())
9432     return;
9433 
9434   DEBUG({
9435       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9436       dbgs() << "ArrayDecl[UnknownSize]";
9437       for (const SCEV *S : Sizes)
9438         dbgs() << "[" << *S << "]";
9439 
9440       dbgs() << "\nArrayRef";
9441       for (const SCEV *S : Subscripts)
9442         dbgs() << "[" << *S << "]";
9443       dbgs() << "\n";
9444     });
9445 }
9446 
9447 //===----------------------------------------------------------------------===//
9448 //                   SCEVCallbackVH Class Implementation
9449 //===----------------------------------------------------------------------===//
9450 
9451 void ScalarEvolution::SCEVCallbackVH::deleted() {
9452   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9453   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9454     SE->ConstantEvolutionLoopExitValue.erase(PN);
9455   SE->eraseValueFromMap(getValPtr());
9456   // this now dangles!
9457 }
9458 
9459 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9460   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9461 
9462   // Forget all the expressions associated with users of the old value,
9463   // so that future queries will recompute the expressions using the new
9464   // value.
9465   Value *Old = getValPtr();
9466   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9467   SmallPtrSet<User *, 8> Visited;
9468   while (!Worklist.empty()) {
9469     User *U = Worklist.pop_back_val();
9470     // Deleting the Old value will cause this to dangle. Postpone
9471     // that until everything else is done.
9472     if (U == Old)
9473       continue;
9474     if (!Visited.insert(U).second)
9475       continue;
9476     if (PHINode *PN = dyn_cast<PHINode>(U))
9477       SE->ConstantEvolutionLoopExitValue.erase(PN);
9478     SE->eraseValueFromMap(U);
9479     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9480   }
9481   // Delete the Old value.
9482   if (PHINode *PN = dyn_cast<PHINode>(Old))
9483     SE->ConstantEvolutionLoopExitValue.erase(PN);
9484   SE->eraseValueFromMap(Old);
9485   // this now dangles!
9486 }
9487 
9488 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9489   : CallbackVH(V), SE(se) {}
9490 
9491 //===----------------------------------------------------------------------===//
9492 //                   ScalarEvolution Class Implementation
9493 //===----------------------------------------------------------------------===//
9494 
9495 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9496                                  AssumptionCache &AC, DominatorTree &DT,
9497                                  LoopInfo &LI)
9498     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9499       CouldNotCompute(new SCEVCouldNotCompute()),
9500       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9501       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9502       FirstUnknown(nullptr) {
9503 
9504   // To use guards for proving predicates, we need to scan every instruction in
9505   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9506   // time if the IR does not actually contain any calls to
9507   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9508   //
9509   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9510   // to _add_ guards to the module when there weren't any before, and wants
9511   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9512   // efficient in lieu of being smart in that rather obscure case.
9513 
9514   auto *GuardDecl = F.getParent()->getFunction(
9515       Intrinsic::getName(Intrinsic::experimental_guard));
9516   HasGuards = GuardDecl && !GuardDecl->use_empty();
9517 }
9518 
9519 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9520     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9521       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9522       ValueExprMap(std::move(Arg.ValueExprMap)),
9523       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9524       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9525       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9526       PredicatedBackedgeTakenCounts(
9527           std::move(Arg.PredicatedBackedgeTakenCounts)),
9528       ConstantEvolutionLoopExitValue(
9529           std::move(Arg.ConstantEvolutionLoopExitValue)),
9530       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9531       LoopDispositions(std::move(Arg.LoopDispositions)),
9532       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9533       BlockDispositions(std::move(Arg.BlockDispositions)),
9534       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9535       SignedRanges(std::move(Arg.SignedRanges)),
9536       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9537       UniquePreds(std::move(Arg.UniquePreds)),
9538       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9539       FirstUnknown(Arg.FirstUnknown) {
9540   Arg.FirstUnknown = nullptr;
9541 }
9542 
9543 ScalarEvolution::~ScalarEvolution() {
9544   // Iterate through all the SCEVUnknown instances and call their
9545   // destructors, so that they release their references to their values.
9546   for (SCEVUnknown *U = FirstUnknown; U;) {
9547     SCEVUnknown *Tmp = U;
9548     U = U->Next;
9549     Tmp->~SCEVUnknown();
9550   }
9551   FirstUnknown = nullptr;
9552 
9553   ExprValueMap.clear();
9554   ValueExprMap.clear();
9555   HasRecMap.clear();
9556 
9557   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9558   // that a loop had multiple computable exits.
9559   for (auto &BTCI : BackedgeTakenCounts)
9560     BTCI.second.clear();
9561   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9562     BTCI.second.clear();
9563 
9564   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9565   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9566   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9567 }
9568 
9569 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9570   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9571 }
9572 
9573 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9574                           const Loop *L) {
9575   // Print all inner loops first
9576   for (Loop *I : *L)
9577     PrintLoopInfo(OS, SE, I);
9578 
9579   OS << "Loop ";
9580   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9581   OS << ": ";
9582 
9583   SmallVector<BasicBlock *, 8> ExitBlocks;
9584   L->getExitBlocks(ExitBlocks);
9585   if (ExitBlocks.size() != 1)
9586     OS << "<multiple exits> ";
9587 
9588   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9589     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9590   } else {
9591     OS << "Unpredictable backedge-taken count. ";
9592   }
9593 
9594   OS << "\n"
9595         "Loop ";
9596   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9597   OS << ": ";
9598 
9599   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9600     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9601   } else {
9602     OS << "Unpredictable max backedge-taken count. ";
9603   }
9604 
9605   OS << "\n"
9606         "Loop ";
9607   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9608   OS << ": ";
9609 
9610   SCEVUnionPredicate Pred;
9611   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9612   if (!isa<SCEVCouldNotCompute>(PBT)) {
9613     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9614     OS << " Predicates:\n";
9615     Pred.print(OS, 4);
9616   } else {
9617     OS << "Unpredictable predicated backedge-taken count. ";
9618   }
9619   OS << "\n";
9620 }
9621 
9622 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9623   switch (LD) {
9624   case ScalarEvolution::LoopVariant:
9625     return "Variant";
9626   case ScalarEvolution::LoopInvariant:
9627     return "Invariant";
9628   case ScalarEvolution::LoopComputable:
9629     return "Computable";
9630   }
9631   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9632 }
9633 
9634 void ScalarEvolution::print(raw_ostream &OS) const {
9635   // ScalarEvolution's implementation of the print method is to print
9636   // out SCEV values of all instructions that are interesting. Doing
9637   // this potentially causes it to create new SCEV objects though,
9638   // which technically conflicts with the const qualifier. This isn't
9639   // observable from outside the class though, so casting away the
9640   // const isn't dangerous.
9641   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9642 
9643   OS << "Classifying expressions for: ";
9644   F.printAsOperand(OS, /*PrintType=*/false);
9645   OS << "\n";
9646   for (Instruction &I : instructions(F))
9647     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9648       OS << I << '\n';
9649       OS << "  -->  ";
9650       const SCEV *SV = SE.getSCEV(&I);
9651       SV->print(OS);
9652       if (!isa<SCEVCouldNotCompute>(SV)) {
9653         OS << " U: ";
9654         SE.getUnsignedRange(SV).print(OS);
9655         OS << " S: ";
9656         SE.getSignedRange(SV).print(OS);
9657       }
9658 
9659       const Loop *L = LI.getLoopFor(I.getParent());
9660 
9661       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9662       if (AtUse != SV) {
9663         OS << "  -->  ";
9664         AtUse->print(OS);
9665         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9666           OS << " U: ";
9667           SE.getUnsignedRange(AtUse).print(OS);
9668           OS << " S: ";
9669           SE.getSignedRange(AtUse).print(OS);
9670         }
9671       }
9672 
9673       if (L) {
9674         OS << "\t\t" "Exits: ";
9675         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9676         if (!SE.isLoopInvariant(ExitValue, L)) {
9677           OS << "<<Unknown>>";
9678         } else {
9679           OS << *ExitValue;
9680         }
9681 
9682         bool First = true;
9683         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9684           if (First) {
9685             OS << "\t\t" "LoopDispositions: { ";
9686             First = false;
9687           } else {
9688             OS << ", ";
9689           }
9690 
9691           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9692           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9693         }
9694 
9695         for (auto *InnerL : depth_first(L)) {
9696           if (InnerL == L)
9697             continue;
9698           if (First) {
9699             OS << "\t\t" "LoopDispositions: { ";
9700             First = false;
9701           } else {
9702             OS << ", ";
9703           }
9704 
9705           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9706           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9707         }
9708 
9709         OS << " }";
9710       }
9711 
9712       OS << "\n";
9713     }
9714 
9715   OS << "Determining loop execution counts for: ";
9716   F.printAsOperand(OS, /*PrintType=*/false);
9717   OS << "\n";
9718   for (Loop *I : LI)
9719     PrintLoopInfo(OS, &SE, I);
9720 }
9721 
9722 ScalarEvolution::LoopDisposition
9723 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9724   auto &Values = LoopDispositions[S];
9725   for (auto &V : Values) {
9726     if (V.getPointer() == L)
9727       return V.getInt();
9728   }
9729   Values.emplace_back(L, LoopVariant);
9730   LoopDisposition D = computeLoopDisposition(S, L);
9731   auto &Values2 = LoopDispositions[S];
9732   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9733     if (V.getPointer() == L) {
9734       V.setInt(D);
9735       break;
9736     }
9737   }
9738   return D;
9739 }
9740 
9741 ScalarEvolution::LoopDisposition
9742 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9743   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9744   case scConstant:
9745     return LoopInvariant;
9746   case scTruncate:
9747   case scZeroExtend:
9748   case scSignExtend:
9749     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9750   case scAddRecExpr: {
9751     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9752 
9753     // If L is the addrec's loop, it's computable.
9754     if (AR->getLoop() == L)
9755       return LoopComputable;
9756 
9757     // Add recurrences are never invariant in the function-body (null loop).
9758     if (!L)
9759       return LoopVariant;
9760 
9761     // This recurrence is variant w.r.t. L if L contains AR's loop.
9762     if (L->contains(AR->getLoop()))
9763       return LoopVariant;
9764 
9765     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9766     if (AR->getLoop()->contains(L))
9767       return LoopInvariant;
9768 
9769     // This recurrence is variant w.r.t. L if any of its operands
9770     // are variant.
9771     for (auto *Op : AR->operands())
9772       if (!isLoopInvariant(Op, L))
9773         return LoopVariant;
9774 
9775     // Otherwise it's loop-invariant.
9776     return LoopInvariant;
9777   }
9778   case scAddExpr:
9779   case scMulExpr:
9780   case scUMaxExpr:
9781   case scSMaxExpr: {
9782     bool HasVarying = false;
9783     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9784       LoopDisposition D = getLoopDisposition(Op, L);
9785       if (D == LoopVariant)
9786         return LoopVariant;
9787       if (D == LoopComputable)
9788         HasVarying = true;
9789     }
9790     return HasVarying ? LoopComputable : LoopInvariant;
9791   }
9792   case scUDivExpr: {
9793     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9794     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9795     if (LD == LoopVariant)
9796       return LoopVariant;
9797     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9798     if (RD == LoopVariant)
9799       return LoopVariant;
9800     return (LD == LoopInvariant && RD == LoopInvariant) ?
9801            LoopInvariant : LoopComputable;
9802   }
9803   case scUnknown:
9804     // All non-instruction values are loop invariant.  All instructions are loop
9805     // invariant if they are not contained in the specified loop.
9806     // Instructions are never considered invariant in the function body
9807     // (null loop) because they are defined within the "loop".
9808     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9809       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9810     return LoopInvariant;
9811   case scCouldNotCompute:
9812     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9813   }
9814   llvm_unreachable("Unknown SCEV kind!");
9815 }
9816 
9817 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9818   return getLoopDisposition(S, L) == LoopInvariant;
9819 }
9820 
9821 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9822   return getLoopDisposition(S, L) == LoopComputable;
9823 }
9824 
9825 ScalarEvolution::BlockDisposition
9826 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9827   auto &Values = BlockDispositions[S];
9828   for (auto &V : Values) {
9829     if (V.getPointer() == BB)
9830       return V.getInt();
9831   }
9832   Values.emplace_back(BB, DoesNotDominateBlock);
9833   BlockDisposition D = computeBlockDisposition(S, BB);
9834   auto &Values2 = BlockDispositions[S];
9835   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9836     if (V.getPointer() == BB) {
9837       V.setInt(D);
9838       break;
9839     }
9840   }
9841   return D;
9842 }
9843 
9844 ScalarEvolution::BlockDisposition
9845 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9846   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9847   case scConstant:
9848     return ProperlyDominatesBlock;
9849   case scTruncate:
9850   case scZeroExtend:
9851   case scSignExtend:
9852     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9853   case scAddRecExpr: {
9854     // This uses a "dominates" query instead of "properly dominates" query
9855     // to test for proper dominance too, because the instruction which
9856     // produces the addrec's value is a PHI, and a PHI effectively properly
9857     // dominates its entire containing block.
9858     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9859     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9860       return DoesNotDominateBlock;
9861 
9862     // Fall through into SCEVNAryExpr handling.
9863     LLVM_FALLTHROUGH;
9864   }
9865   case scAddExpr:
9866   case scMulExpr:
9867   case scUMaxExpr:
9868   case scSMaxExpr: {
9869     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9870     bool Proper = true;
9871     for (const SCEV *NAryOp : NAry->operands()) {
9872       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9873       if (D == DoesNotDominateBlock)
9874         return DoesNotDominateBlock;
9875       if (D == DominatesBlock)
9876         Proper = false;
9877     }
9878     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9879   }
9880   case scUDivExpr: {
9881     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9882     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9883     BlockDisposition LD = getBlockDisposition(LHS, BB);
9884     if (LD == DoesNotDominateBlock)
9885       return DoesNotDominateBlock;
9886     BlockDisposition RD = getBlockDisposition(RHS, BB);
9887     if (RD == DoesNotDominateBlock)
9888       return DoesNotDominateBlock;
9889     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9890       ProperlyDominatesBlock : DominatesBlock;
9891   }
9892   case scUnknown:
9893     if (Instruction *I =
9894           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9895       if (I->getParent() == BB)
9896         return DominatesBlock;
9897       if (DT.properlyDominates(I->getParent(), BB))
9898         return ProperlyDominatesBlock;
9899       return DoesNotDominateBlock;
9900     }
9901     return ProperlyDominatesBlock;
9902   case scCouldNotCompute:
9903     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9904   }
9905   llvm_unreachable("Unknown SCEV kind!");
9906 }
9907 
9908 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9909   return getBlockDisposition(S, BB) >= DominatesBlock;
9910 }
9911 
9912 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9913   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9914 }
9915 
9916 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9917   // Search for a SCEV expression node within an expression tree.
9918   // Implements SCEVTraversal::Visitor.
9919   struct SCEVSearch {
9920     const SCEV *Node;
9921     bool IsFound;
9922 
9923     SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9924 
9925     bool follow(const SCEV *S) {
9926       IsFound |= (S == Node);
9927       return !IsFound;
9928     }
9929     bool isDone() const { return IsFound; }
9930   };
9931 
9932   SCEVSearch Search(Op);
9933   visitAll(S, Search);
9934   return Search.IsFound;
9935 }
9936 
9937 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9938   ValuesAtScopes.erase(S);
9939   LoopDispositions.erase(S);
9940   BlockDispositions.erase(S);
9941   UnsignedRanges.erase(S);
9942   SignedRanges.erase(S);
9943   ExprValueMap.erase(S);
9944   HasRecMap.erase(S);
9945 
9946   auto RemoveSCEVFromBackedgeMap =
9947       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9948         for (auto I = Map.begin(), E = Map.end(); I != E;) {
9949           BackedgeTakenInfo &BEInfo = I->second;
9950           if (BEInfo.hasOperand(S, this)) {
9951             BEInfo.clear();
9952             Map.erase(I++);
9953           } else
9954             ++I;
9955         }
9956       };
9957 
9958   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9959   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
9960 }
9961 
9962 typedef DenseMap<const Loop *, std::string> VerifyMap;
9963 
9964 /// replaceSubString - Replaces all occurrences of From in Str with To.
9965 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9966   size_t Pos = 0;
9967   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9968     Str.replace(Pos, From.size(), To.data(), To.size());
9969     Pos += To.size();
9970   }
9971 }
9972 
9973 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9974 static void
9975 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9976   std::string &S = Map[L];
9977   if (S.empty()) {
9978     raw_string_ostream OS(S);
9979     SE.getBackedgeTakenCount(L)->print(OS);
9980 
9981     // false and 0 are semantically equivalent. This can happen in dead loops.
9982     replaceSubString(OS.str(), "false", "0");
9983     // Remove wrap flags, their use in SCEV is highly fragile.
9984     // FIXME: Remove this when SCEV gets smarter about them.
9985     replaceSubString(OS.str(), "<nw>", "");
9986     replaceSubString(OS.str(), "<nsw>", "");
9987     replaceSubString(OS.str(), "<nuw>", "");
9988   }
9989 
9990   for (auto *R : reverse(*L))
9991     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
9992 }
9993 
9994 void ScalarEvolution::verify() const {
9995   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9996 
9997   // Gather stringified backedge taken counts for all loops using SCEV's caches.
9998   // FIXME: It would be much better to store actual values instead of strings,
9999   //        but SCEV pointers will change if we drop the caches.
10000   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
10001   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10002     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10003 
10004   // Gather stringified backedge taken counts for all loops using a fresh
10005   // ScalarEvolution object.
10006   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10007   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10008     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10009 
10010   // Now compare whether they're the same with and without caches. This allows
10011   // verifying that no pass changed the cache.
10012   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10013          "New loops suddenly appeared!");
10014 
10015   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10016                            OldE = BackedgeDumpsOld.end(),
10017                            NewI = BackedgeDumpsNew.begin();
10018        OldI != OldE; ++OldI, ++NewI) {
10019     assert(OldI->first == NewI->first && "Loop order changed!");
10020 
10021     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10022     // changes.
10023     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10024     // means that a pass is buggy or SCEV has to learn a new pattern but is
10025     // usually not harmful.
10026     if (OldI->second != NewI->second &&
10027         OldI->second.find("undef") == std::string::npos &&
10028         NewI->second.find("undef") == std::string::npos &&
10029         OldI->second != "***COULDNOTCOMPUTE***" &&
10030         NewI->second != "***COULDNOTCOMPUTE***") {
10031       dbgs() << "SCEVValidator: SCEV for loop '"
10032              << OldI->first->getHeader()->getName()
10033              << "' changed from '" << OldI->second
10034              << "' to '" << NewI->second << "'!\n";
10035       std::abort();
10036     }
10037   }
10038 
10039   // TODO: Verify more things.
10040 }
10041 
10042 char ScalarEvolutionAnalysis::PassID;
10043 
10044 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10045                                              FunctionAnalysisManager &AM) {
10046   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10047                          AM.getResult<AssumptionAnalysis>(F),
10048                          AM.getResult<DominatorTreeAnalysis>(F),
10049                          AM.getResult<LoopAnalysis>(F));
10050 }
10051 
10052 PreservedAnalyses
10053 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10054   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10055   return PreservedAnalyses::all();
10056 }
10057 
10058 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10059                       "Scalar Evolution Analysis", false, true)
10060 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10061 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10062 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10063 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10064 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10065                     "Scalar Evolution Analysis", false, true)
10066 char ScalarEvolutionWrapperPass::ID = 0;
10067 
10068 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10069   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10070 }
10071 
10072 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10073   SE.reset(new ScalarEvolution(
10074       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10075       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10076       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10077       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10078   return false;
10079 }
10080 
10081 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10082 
10083 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10084   SE->print(OS);
10085 }
10086 
10087 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10088   if (!VerifySCEV)
10089     return;
10090 
10091   SE->verify();
10092 }
10093 
10094 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10095   AU.setPreservesAll();
10096   AU.addRequiredTransitive<AssumptionCacheTracker>();
10097   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10098   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10099   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10100 }
10101 
10102 const SCEVPredicate *
10103 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10104                                    const SCEVConstant *RHS) {
10105   FoldingSetNodeID ID;
10106   // Unique this node based on the arguments
10107   ID.AddInteger(SCEVPredicate::P_Equal);
10108   ID.AddPointer(LHS);
10109   ID.AddPointer(RHS);
10110   void *IP = nullptr;
10111   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10112     return S;
10113   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10114       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10115   UniquePreds.InsertNode(Eq, IP);
10116   return Eq;
10117 }
10118 
10119 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10120     const SCEVAddRecExpr *AR,
10121     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10122   FoldingSetNodeID ID;
10123   // Unique this node based on the arguments
10124   ID.AddInteger(SCEVPredicate::P_Wrap);
10125   ID.AddPointer(AR);
10126   ID.AddInteger(AddedFlags);
10127   void *IP = nullptr;
10128   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10129     return S;
10130   auto *OF = new (SCEVAllocator)
10131       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10132   UniquePreds.InsertNode(OF, IP);
10133   return OF;
10134 }
10135 
10136 namespace {
10137 
10138 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10139 public:
10140   /// Rewrites \p S in the context of a loop L and the SCEV predication
10141   /// infrastructure.
10142   ///
10143   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10144   /// equivalences present in \p Pred.
10145   ///
10146   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10147   /// \p NewPreds such that the result will be an AddRecExpr.
10148   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10149                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10150                              SCEVUnionPredicate *Pred) {
10151     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10152     return Rewriter.visit(S);
10153   }
10154 
10155   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10156                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10157                         SCEVUnionPredicate *Pred)
10158       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10159 
10160   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10161     if (Pred) {
10162       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10163       for (auto *Pred : ExprPreds)
10164         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10165           if (IPred->getLHS() == Expr)
10166             return IPred->getRHS();
10167     }
10168 
10169     return Expr;
10170   }
10171 
10172   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10173     const SCEV *Operand = visit(Expr->getOperand());
10174     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10175     if (AR && AR->getLoop() == L && AR->isAffine()) {
10176       // This couldn't be folded because the operand didn't have the nuw
10177       // flag. Add the nusw flag as an assumption that we could make.
10178       const SCEV *Step = AR->getStepRecurrence(SE);
10179       Type *Ty = Expr->getType();
10180       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10181         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10182                                 SE.getSignExtendExpr(Step, Ty), L,
10183                                 AR->getNoWrapFlags());
10184     }
10185     return SE.getZeroExtendExpr(Operand, Expr->getType());
10186   }
10187 
10188   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10189     const SCEV *Operand = visit(Expr->getOperand());
10190     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10191     if (AR && AR->getLoop() == L && AR->isAffine()) {
10192       // This couldn't be folded because the operand didn't have the nsw
10193       // flag. Add the nssw flag as an assumption that we could make.
10194       const SCEV *Step = AR->getStepRecurrence(SE);
10195       Type *Ty = Expr->getType();
10196       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10197         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10198                                 SE.getSignExtendExpr(Step, Ty), L,
10199                                 AR->getNoWrapFlags());
10200     }
10201     return SE.getSignExtendExpr(Operand, Expr->getType());
10202   }
10203 
10204 private:
10205   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10206                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10207     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10208     if (!NewPreds) {
10209       // Check if we've already made this assumption.
10210       return Pred && Pred->implies(A);
10211     }
10212     NewPreds->insert(A);
10213     return true;
10214   }
10215 
10216   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10217   SCEVUnionPredicate *Pred;
10218   const Loop *L;
10219 };
10220 } // end anonymous namespace
10221 
10222 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10223                                                    SCEVUnionPredicate &Preds) {
10224   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10225 }
10226 
10227 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10228     const SCEV *S, const Loop *L,
10229     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10230 
10231   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10232   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10233   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10234 
10235   if (!AddRec)
10236     return nullptr;
10237 
10238   // Since the transformation was successful, we can now transfer the SCEV
10239   // predicates.
10240   for (auto *P : TransformPreds)
10241     Preds.insert(P);
10242 
10243   return AddRec;
10244 }
10245 
10246 /// SCEV predicates
10247 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10248                              SCEVPredicateKind Kind)
10249     : FastID(ID), Kind(Kind) {}
10250 
10251 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10252                                        const SCEVUnknown *LHS,
10253                                        const SCEVConstant *RHS)
10254     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10255 
10256 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10257   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10258 
10259   if (!Op)
10260     return false;
10261 
10262   return Op->LHS == LHS && Op->RHS == RHS;
10263 }
10264 
10265 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10266 
10267 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10268 
10269 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10270   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10271 }
10272 
10273 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10274                                      const SCEVAddRecExpr *AR,
10275                                      IncrementWrapFlags Flags)
10276     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10277 
10278 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10279 
10280 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10281   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10282 
10283   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10284 }
10285 
10286 bool SCEVWrapPredicate::isAlwaysTrue() const {
10287   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10288   IncrementWrapFlags IFlags = Flags;
10289 
10290   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10291     IFlags = clearFlags(IFlags, IncrementNSSW);
10292 
10293   return IFlags == IncrementAnyWrap;
10294 }
10295 
10296 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10297   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10298   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10299     OS << "<nusw>";
10300   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10301     OS << "<nssw>";
10302   OS << "\n";
10303 }
10304 
10305 SCEVWrapPredicate::IncrementWrapFlags
10306 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10307                                    ScalarEvolution &SE) {
10308   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10309   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10310 
10311   // We can safely transfer the NSW flag as NSSW.
10312   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10313     ImpliedFlags = IncrementNSSW;
10314 
10315   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10316     // If the increment is positive, the SCEV NUW flag will also imply the
10317     // WrapPredicate NUSW flag.
10318     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10319       if (Step->getValue()->getValue().isNonNegative())
10320         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10321   }
10322 
10323   return ImpliedFlags;
10324 }
10325 
10326 /// Union predicates don't get cached so create a dummy set ID for it.
10327 SCEVUnionPredicate::SCEVUnionPredicate()
10328     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10329 
10330 bool SCEVUnionPredicate::isAlwaysTrue() const {
10331   return all_of(Preds,
10332                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10333 }
10334 
10335 ArrayRef<const SCEVPredicate *>
10336 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10337   auto I = SCEVToPreds.find(Expr);
10338   if (I == SCEVToPreds.end())
10339     return ArrayRef<const SCEVPredicate *>();
10340   return I->second;
10341 }
10342 
10343 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10344   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10345     return all_of(Set->Preds,
10346                   [this](const SCEVPredicate *I) { return this->implies(I); });
10347 
10348   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10349   if (ScevPredsIt == SCEVToPreds.end())
10350     return false;
10351   auto &SCEVPreds = ScevPredsIt->second;
10352 
10353   return any_of(SCEVPreds,
10354                 [N](const SCEVPredicate *I) { return I->implies(N); });
10355 }
10356 
10357 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10358 
10359 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10360   for (auto Pred : Preds)
10361     Pred->print(OS, Depth);
10362 }
10363 
10364 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10365   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10366     for (auto Pred : Set->Preds)
10367       add(Pred);
10368     return;
10369   }
10370 
10371   if (implies(N))
10372     return;
10373 
10374   const SCEV *Key = N->getExpr();
10375   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10376                 " associated expression!");
10377 
10378   SCEVToPreds[Key].push_back(N);
10379   Preds.push_back(N);
10380 }
10381 
10382 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10383                                                      Loop &L)
10384     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10385 
10386 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10387   const SCEV *Expr = SE.getSCEV(V);
10388   RewriteEntry &Entry = RewriteMap[Expr];
10389 
10390   // If we already have an entry and the version matches, return it.
10391   if (Entry.second && Generation == Entry.first)
10392     return Entry.second;
10393 
10394   // We found an entry but it's stale. Rewrite the stale entry
10395   // acording to the current predicate.
10396   if (Entry.second)
10397     Expr = Entry.second;
10398 
10399   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10400   Entry = {Generation, NewSCEV};
10401 
10402   return NewSCEV;
10403 }
10404 
10405 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10406   if (!BackedgeCount) {
10407     SCEVUnionPredicate BackedgePred;
10408     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10409     addPredicate(BackedgePred);
10410   }
10411   return BackedgeCount;
10412 }
10413 
10414 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10415   if (Preds.implies(&Pred))
10416     return;
10417   Preds.add(&Pred);
10418   updateGeneration();
10419 }
10420 
10421 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10422   return Preds;
10423 }
10424 
10425 void PredicatedScalarEvolution::updateGeneration() {
10426   // If the generation number wrapped recompute everything.
10427   if (++Generation == 0) {
10428     for (auto &II : RewriteMap) {
10429       const SCEV *Rewritten = II.second.second;
10430       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10431     }
10432   }
10433 }
10434 
10435 void PredicatedScalarEvolution::setNoOverflow(
10436     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10437   const SCEV *Expr = getSCEV(V);
10438   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10439 
10440   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10441 
10442   // Clear the statically implied flags.
10443   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10444   addPredicate(*SE.getWrapPredicate(AR, Flags));
10445 
10446   auto II = FlagsMap.insert({V, Flags});
10447   if (!II.second)
10448     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10449 }
10450 
10451 bool PredicatedScalarEvolution::hasNoOverflow(
10452     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10453   const SCEV *Expr = getSCEV(V);
10454   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10455 
10456   Flags = SCEVWrapPredicate::clearFlags(
10457       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10458 
10459   auto II = FlagsMap.find(V);
10460 
10461   if (II != FlagsMap.end())
10462     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10463 
10464   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10465 }
10466 
10467 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10468   const SCEV *Expr = this->getSCEV(V);
10469   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10470   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10471 
10472   if (!New)
10473     return nullptr;
10474 
10475   for (auto *P : NewPreds)
10476     Preds.add(P);
10477 
10478   updateGeneration();
10479   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10480   return New;
10481 }
10482 
10483 PredicatedScalarEvolution::PredicatedScalarEvolution(
10484     const PredicatedScalarEvolution &Init)
10485     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10486       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10487   for (const auto &I : Init.FlagsMap)
10488     FlagsMap.insert(I);
10489 }
10490 
10491 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10492   // For each block.
10493   for (auto *BB : L.getBlocks())
10494     for (auto &I : *BB) {
10495       if (!SE.isSCEVable(I.getType()))
10496         continue;
10497 
10498       auto *Expr = SE.getSCEV(&I);
10499       auto II = RewriteMap.find(Expr);
10500 
10501       if (II == RewriteMap.end())
10502         continue;
10503 
10504       // Don't print things that are not interesting.
10505       if (II->second.second == Expr)
10506         continue;
10507 
10508       OS.indent(Depth) << "[PSE]" << I << ":\n";
10509       OS.indent(Depth + 2) << *Expr << "\n";
10510       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10511     }
10512 }
10513