xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision d3488c6060efc5cc554c15d30917c25acf98eeaa)
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/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/Analysis/AssumptionCache.h"
67 #include "llvm/Analysis/ConstantFolding.h"
68 #include "llvm/Analysis/InstructionSimplify.h"
69 #include "llvm/Analysis/LoopInfo.h"
70 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
71 #include "llvm/Analysis/TargetLibraryInfo.h"
72 #include "llvm/Analysis/ValueTracking.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/GetElementPtrTypeIterator.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalVariable.h"
81 #include "llvm/IR/InstIterator.h"
82 #include "llvm/IR/Instructions.h"
83 #include "llvm/IR/LLVMContext.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/Support/CommandLine.h"
88 #include "llvm/Support/Debug.h"
89 #include "llvm/Support/ErrorHandling.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Support/SaveAndRestore.h"
93 #include <algorithm>
94 using namespace llvm;
95 
96 #define DEBUG_TYPE "scalar-evolution"
97 
98 STATISTIC(NumArrayLenItCounts,
99           "Number of trip counts computed with array length");
100 STATISTIC(NumTripCountsComputed,
101           "Number of loops with predictable loop counts");
102 STATISTIC(NumTripCountsNotComputed,
103           "Number of loops without predictable loop counts");
104 STATISTIC(NumBruteForceTripCountsComputed,
105           "Number of loops with trip counts computed by force");
106 
107 static cl::opt<unsigned>
108 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
109                         cl::desc("Maximum number of iterations SCEV will "
110                                  "symbolically execute a constant "
111                                  "derived loop"),
112                         cl::init(100));
113 
114 // FIXME: Enable this with XDEBUG when the test suite is clean.
115 static cl::opt<bool>
116 VerifySCEV("verify-scev",
117            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
118 static cl::opt<bool>
119     VerifySCEVMap("verify-scev-maps",
120                   cl::desc("Verify no dangling value in ScalarEvolution's"
121                            "ExprValueMap (slow)"));
122 
123 //===----------------------------------------------------------------------===//
124 //                           SCEV class definitions
125 //===----------------------------------------------------------------------===//
126 
127 //===----------------------------------------------------------------------===//
128 // Implementation of the SCEV class.
129 //
130 
131 LLVM_DUMP_METHOD
132 void SCEV::dump() const {
133   print(dbgs());
134   dbgs() << '\n';
135 }
136 
137 void SCEV::print(raw_ostream &OS) const {
138   switch (static_cast<SCEVTypes>(getSCEVType())) {
139   case scConstant:
140     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
141     return;
142   case scTruncate: {
143     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
144     const SCEV *Op = Trunc->getOperand();
145     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
146        << *Trunc->getType() << ")";
147     return;
148   }
149   case scZeroExtend: {
150     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
151     const SCEV *Op = ZExt->getOperand();
152     OS << "(zext " << *Op->getType() << " " << *Op << " to "
153        << *ZExt->getType() << ")";
154     return;
155   }
156   case scSignExtend: {
157     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
158     const SCEV *Op = SExt->getOperand();
159     OS << "(sext " << *Op->getType() << " " << *Op << " to "
160        << *SExt->getType() << ")";
161     return;
162   }
163   case scAddRecExpr: {
164     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
165     OS << "{" << *AR->getOperand(0);
166     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
167       OS << ",+," << *AR->getOperand(i);
168     OS << "}<";
169     if (AR->hasNoUnsignedWrap())
170       OS << "nuw><";
171     if (AR->hasNoSignedWrap())
172       OS << "nsw><";
173     if (AR->hasNoSelfWrap() &&
174         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
175       OS << "nw><";
176     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
177     OS << ">";
178     return;
179   }
180   case scAddExpr:
181   case scMulExpr:
182   case scUMaxExpr:
183   case scSMaxExpr: {
184     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
185     const char *OpStr = nullptr;
186     switch (NAry->getSCEVType()) {
187     case scAddExpr: OpStr = " + "; break;
188     case scMulExpr: OpStr = " * "; break;
189     case scUMaxExpr: OpStr = " umax "; break;
190     case scSMaxExpr: OpStr = " smax "; break;
191     }
192     OS << "(";
193     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
194          I != E; ++I) {
195       OS << **I;
196       if (std::next(I) != E)
197         OS << OpStr;
198     }
199     OS << ")";
200     switch (NAry->getSCEVType()) {
201     case scAddExpr:
202     case scMulExpr:
203       if (NAry->hasNoUnsignedWrap())
204         OS << "<nuw>";
205       if (NAry->hasNoSignedWrap())
206         OS << "<nsw>";
207     }
208     return;
209   }
210   case scUDivExpr: {
211     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
212     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
213     return;
214   }
215   case scUnknown: {
216     const SCEVUnknown *U = cast<SCEVUnknown>(this);
217     Type *AllocTy;
218     if (U->isSizeOf(AllocTy)) {
219       OS << "sizeof(" << *AllocTy << ")";
220       return;
221     }
222     if (U->isAlignOf(AllocTy)) {
223       OS << "alignof(" << *AllocTy << ")";
224       return;
225     }
226 
227     Type *CTy;
228     Constant *FieldNo;
229     if (U->isOffsetOf(CTy, FieldNo)) {
230       OS << "offsetof(" << *CTy << ", ";
231       FieldNo->printAsOperand(OS, false);
232       OS << ")";
233       return;
234     }
235 
236     // Otherwise just print it normally.
237     U->getValue()->printAsOperand(OS, false);
238     return;
239   }
240   case scCouldNotCompute:
241     OS << "***COULDNOTCOMPUTE***";
242     return;
243   }
244   llvm_unreachable("Unknown SCEV kind!");
245 }
246 
247 Type *SCEV::getType() const {
248   switch (static_cast<SCEVTypes>(getSCEVType())) {
249   case scConstant:
250     return cast<SCEVConstant>(this)->getType();
251   case scTruncate:
252   case scZeroExtend:
253   case scSignExtend:
254     return cast<SCEVCastExpr>(this)->getType();
255   case scAddRecExpr:
256   case scMulExpr:
257   case scUMaxExpr:
258   case scSMaxExpr:
259     return cast<SCEVNAryExpr>(this)->getType();
260   case scAddExpr:
261     return cast<SCEVAddExpr>(this)->getType();
262   case scUDivExpr:
263     return cast<SCEVUDivExpr>(this)->getType();
264   case scUnknown:
265     return cast<SCEVUnknown>(this)->getType();
266   case scCouldNotCompute:
267     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
268   }
269   llvm_unreachable("Unknown SCEV kind!");
270 }
271 
272 bool SCEV::isZero() const {
273   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
274     return SC->getValue()->isZero();
275   return false;
276 }
277 
278 bool SCEV::isOne() const {
279   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
280     return SC->getValue()->isOne();
281   return false;
282 }
283 
284 bool SCEV::isAllOnesValue() const {
285   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286     return SC->getValue()->isAllOnesValue();
287   return false;
288 }
289 
290 /// isNonConstantNegative - Return true if the specified scev is negated, but
291 /// not a constant.
292 bool SCEV::isNonConstantNegative() const {
293   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
294   if (!Mul) return false;
295 
296   // If there is a constant factor, it will be first.
297   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
298   if (!SC) return false;
299 
300   // Return true if the value is negative, this matches things like (-42 * V).
301   return SC->getAPInt().isNegative();
302 }
303 
304 SCEVCouldNotCompute::SCEVCouldNotCompute() :
305   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
306 
307 bool SCEVCouldNotCompute::classof(const SCEV *S) {
308   return S->getSCEVType() == scCouldNotCompute;
309 }
310 
311 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
312   FoldingSetNodeID ID;
313   ID.AddInteger(scConstant);
314   ID.AddPointer(V);
315   void *IP = nullptr;
316   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
317   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
318   UniqueSCEVs.InsertNode(S, IP);
319   return S;
320 }
321 
322 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
323   return getConstant(ConstantInt::get(getContext(), Val));
324 }
325 
326 const SCEV *
327 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
328   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
329   return getConstant(ConstantInt::get(ITy, V, isSigned));
330 }
331 
332 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
333                            unsigned SCEVTy, const SCEV *op, Type *ty)
334   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
335 
336 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
337                                    const SCEV *op, Type *ty)
338   : SCEVCastExpr(ID, scTruncate, op, ty) {
339   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
340          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
341          "Cannot truncate non-integer value!");
342 }
343 
344 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
345                                        const SCEV *op, Type *ty)
346   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
347   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
348          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
349          "Cannot zero extend non-integer value!");
350 }
351 
352 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
353                                        const SCEV *op, Type *ty)
354   : SCEVCastExpr(ID, scSignExtend, op, ty) {
355   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
356          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
357          "Cannot sign extend non-integer value!");
358 }
359 
360 void SCEVUnknown::deleted() {
361   // Clear this SCEVUnknown from various maps.
362   SE->forgetMemoizedResults(this);
363 
364   // Remove this SCEVUnknown from the uniquing map.
365   SE->UniqueSCEVs.RemoveNode(this);
366 
367   // Release the value.
368   setValPtr(nullptr);
369 }
370 
371 void SCEVUnknown::allUsesReplacedWith(Value *New) {
372   // Clear this SCEVUnknown from various maps.
373   SE->forgetMemoizedResults(this);
374 
375   // Remove this SCEVUnknown from the uniquing map.
376   SE->UniqueSCEVs.RemoveNode(this);
377 
378   // Update this SCEVUnknown to point to the new value. This is needed
379   // because there may still be outstanding SCEVs which still point to
380   // this SCEVUnknown.
381   setValPtr(New);
382 }
383 
384 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
385   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
386     if (VCE->getOpcode() == Instruction::PtrToInt)
387       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
388         if (CE->getOpcode() == Instruction::GetElementPtr &&
389             CE->getOperand(0)->isNullValue() &&
390             CE->getNumOperands() == 2)
391           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
392             if (CI->isOne()) {
393               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
394                                  ->getElementType();
395               return true;
396             }
397 
398   return false;
399 }
400 
401 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
402   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
403     if (VCE->getOpcode() == Instruction::PtrToInt)
404       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
405         if (CE->getOpcode() == Instruction::GetElementPtr &&
406             CE->getOperand(0)->isNullValue()) {
407           Type *Ty =
408             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
409           if (StructType *STy = dyn_cast<StructType>(Ty))
410             if (!STy->isPacked() &&
411                 CE->getNumOperands() == 3 &&
412                 CE->getOperand(1)->isNullValue()) {
413               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
414                 if (CI->isOne() &&
415                     STy->getNumElements() == 2 &&
416                     STy->getElementType(0)->isIntegerTy(1)) {
417                   AllocTy = STy->getElementType(1);
418                   return true;
419                 }
420             }
421         }
422 
423   return false;
424 }
425 
426 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
427   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
428     if (VCE->getOpcode() == Instruction::PtrToInt)
429       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
430         if (CE->getOpcode() == Instruction::GetElementPtr &&
431             CE->getNumOperands() == 3 &&
432             CE->getOperand(0)->isNullValue() &&
433             CE->getOperand(1)->isNullValue()) {
434           Type *Ty =
435             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
436           // Ignore vector types here so that ScalarEvolutionExpander doesn't
437           // emit getelementptrs that index into vectors.
438           if (Ty->isStructTy() || Ty->isArrayTy()) {
439             CTy = Ty;
440             FieldNo = CE->getOperand(2);
441             return true;
442           }
443         }
444 
445   return false;
446 }
447 
448 //===----------------------------------------------------------------------===//
449 //                               SCEV Utilities
450 //===----------------------------------------------------------------------===//
451 
452 namespace {
453 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
454 /// than the complexity of the RHS.  This comparator is used to canonicalize
455 /// expressions.
456 class SCEVComplexityCompare {
457   const LoopInfo *const LI;
458 public:
459   explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
460 
461   // Return true or false if LHS is less than, or at least RHS, respectively.
462   bool operator()(const SCEV *LHS, const SCEV *RHS) const {
463     return compare(LHS, RHS) < 0;
464   }
465 
466   // Return negative, zero, or positive, if LHS is less than, equal to, or
467   // greater than RHS, respectively. A three-way result allows recursive
468   // comparisons to be more efficient.
469   int compare(const SCEV *LHS, const SCEV *RHS) const {
470     // Fast-path: SCEVs are uniqued so we can do a quick equality check.
471     if (LHS == RHS)
472       return 0;
473 
474     // Primarily, sort the SCEVs by their getSCEVType().
475     unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
476     if (LType != RType)
477       return (int)LType - (int)RType;
478 
479     // Aside from the getSCEVType() ordering, the particular ordering
480     // isn't very important except that it's beneficial to be consistent,
481     // so that (a + b) and (b + a) don't end up as different expressions.
482     switch (static_cast<SCEVTypes>(LType)) {
483     case scUnknown: {
484       const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
485       const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
486 
487       // Sort SCEVUnknown values with some loose heuristics. TODO: This is
488       // not as complete as it could be.
489       const Value *LV = LU->getValue(), *RV = RU->getValue();
490 
491       // Order pointer values after integer values. This helps SCEVExpander
492       // form GEPs.
493       bool LIsPointer = LV->getType()->isPointerTy(),
494         RIsPointer = RV->getType()->isPointerTy();
495       if (LIsPointer != RIsPointer)
496         return (int)LIsPointer - (int)RIsPointer;
497 
498       // Compare getValueID values.
499       unsigned LID = LV->getValueID(),
500         RID = RV->getValueID();
501       if (LID != RID)
502         return (int)LID - (int)RID;
503 
504       // Sort arguments by their position.
505       if (const Argument *LA = dyn_cast<Argument>(LV)) {
506         const Argument *RA = cast<Argument>(RV);
507         unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
508         return (int)LArgNo - (int)RArgNo;
509       }
510 
511       // For instructions, compare their loop depth, and their operand
512       // count.  This is pretty loose.
513       if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
514         const Instruction *RInst = cast<Instruction>(RV);
515 
516         // Compare loop depths.
517         const BasicBlock *LParent = LInst->getParent(),
518           *RParent = RInst->getParent();
519         if (LParent != RParent) {
520           unsigned LDepth = LI->getLoopDepth(LParent),
521             RDepth = LI->getLoopDepth(RParent);
522           if (LDepth != RDepth)
523             return (int)LDepth - (int)RDepth;
524         }
525 
526         // Compare the number of operands.
527         unsigned LNumOps = LInst->getNumOperands(),
528           RNumOps = RInst->getNumOperands();
529         return (int)LNumOps - (int)RNumOps;
530       }
531 
532       return 0;
533     }
534 
535     case scConstant: {
536       const SCEVConstant *LC = cast<SCEVConstant>(LHS);
537       const SCEVConstant *RC = cast<SCEVConstant>(RHS);
538 
539       // Compare constant values.
540       const APInt &LA = LC->getAPInt();
541       const APInt &RA = RC->getAPInt();
542       unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
543       if (LBitWidth != RBitWidth)
544         return (int)LBitWidth - (int)RBitWidth;
545       return LA.ult(RA) ? -1 : 1;
546     }
547 
548     case scAddRecExpr: {
549       const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
550       const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
551 
552       // Compare addrec loop depths.
553       const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
554       if (LLoop != RLoop) {
555         unsigned LDepth = LLoop->getLoopDepth(),
556           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 = compare(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 = compare(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 = compare(LC->getLHS(), RC->getLHS());
604       if (X != 0)
605         return X;
606       return compare(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 compare(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 }  // end anonymous namespace
626 
627 /// GroupByComplexity - Given a list of SCEV objects, order them by their
628 /// complexity, and group objects of the same complexity together by value.
629 /// When this routine is finished, we know that any duplicates in the vector are
630 /// consecutive and that complexity is monotonically increasing.
631 ///
632 /// Note that we go take special precautions to ensure that we get deterministic
633 /// results from this routine.  In other words, we don't want the results of
634 /// this to depend on where the addresses of various SCEV objects happened to
635 /// land in memory.
636 ///
637 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
638                               LoopInfo *LI) {
639   if (Ops.size() < 2) return;  // Noop
640   if (Ops.size() == 2) {
641     // This is the common case, which also happens to be trivially simple.
642     // Special case it.
643     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
644     if (SCEVComplexityCompare(LI)(RHS, LHS))
645       std::swap(LHS, RHS);
646     return;
647   }
648 
649   // Do the rough sort by complexity.
650   std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
651 
652   // Now that we are sorted by complexity, group elements of the same
653   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
654   // be extremely short in practice.  Note that we take this approach because we
655   // do not want to depend on the addresses of the objects we are grouping.
656   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
657     const SCEV *S = Ops[i];
658     unsigned Complexity = S->getSCEVType();
659 
660     // If there are any objects of the same complexity and same value as this
661     // one, group them.
662     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
663       if (Ops[j] == S) { // Found a duplicate.
664         // Move it to immediately after i'th element.
665         std::swap(Ops[i+1], Ops[j]);
666         ++i;   // no need to rescan it.
667         if (i == e-2) return;  // Done!
668       }
669     }
670   }
671 }
672 
673 // Returns the size of the SCEV S.
674 static inline int sizeOfSCEV(const SCEV *S) {
675   struct FindSCEVSize {
676     int Size;
677     FindSCEVSize() : Size(0) {}
678 
679     bool follow(const SCEV *S) {
680       ++Size;
681       // Keep looking at all operands of S.
682       return true;
683     }
684     bool isDone() const {
685       return false;
686     }
687   };
688 
689   FindSCEVSize F;
690   SCEVTraversal<FindSCEVSize> ST(F);
691   ST.visitAll(S);
692   return F.Size;
693 }
694 
695 namespace {
696 
697 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
698 public:
699   // Computes the Quotient and Remainder of the division of Numerator by
700   // Denominator.
701   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
702                      const SCEV *Denominator, const SCEV **Quotient,
703                      const SCEV **Remainder) {
704     assert(Numerator && Denominator && "Uninitialized SCEV");
705 
706     SCEVDivision D(SE, Numerator, Denominator);
707 
708     // Check for the trivial case here to avoid having to check for it in the
709     // rest of the code.
710     if (Numerator == Denominator) {
711       *Quotient = D.One;
712       *Remainder = D.Zero;
713       return;
714     }
715 
716     if (Numerator->isZero()) {
717       *Quotient = D.Zero;
718       *Remainder = D.Zero;
719       return;
720     }
721 
722     // A simple case when N/1. The quotient is N.
723     if (Denominator->isOne()) {
724       *Quotient = Numerator;
725       *Remainder = D.Zero;
726       return;
727     }
728 
729     // Split the Denominator when it is a product.
730     if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
731       const SCEV *Q, *R;
732       *Quotient = Numerator;
733       for (const SCEV *Op : T->operands()) {
734         divide(SE, *Quotient, Op, &Q, &R);
735         *Quotient = Q;
736 
737         // Bail out when the Numerator is not divisible by one of the terms of
738         // the Denominator.
739         if (!R->isZero()) {
740           *Quotient = D.Zero;
741           *Remainder = Numerator;
742           return;
743         }
744       }
745       *Remainder = D.Zero;
746       return;
747     }
748 
749     D.visit(Numerator);
750     *Quotient = D.Quotient;
751     *Remainder = D.Remainder;
752   }
753 
754   // Except in the trivial case described above, we do not know how to divide
755   // Expr by Denominator for the following functions with empty implementation.
756   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
757   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
758   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
759   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
760   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
761   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
762   void visitUnknown(const SCEVUnknown *Numerator) {}
763   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
764 
765   void visitConstant(const SCEVConstant *Numerator) {
766     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
767       APInt NumeratorVal = Numerator->getAPInt();
768       APInt DenominatorVal = D->getAPInt();
769       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
770       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
771 
772       if (NumeratorBW > DenominatorBW)
773         DenominatorVal = DenominatorVal.sext(NumeratorBW);
774       else if (NumeratorBW < DenominatorBW)
775         NumeratorVal = NumeratorVal.sext(DenominatorBW);
776 
777       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
778       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
779       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
780       Quotient = SE.getConstant(QuotientVal);
781       Remainder = SE.getConstant(RemainderVal);
782       return;
783     }
784   }
785 
786   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
787     const SCEV *StartQ, *StartR, *StepQ, *StepR;
788     if (!Numerator->isAffine())
789       return cannotDivide(Numerator);
790     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
791     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
792     // Bail out if the types do not match.
793     Type *Ty = Denominator->getType();
794     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
795         Ty != StepQ->getType() || Ty != StepR->getType())
796       return cannotDivide(Numerator);
797     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
798                                 Numerator->getNoWrapFlags());
799     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
800                                  Numerator->getNoWrapFlags());
801   }
802 
803   void visitAddExpr(const SCEVAddExpr *Numerator) {
804     SmallVector<const SCEV *, 2> Qs, Rs;
805     Type *Ty = Denominator->getType();
806 
807     for (const SCEV *Op : Numerator->operands()) {
808       const SCEV *Q, *R;
809       divide(SE, Op, Denominator, &Q, &R);
810 
811       // Bail out if types do not match.
812       if (Ty != Q->getType() || Ty != R->getType())
813         return cannotDivide(Numerator);
814 
815       Qs.push_back(Q);
816       Rs.push_back(R);
817     }
818 
819     if (Qs.size() == 1) {
820       Quotient = Qs[0];
821       Remainder = Rs[0];
822       return;
823     }
824 
825     Quotient = SE.getAddExpr(Qs);
826     Remainder = SE.getAddExpr(Rs);
827   }
828 
829   void visitMulExpr(const SCEVMulExpr *Numerator) {
830     SmallVector<const SCEV *, 2> Qs;
831     Type *Ty = Denominator->getType();
832 
833     bool FoundDenominatorTerm = false;
834     for (const SCEV *Op : Numerator->operands()) {
835       // Bail out if types do not match.
836       if (Ty != Op->getType())
837         return cannotDivide(Numerator);
838 
839       if (FoundDenominatorTerm) {
840         Qs.push_back(Op);
841         continue;
842       }
843 
844       // Check whether Denominator divides one of the product operands.
845       const SCEV *Q, *R;
846       divide(SE, Op, Denominator, &Q, &R);
847       if (!R->isZero()) {
848         Qs.push_back(Op);
849         continue;
850       }
851 
852       // Bail out if types do not match.
853       if (Ty != Q->getType())
854         return cannotDivide(Numerator);
855 
856       FoundDenominatorTerm = true;
857       Qs.push_back(Q);
858     }
859 
860     if (FoundDenominatorTerm) {
861       Remainder = Zero;
862       if (Qs.size() == 1)
863         Quotient = Qs[0];
864       else
865         Quotient = SE.getMulExpr(Qs);
866       return;
867     }
868 
869     if (!isa<SCEVUnknown>(Denominator))
870       return cannotDivide(Numerator);
871 
872     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
873     ValueToValueMap RewriteMap;
874     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
875         cast<SCEVConstant>(Zero)->getValue();
876     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
877 
878     if (Remainder->isZero()) {
879       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
880       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881           cast<SCEVConstant>(One)->getValue();
882       Quotient =
883           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
884       return;
885     }
886 
887     // Quotient is (Numerator - Remainder) divided by Denominator.
888     const SCEV *Q, *R;
889     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
890     // This SCEV does not seem to simplify: fail the division here.
891     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
892       return cannotDivide(Numerator);
893     divide(SE, Diff, Denominator, &Q, &R);
894     if (R != Zero)
895       return cannotDivide(Numerator);
896     Quotient = Q;
897   }
898 
899 private:
900   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
901                const SCEV *Denominator)
902       : SE(S), Denominator(Denominator) {
903     Zero = SE.getZero(Denominator->getType());
904     One = SE.getOne(Denominator->getType());
905 
906     // We generally do not know how to divide Expr by Denominator. We
907     // initialize the division to a "cannot divide" state to simplify the rest
908     // of the code.
909     cannotDivide(Numerator);
910   }
911 
912   // Convenience function for giving up on the division. We set the quotient to
913   // be equal to zero and the remainder to be equal to the numerator.
914   void cannotDivide(const SCEV *Numerator) {
915     Quotient = Zero;
916     Remainder = Numerator;
917   }
918 
919   ScalarEvolution &SE;
920   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
921 };
922 
923 }
924 
925 //===----------------------------------------------------------------------===//
926 //                      Simple SCEV method implementations
927 //===----------------------------------------------------------------------===//
928 
929 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
930 /// 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 /// evaluateAtIteration - Return the value of this chain of recurrences at
1042 /// the specified iteration number.  We can evaluate this recurrence by
1043 /// multiplying each element in the chain by the binomial coefficient
1044 /// corresponding to it.  In other words, we 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         // If the backedge is guarded by a comparison with the pre-inc value
1526         // the addrec is safe. Also, if the entry is guarded by a comparison
1527         // with the start value and the backedge is guarded by a comparison
1528         // with the post-inc value, the addrec is safe.
1529         if (isKnownPositive(Step)) {
1530           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1531                                       getUnsignedRange(Step).getUnsignedMax());
1532           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1533               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1534                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1535                                            AR->getPostIncExpr(*this), N))) {
1536             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1537             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1538             // Return the expression with the addrec on the outside.
1539             return getAddRecExpr(
1540                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1541                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1542           }
1543         } else if (isKnownNegative(Step)) {
1544           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1545                                       getSignedRange(Step).getSignedMin());
1546           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1547               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1548                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1549                                            AR->getPostIncExpr(*this), N))) {
1550             // Cache knowledge of AR NW, which is propagated to this AddRec.
1551             // Negative step causes unsigned wrap, but it still can't self-wrap.
1552             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1553             // Return the expression with the addrec on the outside.
1554             return getAddRecExpr(
1555                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1556                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1557           }
1558         }
1559       }
1560 
1561       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1562         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1563         return getAddRecExpr(
1564             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1565             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1566       }
1567     }
1568 
1569   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1570     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1571     if (SA->hasNoUnsignedWrap()) {
1572       // If the addition does not unsign overflow then we can, by definition,
1573       // commute the zero extension with the addition operation.
1574       SmallVector<const SCEV *, 4> Ops;
1575       for (const auto *Op : SA->operands())
1576         Ops.push_back(getZeroExtendExpr(Op, Ty));
1577       return getAddExpr(Ops, SCEV::FlagNUW);
1578     }
1579   }
1580 
1581   // The cast wasn't folded; create an explicit cast node.
1582   // Recompute the insert position, as it may have been invalidated.
1583   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1584   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1585                                                    Op, Ty);
1586   UniqueSCEVs.InsertNode(S, IP);
1587   return S;
1588 }
1589 
1590 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1591                                                Type *Ty) {
1592   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1593          "This is not an extending conversion!");
1594   assert(isSCEVable(Ty) &&
1595          "This is not a conversion to a SCEVable type!");
1596   Ty = getEffectiveSCEVType(Ty);
1597 
1598   // Fold if the operand is constant.
1599   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1600     return getConstant(
1601       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1602 
1603   // sext(sext(x)) --> sext(x)
1604   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1605     return getSignExtendExpr(SS->getOperand(), Ty);
1606 
1607   // sext(zext(x)) --> zext(x)
1608   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1609     return getZeroExtendExpr(SZ->getOperand(), Ty);
1610 
1611   // Before doing any expensive analysis, check to see if we've already
1612   // computed a SCEV for this Op and Ty.
1613   FoldingSetNodeID ID;
1614   ID.AddInteger(scSignExtend);
1615   ID.AddPointer(Op);
1616   ID.AddPointer(Ty);
1617   void *IP = nullptr;
1618   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1619 
1620   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1621   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1622     // It's possible the bits taken off by the truncate were all sign bits. If
1623     // so, we should be able to simplify this further.
1624     const SCEV *X = ST->getOperand();
1625     ConstantRange CR = getSignedRange(X);
1626     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1627     unsigned NewBits = getTypeSizeInBits(Ty);
1628     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1629             CR.sextOrTrunc(NewBits)))
1630       return getTruncateOrSignExtend(X, Ty);
1631   }
1632 
1633   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1634   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1635     if (SA->getNumOperands() == 2) {
1636       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1637       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1638       if (SMul && SC1) {
1639         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1640           const APInt &C1 = SC1->getAPInt();
1641           const APInt &C2 = SC2->getAPInt();
1642           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1643               C2.ugt(C1) && C2.isPowerOf2())
1644             return getAddExpr(getSignExtendExpr(SC1, Ty),
1645                               getSignExtendExpr(SMul, Ty));
1646         }
1647       }
1648     }
1649 
1650     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1651     if (SA->hasNoSignedWrap()) {
1652       // If the addition does not sign overflow then we can, by definition,
1653       // commute the sign extension with the addition operation.
1654       SmallVector<const SCEV *, 4> Ops;
1655       for (const auto *Op : SA->operands())
1656         Ops.push_back(getSignExtendExpr(Op, Ty));
1657       return getAddExpr(Ops, SCEV::FlagNSW);
1658     }
1659   }
1660   // If the input value is a chrec scev, and we can prove that the value
1661   // did not overflow the old, smaller, value, we can sign extend all of the
1662   // operands (often constants).  This allows analysis of something like
1663   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1664   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1665     if (AR->isAffine()) {
1666       const SCEV *Start = AR->getStart();
1667       const SCEV *Step = AR->getStepRecurrence(*this);
1668       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1669       const Loop *L = AR->getLoop();
1670 
1671       if (!AR->hasNoSignedWrap()) {
1672         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1673         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1674       }
1675 
1676       // If we have special knowledge that this addrec won't overflow,
1677       // we don't need to do any further analysis.
1678       if (AR->hasNoSignedWrap())
1679         return getAddRecExpr(
1680             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1681             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1682 
1683       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1684       // Note that this serves two purposes: It filters out loops that are
1685       // simply not analyzable, and it covers the case where this code is
1686       // being called from within backedge-taken count analysis, such that
1687       // attempting to ask for the backedge-taken count would likely result
1688       // in infinite recursion. In the later case, the analysis code will
1689       // cope with a conservative value, and it will take care to purge
1690       // that value once it has finished.
1691       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1692       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1693         // Manually compute the final value for AR, checking for
1694         // overflow.
1695 
1696         // Check whether the backedge-taken count can be losslessly casted to
1697         // the addrec's type. The count is always unsigned.
1698         const SCEV *CastedMaxBECount =
1699           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1700         const SCEV *RecastedMaxBECount =
1701           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1702         if (MaxBECount == RecastedMaxBECount) {
1703           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1704           // Check whether Start+Step*MaxBECount has no signed overflow.
1705           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1706           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1707           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1708           const SCEV *WideMaxBECount =
1709             getZeroExtendExpr(CastedMaxBECount, WideTy);
1710           const SCEV *OperandExtendedAdd =
1711             getAddExpr(WideStart,
1712                        getMulExpr(WideMaxBECount,
1713                                   getSignExtendExpr(Step, WideTy)));
1714           if (SAdd == OperandExtendedAdd) {
1715             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1716             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1717             // Return the expression with the addrec on the outside.
1718             return getAddRecExpr(
1719                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1720                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1721           }
1722           // Similar to above, only this time treat the step value as unsigned.
1723           // This covers loops that count up with an unsigned step.
1724           OperandExtendedAdd =
1725             getAddExpr(WideStart,
1726                        getMulExpr(WideMaxBECount,
1727                                   getZeroExtendExpr(Step, WideTy)));
1728           if (SAdd == OperandExtendedAdd) {
1729             // If AR wraps around then
1730             //
1731             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1732             // => SAdd != OperandExtendedAdd
1733             //
1734             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1735             // (SAdd == OperandExtendedAdd => AR is NW)
1736 
1737             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1738 
1739             // Return the expression with the addrec on the outside.
1740             return getAddRecExpr(
1741                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1742                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1743           }
1744         }
1745 
1746         // If the backedge is guarded by a comparison with the pre-inc value
1747         // the addrec is safe. Also, if the entry is guarded by a comparison
1748         // with the start value and the backedge is guarded by a comparison
1749         // with the post-inc value, the addrec is safe.
1750         ICmpInst::Predicate Pred;
1751         const SCEV *OverflowLimit =
1752             getSignedOverflowLimitForStep(Step, &Pred, this);
1753         if (OverflowLimit &&
1754             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1755              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1756               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1757                                           OverflowLimit)))) {
1758           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1759           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1760           return getAddRecExpr(
1761               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1762               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1763         }
1764       }
1765       // If Start and Step are constants, check if we can apply this
1766       // transformation:
1767       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1768       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1769       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1770       if (SC1 && SC2) {
1771         const APInt &C1 = SC1->getAPInt();
1772         const APInt &C2 = SC2->getAPInt();
1773         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1774             C2.isPowerOf2()) {
1775           Start = getSignExtendExpr(Start, Ty);
1776           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1777                                             AR->getNoWrapFlags());
1778           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1779         }
1780       }
1781 
1782       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1783         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1784         return getAddRecExpr(
1785             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1786             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1787       }
1788     }
1789 
1790   // If the input value is provably positive and we could not simplify
1791   // away the sext build a zext instead.
1792   if (isKnownNonNegative(Op))
1793     return getZeroExtendExpr(Op, Ty);
1794 
1795   // The cast wasn't folded; create an explicit cast node.
1796   // Recompute the insert position, as it may have been invalidated.
1797   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1798   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1799                                                    Op, Ty);
1800   UniqueSCEVs.InsertNode(S, IP);
1801   return S;
1802 }
1803 
1804 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1805 /// unspecified bits out to the given type.
1806 ///
1807 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1808                                               Type *Ty) {
1809   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1810          "This is not an extending conversion!");
1811   assert(isSCEVable(Ty) &&
1812          "This is not a conversion to a SCEVable type!");
1813   Ty = getEffectiveSCEVType(Ty);
1814 
1815   // Sign-extend negative constants.
1816   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1817     if (SC->getAPInt().isNegative())
1818       return getSignExtendExpr(Op, Ty);
1819 
1820   // Peel off a truncate cast.
1821   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1822     const SCEV *NewOp = T->getOperand();
1823     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1824       return getAnyExtendExpr(NewOp, Ty);
1825     return getTruncateOrNoop(NewOp, Ty);
1826   }
1827 
1828   // Next try a zext cast. If the cast is folded, use it.
1829   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1830   if (!isa<SCEVZeroExtendExpr>(ZExt))
1831     return ZExt;
1832 
1833   // Next try a sext cast. If the cast is folded, use it.
1834   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1835   if (!isa<SCEVSignExtendExpr>(SExt))
1836     return SExt;
1837 
1838   // Force the cast to be folded into the operands of an addrec.
1839   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1840     SmallVector<const SCEV *, 4> Ops;
1841     for (const SCEV *Op : AR->operands())
1842       Ops.push_back(getAnyExtendExpr(Op, Ty));
1843     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1844   }
1845 
1846   // If the expression is obviously signed, use the sext cast value.
1847   if (isa<SCEVSMaxExpr>(Op))
1848     return SExt;
1849 
1850   // Absent any other information, use the zext cast value.
1851   return ZExt;
1852 }
1853 
1854 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1855 /// a list of operands to be added under the given scale, update the given
1856 /// map. This is a helper function for getAddRecExpr. As an example of
1857 /// what it does, given a sequence of operands that would form an add
1858 /// expression like this:
1859 ///
1860 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1861 ///
1862 /// where A and B are constants, update the map with these values:
1863 ///
1864 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1865 ///
1866 /// and add 13 + A*B*29 to AccumulatedConstant.
1867 /// This will allow getAddRecExpr to produce this:
1868 ///
1869 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1870 ///
1871 /// This form often exposes folding opportunities that are hidden in
1872 /// the original operand list.
1873 ///
1874 /// Return true iff it appears that any interesting folding opportunities
1875 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1876 /// the common case where no interesting opportunities are present, and
1877 /// is also used as a check to avoid infinite recursion.
1878 ///
1879 static bool
1880 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1881                              SmallVectorImpl<const SCEV *> &NewOps,
1882                              APInt &AccumulatedConstant,
1883                              const SCEV *const *Ops, size_t NumOperands,
1884                              const APInt &Scale,
1885                              ScalarEvolution &SE) {
1886   bool Interesting = false;
1887 
1888   // Iterate over the add operands. They are sorted, with constants first.
1889   unsigned i = 0;
1890   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1891     ++i;
1892     // Pull a buried constant out to the outside.
1893     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1894       Interesting = true;
1895     AccumulatedConstant += Scale * C->getAPInt();
1896   }
1897 
1898   // Next comes everything else. We're especially interested in multiplies
1899   // here, but they're in the middle, so just visit the rest with one loop.
1900   for (; i != NumOperands; ++i) {
1901     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1902     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1903       APInt NewScale =
1904           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
1905       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1906         // A multiplication of a constant with another add; recurse.
1907         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1908         Interesting |=
1909           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1910                                        Add->op_begin(), Add->getNumOperands(),
1911                                        NewScale, SE);
1912       } else {
1913         // A multiplication of a constant with some other value. Update
1914         // the map.
1915         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1916         const SCEV *Key = SE.getMulExpr(MulOps);
1917         auto Pair = M.insert({Key, NewScale});
1918         if (Pair.second) {
1919           NewOps.push_back(Pair.first->first);
1920         } else {
1921           Pair.first->second += NewScale;
1922           // The map already had an entry for this value, which may indicate
1923           // a folding opportunity.
1924           Interesting = true;
1925         }
1926       }
1927     } else {
1928       // An ordinary operand. Update the map.
1929       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1930           M.insert({Ops[i], Scale});
1931       if (Pair.second) {
1932         NewOps.push_back(Pair.first->first);
1933       } else {
1934         Pair.first->second += Scale;
1935         // The map already had an entry for this value, which may indicate
1936         // a folding opportunity.
1937         Interesting = true;
1938       }
1939     }
1940   }
1941 
1942   return Interesting;
1943 }
1944 
1945 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1946 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
1947 // can't-overflow flags for the operation if possible.
1948 static SCEV::NoWrapFlags
1949 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1950                       const SmallVectorImpl<const SCEV *> &Ops,
1951                       SCEV::NoWrapFlags Flags) {
1952   using namespace std::placeholders;
1953   typedef OverflowingBinaryOperator OBO;
1954 
1955   bool CanAnalyze =
1956       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1957   (void)CanAnalyze;
1958   assert(CanAnalyze && "don't call from other places!");
1959 
1960   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1961   SCEV::NoWrapFlags SignOrUnsignWrap =
1962       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1963 
1964   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1965   auto IsKnownNonNegative = [&](const SCEV *S) {
1966     return SE->isKnownNonNegative(S);
1967   };
1968 
1969   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
1970     Flags =
1971         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1972 
1973   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1974 
1975   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1976       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1977 
1978     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1979     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
1980 
1981     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
1982     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
1983       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1984           Instruction::Add, C, OBO::NoSignedWrap);
1985       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
1986         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
1987     }
1988     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
1989       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1990           Instruction::Add, C, OBO::NoUnsignedWrap);
1991       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
1992         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
1993     }
1994   }
1995 
1996   return Flags;
1997 }
1998 
1999 /// getAddExpr - Get a canonical add expression, or something simpler if
2000 /// possible.
2001 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2002                                         SCEV::NoWrapFlags Flags) {
2003   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2004          "only nuw or nsw allowed");
2005   assert(!Ops.empty() && "Cannot get empty add!");
2006   if (Ops.size() == 1) return Ops[0];
2007 #ifndef NDEBUG
2008   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2009   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2010     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2011            "SCEVAddExpr operand types don't match!");
2012 #endif
2013 
2014   // Sort by complexity, this groups all similar expression types together.
2015   GroupByComplexity(Ops, &LI);
2016 
2017   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2018 
2019   // If there are any constants, fold them together.
2020   unsigned Idx = 0;
2021   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2022     ++Idx;
2023     assert(Idx < Ops.size());
2024     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2025       // We found two constants, fold them together!
2026       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2027       if (Ops.size() == 2) return Ops[0];
2028       Ops.erase(Ops.begin()+1);  // Erase the folded element
2029       LHSC = cast<SCEVConstant>(Ops[0]);
2030     }
2031 
2032     // If we are left with a constant zero being added, strip it off.
2033     if (LHSC->getValue()->isZero()) {
2034       Ops.erase(Ops.begin());
2035       --Idx;
2036     }
2037 
2038     if (Ops.size() == 1) return Ops[0];
2039   }
2040 
2041   // Okay, check to see if the same value occurs in the operand list more than
2042   // once.  If so, merge them together into an multiply expression.  Since we
2043   // sorted the list, these values are required to be adjacent.
2044   Type *Ty = Ops[0]->getType();
2045   bool FoundMatch = false;
2046   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2047     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2048       // Scan ahead to count how many equal operands there are.
2049       unsigned Count = 2;
2050       while (i+Count != e && Ops[i+Count] == Ops[i])
2051         ++Count;
2052       // Merge the values into a multiply.
2053       const SCEV *Scale = getConstant(Ty, Count);
2054       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2055       if (Ops.size() == Count)
2056         return Mul;
2057       Ops[i] = Mul;
2058       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2059       --i; e -= Count - 1;
2060       FoundMatch = true;
2061     }
2062   if (FoundMatch)
2063     return getAddExpr(Ops, Flags);
2064 
2065   // Check for truncates. If all the operands are truncated from the same
2066   // type, see if factoring out the truncate would permit the result to be
2067   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2068   // if the contents of the resulting outer trunc fold to something simple.
2069   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2070     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2071     Type *DstType = Trunc->getType();
2072     Type *SrcType = Trunc->getOperand()->getType();
2073     SmallVector<const SCEV *, 8> LargeOps;
2074     bool Ok = true;
2075     // Check all the operands to see if they can be represented in the
2076     // source type of the truncate.
2077     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2078       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2079         if (T->getOperand()->getType() != SrcType) {
2080           Ok = false;
2081           break;
2082         }
2083         LargeOps.push_back(T->getOperand());
2084       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2085         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2086       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2087         SmallVector<const SCEV *, 8> LargeMulOps;
2088         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2089           if (const SCEVTruncateExpr *T =
2090                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2091             if (T->getOperand()->getType() != SrcType) {
2092               Ok = false;
2093               break;
2094             }
2095             LargeMulOps.push_back(T->getOperand());
2096           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2097             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2098           } else {
2099             Ok = false;
2100             break;
2101           }
2102         }
2103         if (Ok)
2104           LargeOps.push_back(getMulExpr(LargeMulOps));
2105       } else {
2106         Ok = false;
2107         break;
2108       }
2109     }
2110     if (Ok) {
2111       // Evaluate the expression in the larger type.
2112       const SCEV *Fold = getAddExpr(LargeOps, Flags);
2113       // If it folds to something simple, use it. Otherwise, don't.
2114       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2115         return getTruncateExpr(Fold, DstType);
2116     }
2117   }
2118 
2119   // Skip past any other cast SCEVs.
2120   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2121     ++Idx;
2122 
2123   // If there are add operands they would be next.
2124   if (Idx < Ops.size()) {
2125     bool DeletedAdd = false;
2126     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2127       // If we have an add, expand the add operands onto the end of the operands
2128       // list.
2129       Ops.erase(Ops.begin()+Idx);
2130       Ops.append(Add->op_begin(), Add->op_end());
2131       DeletedAdd = true;
2132     }
2133 
2134     // If we deleted at least one add, we added operands to the end of the list,
2135     // and they are not necessarily sorted.  Recurse to resort and resimplify
2136     // any operands we just acquired.
2137     if (DeletedAdd)
2138       return getAddExpr(Ops);
2139   }
2140 
2141   // Skip over the add expression until we get to a multiply.
2142   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2143     ++Idx;
2144 
2145   // Check to see if there are any folding opportunities present with
2146   // operands multiplied by constant values.
2147   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2148     uint64_t BitWidth = getTypeSizeInBits(Ty);
2149     DenseMap<const SCEV *, APInt> M;
2150     SmallVector<const SCEV *, 8> NewOps;
2151     APInt AccumulatedConstant(BitWidth, 0);
2152     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2153                                      Ops.data(), Ops.size(),
2154                                      APInt(BitWidth, 1), *this)) {
2155       struct APIntCompare {
2156         bool operator()(const APInt &LHS, const APInt &RHS) const {
2157           return LHS.ult(RHS);
2158         }
2159       };
2160 
2161       // Some interesting folding opportunity is present, so its worthwhile to
2162       // re-generate the operands list. Group the operands by constant scale,
2163       // to avoid multiplying by the same constant scale multiple times.
2164       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2165       for (const SCEV *NewOp : NewOps)
2166         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2167       // Re-generate the operands list.
2168       Ops.clear();
2169       if (AccumulatedConstant != 0)
2170         Ops.push_back(getConstant(AccumulatedConstant));
2171       for (auto &MulOp : MulOpLists)
2172         if (MulOp.first != 0)
2173           Ops.push_back(getMulExpr(getConstant(MulOp.first),
2174                                    getAddExpr(MulOp.second)));
2175       if (Ops.empty())
2176         return getZero(Ty);
2177       if (Ops.size() == 1)
2178         return Ops[0];
2179       return getAddExpr(Ops);
2180     }
2181   }
2182 
2183   // If we are adding something to a multiply expression, make sure the
2184   // something is not already an operand of the multiply.  If so, merge it into
2185   // the multiply.
2186   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2187     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2188     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2189       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2190       if (isa<SCEVConstant>(MulOpSCEV))
2191         continue;
2192       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2193         if (MulOpSCEV == Ops[AddOp]) {
2194           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2195           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2196           if (Mul->getNumOperands() != 2) {
2197             // If the multiply has more than two operands, we must get the
2198             // Y*Z term.
2199             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2200                                                 Mul->op_begin()+MulOp);
2201             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2202             InnerMul = getMulExpr(MulOps);
2203           }
2204           const SCEV *One = getOne(Ty);
2205           const SCEV *AddOne = getAddExpr(One, InnerMul);
2206           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2207           if (Ops.size() == 2) return OuterMul;
2208           if (AddOp < Idx) {
2209             Ops.erase(Ops.begin()+AddOp);
2210             Ops.erase(Ops.begin()+Idx-1);
2211           } else {
2212             Ops.erase(Ops.begin()+Idx);
2213             Ops.erase(Ops.begin()+AddOp-1);
2214           }
2215           Ops.push_back(OuterMul);
2216           return getAddExpr(Ops);
2217         }
2218 
2219       // Check this multiply against other multiplies being added together.
2220       for (unsigned OtherMulIdx = Idx+1;
2221            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2222            ++OtherMulIdx) {
2223         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2224         // If MulOp occurs in OtherMul, we can fold the two multiplies
2225         // together.
2226         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2227              OMulOp != e; ++OMulOp)
2228           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2229             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2230             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2231             if (Mul->getNumOperands() != 2) {
2232               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2233                                                   Mul->op_begin()+MulOp);
2234               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2235               InnerMul1 = getMulExpr(MulOps);
2236             }
2237             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2238             if (OtherMul->getNumOperands() != 2) {
2239               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2240                                                   OtherMul->op_begin()+OMulOp);
2241               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2242               InnerMul2 = getMulExpr(MulOps);
2243             }
2244             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2245             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2246             if (Ops.size() == 2) return OuterMul;
2247             Ops.erase(Ops.begin()+Idx);
2248             Ops.erase(Ops.begin()+OtherMulIdx-1);
2249             Ops.push_back(OuterMul);
2250             return getAddExpr(Ops);
2251           }
2252       }
2253     }
2254   }
2255 
2256   // If there are any add recurrences in the operands list, see if any other
2257   // added values are loop invariant.  If so, we can fold them into the
2258   // recurrence.
2259   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2260     ++Idx;
2261 
2262   // Scan over all recurrences, trying to fold loop invariants into them.
2263   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2264     // Scan all of the other operands to this add and add them to the vector if
2265     // they are loop invariant w.r.t. the recurrence.
2266     SmallVector<const SCEV *, 8> LIOps;
2267     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2268     const Loop *AddRecLoop = AddRec->getLoop();
2269     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2270       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2271         LIOps.push_back(Ops[i]);
2272         Ops.erase(Ops.begin()+i);
2273         --i; --e;
2274       }
2275 
2276     // If we found some loop invariants, fold them into the recurrence.
2277     if (!LIOps.empty()) {
2278       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2279       LIOps.push_back(AddRec->getStart());
2280 
2281       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2282                                              AddRec->op_end());
2283       AddRecOps[0] = getAddExpr(LIOps);
2284 
2285       // Build the new addrec. Propagate the NUW and NSW flags if both the
2286       // outer add and the inner addrec are guaranteed to have no overflow.
2287       // Always propagate NW.
2288       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2289       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2290 
2291       // If all of the other operands were loop invariant, we are done.
2292       if (Ops.size() == 1) return NewRec;
2293 
2294       // Otherwise, add the folded AddRec by the non-invariant parts.
2295       for (unsigned i = 0;; ++i)
2296         if (Ops[i] == AddRec) {
2297           Ops[i] = NewRec;
2298           break;
2299         }
2300       return getAddExpr(Ops);
2301     }
2302 
2303     // Okay, if there weren't any loop invariants to be folded, check to see if
2304     // there are multiple AddRec's with the same loop induction variable being
2305     // added together.  If so, we can fold them.
2306     for (unsigned OtherIdx = Idx+1;
2307          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2308          ++OtherIdx)
2309       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2310         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2311         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2312                                                AddRec->op_end());
2313         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2314              ++OtherIdx)
2315           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2316             if (OtherAddRec->getLoop() == AddRecLoop) {
2317               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2318                    i != e; ++i) {
2319                 if (i >= AddRecOps.size()) {
2320                   AddRecOps.append(OtherAddRec->op_begin()+i,
2321                                    OtherAddRec->op_end());
2322                   break;
2323                 }
2324                 AddRecOps[i] = getAddExpr(AddRecOps[i],
2325                                           OtherAddRec->getOperand(i));
2326               }
2327               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2328             }
2329         // Step size has changed, so we cannot guarantee no self-wraparound.
2330         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2331         return getAddExpr(Ops);
2332       }
2333 
2334     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2335     // next one.
2336   }
2337 
2338   // Okay, it looks like we really DO need an add expr.  Check to see if we
2339   // already have one, otherwise create a new one.
2340   FoldingSetNodeID ID;
2341   ID.AddInteger(scAddExpr);
2342   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2343     ID.AddPointer(Ops[i]);
2344   void *IP = nullptr;
2345   SCEVAddExpr *S =
2346     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2347   if (!S) {
2348     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2349     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2350     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2351                                         O, Ops.size());
2352     UniqueSCEVs.InsertNode(S, IP);
2353   }
2354   S->setNoWrapFlags(Flags);
2355   return S;
2356 }
2357 
2358 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2359   uint64_t k = i*j;
2360   if (j > 1 && k / j != i) Overflow = true;
2361   return k;
2362 }
2363 
2364 /// Compute the result of "n choose k", the binomial coefficient.  If an
2365 /// intermediate computation overflows, Overflow will be set and the return will
2366 /// be garbage. Overflow is not cleared on absence of overflow.
2367 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2368   // We use the multiplicative formula:
2369   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2370   // At each iteration, we take the n-th term of the numeral and divide by the
2371   // (k-n)th term of the denominator.  This division will always produce an
2372   // integral result, and helps reduce the chance of overflow in the
2373   // intermediate computations. However, we can still overflow even when the
2374   // final result would fit.
2375 
2376   if (n == 0 || n == k) return 1;
2377   if (k > n) return 0;
2378 
2379   if (k > n/2)
2380     k = n-k;
2381 
2382   uint64_t r = 1;
2383   for (uint64_t i = 1; i <= k; ++i) {
2384     r = umul_ov(r, n-(i-1), Overflow);
2385     r /= i;
2386   }
2387   return r;
2388 }
2389 
2390 /// Determine if any of the operands in this SCEV are a constant or if
2391 /// any of the add or multiply expressions in this SCEV contain a constant.
2392 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2393   SmallVector<const SCEV *, 4> Ops;
2394   Ops.push_back(StartExpr);
2395   while (!Ops.empty()) {
2396     const SCEV *CurrentExpr = Ops.pop_back_val();
2397     if (isa<SCEVConstant>(*CurrentExpr))
2398       return true;
2399 
2400     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2401       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2402       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2403     }
2404   }
2405   return false;
2406 }
2407 
2408 /// getMulExpr - Get a canonical multiply expression, or something simpler if
2409 /// possible.
2410 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2411                                         SCEV::NoWrapFlags Flags) {
2412   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2413          "only nuw or nsw allowed");
2414   assert(!Ops.empty() && "Cannot get empty mul!");
2415   if (Ops.size() == 1) return Ops[0];
2416 #ifndef NDEBUG
2417   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2418   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2419     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2420            "SCEVMulExpr operand types don't match!");
2421 #endif
2422 
2423   // Sort by complexity, this groups all similar expression types together.
2424   GroupByComplexity(Ops, &LI);
2425 
2426   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2427 
2428   // If there are any constants, fold them together.
2429   unsigned Idx = 0;
2430   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2431 
2432     // C1*(C2+V) -> C1*C2 + C1*V
2433     if (Ops.size() == 2)
2434         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2435           // If any of Add's ops are Adds or Muls with a constant,
2436           // apply this transformation as well.
2437           if (Add->getNumOperands() == 2)
2438             if (containsConstantSomewhere(Add))
2439               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2440                                 getMulExpr(LHSC, Add->getOperand(1)));
2441 
2442     ++Idx;
2443     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2444       // We found two constants, fold them together!
2445       ConstantInt *Fold =
2446           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2447       Ops[0] = getConstant(Fold);
2448       Ops.erase(Ops.begin()+1);  // Erase the folded element
2449       if (Ops.size() == 1) return Ops[0];
2450       LHSC = cast<SCEVConstant>(Ops[0]);
2451     }
2452 
2453     // If we are left with a constant one being multiplied, strip it off.
2454     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2455       Ops.erase(Ops.begin());
2456       --Idx;
2457     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2458       // If we have a multiply of zero, it will always be zero.
2459       return Ops[0];
2460     } else if (Ops[0]->isAllOnesValue()) {
2461       // If we have a mul by -1 of an add, try distributing the -1 among the
2462       // add operands.
2463       if (Ops.size() == 2) {
2464         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2465           SmallVector<const SCEV *, 4> NewOps;
2466           bool AnyFolded = false;
2467           for (const SCEV *AddOp : Add->operands()) {
2468             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2469             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2470             NewOps.push_back(Mul);
2471           }
2472           if (AnyFolded)
2473             return getAddExpr(NewOps);
2474         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2475           // Negation preserves a recurrence's no self-wrap property.
2476           SmallVector<const SCEV *, 4> Operands;
2477           for (const SCEV *AddRecOp : AddRec->operands())
2478             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2479 
2480           return getAddRecExpr(Operands, AddRec->getLoop(),
2481                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2482         }
2483       }
2484     }
2485 
2486     if (Ops.size() == 1)
2487       return Ops[0];
2488   }
2489 
2490   // Skip over the add expression until we get to a multiply.
2491   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2492     ++Idx;
2493 
2494   // If there are mul operands inline them all into this expression.
2495   if (Idx < Ops.size()) {
2496     bool DeletedMul = false;
2497     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2498       // If we have an mul, expand the mul operands onto the end of the operands
2499       // list.
2500       Ops.erase(Ops.begin()+Idx);
2501       Ops.append(Mul->op_begin(), Mul->op_end());
2502       DeletedMul = true;
2503     }
2504 
2505     // If we deleted at least one mul, we added operands to the end of the list,
2506     // and they are not necessarily sorted.  Recurse to resort and resimplify
2507     // any operands we just acquired.
2508     if (DeletedMul)
2509       return getMulExpr(Ops);
2510   }
2511 
2512   // If there are any add recurrences in the operands list, see if any other
2513   // added values are loop invariant.  If so, we can fold them into the
2514   // recurrence.
2515   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2516     ++Idx;
2517 
2518   // Scan over all recurrences, trying to fold loop invariants into them.
2519   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2520     // Scan all of the other operands to this mul and add them to the vector if
2521     // they are loop invariant w.r.t. the recurrence.
2522     SmallVector<const SCEV *, 8> LIOps;
2523     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2524     const Loop *AddRecLoop = AddRec->getLoop();
2525     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2526       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2527         LIOps.push_back(Ops[i]);
2528         Ops.erase(Ops.begin()+i);
2529         --i; --e;
2530       }
2531 
2532     // If we found some loop invariants, fold them into the recurrence.
2533     if (!LIOps.empty()) {
2534       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2535       SmallVector<const SCEV *, 4> NewOps;
2536       NewOps.reserve(AddRec->getNumOperands());
2537       const SCEV *Scale = getMulExpr(LIOps);
2538       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2539         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2540 
2541       // Build the new addrec. Propagate the NUW and NSW flags if both the
2542       // outer mul and the inner addrec are guaranteed to have no overflow.
2543       //
2544       // No self-wrap cannot be guaranteed after changing the step size, but
2545       // will be inferred if either NUW or NSW is true.
2546       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2547       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2548 
2549       // If all of the other operands were loop invariant, we are done.
2550       if (Ops.size() == 1) return NewRec;
2551 
2552       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2553       for (unsigned i = 0;; ++i)
2554         if (Ops[i] == AddRec) {
2555           Ops[i] = NewRec;
2556           break;
2557         }
2558       return getMulExpr(Ops);
2559     }
2560 
2561     // Okay, if there weren't any loop invariants to be folded, check to see if
2562     // there are multiple AddRec's with the same loop induction variable being
2563     // multiplied together.  If so, we can fold them.
2564 
2565     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2566     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2567     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2568     //   ]]],+,...up to x=2n}.
2569     // Note that the arguments to choose() are always integers with values
2570     // known at compile time, never SCEV objects.
2571     //
2572     // The implementation avoids pointless extra computations when the two
2573     // addrec's are of different length (mathematically, it's equivalent to
2574     // an infinite stream of zeros on the right).
2575     bool OpsModified = false;
2576     for (unsigned OtherIdx = Idx+1;
2577          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2578          ++OtherIdx) {
2579       const SCEVAddRecExpr *OtherAddRec =
2580         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2581       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2582         continue;
2583 
2584       bool Overflow = false;
2585       Type *Ty = AddRec->getType();
2586       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2587       SmallVector<const SCEV*, 7> AddRecOps;
2588       for (int x = 0, xe = AddRec->getNumOperands() +
2589              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2590         const SCEV *Term = getZero(Ty);
2591         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2592           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2593           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2594                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2595                z < ze && !Overflow; ++z) {
2596             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2597             uint64_t Coeff;
2598             if (LargerThan64Bits)
2599               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2600             else
2601               Coeff = Coeff1*Coeff2;
2602             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2603             const SCEV *Term1 = AddRec->getOperand(y-z);
2604             const SCEV *Term2 = OtherAddRec->getOperand(z);
2605             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2606           }
2607         }
2608         AddRecOps.push_back(Term);
2609       }
2610       if (!Overflow) {
2611         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2612                                               SCEV::FlagAnyWrap);
2613         if (Ops.size() == 2) return NewAddRec;
2614         Ops[Idx] = NewAddRec;
2615         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2616         OpsModified = true;
2617         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2618         if (!AddRec)
2619           break;
2620       }
2621     }
2622     if (OpsModified)
2623       return getMulExpr(Ops);
2624 
2625     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2626     // next one.
2627   }
2628 
2629   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2630   // already have one, otherwise create a new one.
2631   FoldingSetNodeID ID;
2632   ID.AddInteger(scMulExpr);
2633   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2634     ID.AddPointer(Ops[i]);
2635   void *IP = nullptr;
2636   SCEVMulExpr *S =
2637     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2638   if (!S) {
2639     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2640     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2641     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2642                                         O, Ops.size());
2643     UniqueSCEVs.InsertNode(S, IP);
2644   }
2645   S->setNoWrapFlags(Flags);
2646   return S;
2647 }
2648 
2649 /// getUDivExpr - Get a canonical unsigned division expression, or something
2650 /// simpler if possible.
2651 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2652                                          const SCEV *RHS) {
2653   assert(getEffectiveSCEVType(LHS->getType()) ==
2654          getEffectiveSCEVType(RHS->getType()) &&
2655          "SCEVUDivExpr operand types don't match!");
2656 
2657   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2658     if (RHSC->getValue()->equalsInt(1))
2659       return LHS;                               // X udiv 1 --> x
2660     // If the denominator is zero, the result of the udiv is undefined. Don't
2661     // try to analyze it, because the resolution chosen here may differ from
2662     // the resolution chosen in other parts of the compiler.
2663     if (!RHSC->getValue()->isZero()) {
2664       // Determine if the division can be folded into the operands of
2665       // its operands.
2666       // TODO: Generalize this to non-constants by using known-bits information.
2667       Type *Ty = LHS->getType();
2668       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2669       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2670       // For non-power-of-two values, effectively round the value up to the
2671       // nearest power of two.
2672       if (!RHSC->getAPInt().isPowerOf2())
2673         ++MaxShiftAmt;
2674       IntegerType *ExtTy =
2675         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2676       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2677         if (const SCEVConstant *Step =
2678             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2679           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2680           const APInt &StepInt = Step->getAPInt();
2681           const APInt &DivInt = RHSC->getAPInt();
2682           if (!StepInt.urem(DivInt) &&
2683               getZeroExtendExpr(AR, ExtTy) ==
2684               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2685                             getZeroExtendExpr(Step, ExtTy),
2686                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2687             SmallVector<const SCEV *, 4> Operands;
2688             for (const SCEV *Op : AR->operands())
2689               Operands.push_back(getUDivExpr(Op, RHS));
2690             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2691           }
2692           /// Get a canonical UDivExpr for a recurrence.
2693           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2694           // We can currently only fold X%N if X is constant.
2695           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2696           if (StartC && !DivInt.urem(StepInt) &&
2697               getZeroExtendExpr(AR, ExtTy) ==
2698               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2699                             getZeroExtendExpr(Step, ExtTy),
2700                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2701             const APInt &StartInt = StartC->getAPInt();
2702             const APInt &StartRem = StartInt.urem(StepInt);
2703             if (StartRem != 0)
2704               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2705                                   AR->getLoop(), SCEV::FlagNW);
2706           }
2707         }
2708       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2709       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2710         SmallVector<const SCEV *, 4> Operands;
2711         for (const SCEV *Op : M->operands())
2712           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2713         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2714           // Find an operand that's safely divisible.
2715           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2716             const SCEV *Op = M->getOperand(i);
2717             const SCEV *Div = getUDivExpr(Op, RHSC);
2718             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2719               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2720                                                       M->op_end());
2721               Operands[i] = Div;
2722               return getMulExpr(Operands);
2723             }
2724           }
2725       }
2726       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2727       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2728         SmallVector<const SCEV *, 4> Operands;
2729         for (const SCEV *Op : A->operands())
2730           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2731         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2732           Operands.clear();
2733           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2734             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2735             if (isa<SCEVUDivExpr>(Op) ||
2736                 getMulExpr(Op, RHS) != A->getOperand(i))
2737               break;
2738             Operands.push_back(Op);
2739           }
2740           if (Operands.size() == A->getNumOperands())
2741             return getAddExpr(Operands);
2742         }
2743       }
2744 
2745       // Fold if both operands are constant.
2746       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2747         Constant *LHSCV = LHSC->getValue();
2748         Constant *RHSCV = RHSC->getValue();
2749         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2750                                                                    RHSCV)));
2751       }
2752     }
2753   }
2754 
2755   FoldingSetNodeID ID;
2756   ID.AddInteger(scUDivExpr);
2757   ID.AddPointer(LHS);
2758   ID.AddPointer(RHS);
2759   void *IP = nullptr;
2760   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2761   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2762                                              LHS, RHS);
2763   UniqueSCEVs.InsertNode(S, IP);
2764   return S;
2765 }
2766 
2767 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2768   APInt A = C1->getAPInt().abs();
2769   APInt B = C2->getAPInt().abs();
2770   uint32_t ABW = A.getBitWidth();
2771   uint32_t BBW = B.getBitWidth();
2772 
2773   if (ABW > BBW)
2774     B = B.zext(ABW);
2775   else if (ABW < BBW)
2776     A = A.zext(BBW);
2777 
2778   return APIntOps::GreatestCommonDivisor(A, B);
2779 }
2780 
2781 /// getUDivExactExpr - Get a canonical unsigned division expression, or
2782 /// something simpler if possible. There is no representation for an exact udiv
2783 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2784 /// We can't do this when it's not exact because the udiv may be clearing bits.
2785 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2786                                               const SCEV *RHS) {
2787   // TODO: we could try to find factors in all sorts of things, but for now we
2788   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2789   // end of this file for inspiration.
2790 
2791   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2792   if (!Mul)
2793     return getUDivExpr(LHS, RHS);
2794 
2795   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2796     // If the mulexpr multiplies by a constant, then that constant must be the
2797     // first element of the mulexpr.
2798     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2799       if (LHSCst == RHSCst) {
2800         SmallVector<const SCEV *, 2> Operands;
2801         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2802         return getMulExpr(Operands);
2803       }
2804 
2805       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2806       // that there's a factor provided by one of the other terms. We need to
2807       // check.
2808       APInt Factor = gcd(LHSCst, RHSCst);
2809       if (!Factor.isIntN(1)) {
2810         LHSCst =
2811             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2812         RHSCst =
2813             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
2814         SmallVector<const SCEV *, 2> Operands;
2815         Operands.push_back(LHSCst);
2816         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2817         LHS = getMulExpr(Operands);
2818         RHS = RHSCst;
2819         Mul = dyn_cast<SCEVMulExpr>(LHS);
2820         if (!Mul)
2821           return getUDivExactExpr(LHS, RHS);
2822       }
2823     }
2824   }
2825 
2826   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2827     if (Mul->getOperand(i) == RHS) {
2828       SmallVector<const SCEV *, 2> Operands;
2829       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2830       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2831       return getMulExpr(Operands);
2832     }
2833   }
2834 
2835   return getUDivExpr(LHS, RHS);
2836 }
2837 
2838 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2839 /// Simplify the expression as much as possible.
2840 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2841                                            const Loop *L,
2842                                            SCEV::NoWrapFlags Flags) {
2843   SmallVector<const SCEV *, 4> Operands;
2844   Operands.push_back(Start);
2845   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2846     if (StepChrec->getLoop() == L) {
2847       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2848       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2849     }
2850 
2851   Operands.push_back(Step);
2852   return getAddRecExpr(Operands, L, Flags);
2853 }
2854 
2855 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2856 /// Simplify the expression as much as possible.
2857 const SCEV *
2858 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2859                                const Loop *L, SCEV::NoWrapFlags Flags) {
2860   if (Operands.size() == 1) return Operands[0];
2861 #ifndef NDEBUG
2862   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2863   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2864     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2865            "SCEVAddRecExpr operand types don't match!");
2866   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2867     assert(isLoopInvariant(Operands[i], L) &&
2868            "SCEVAddRecExpr operand is not loop-invariant!");
2869 #endif
2870 
2871   if (Operands.back()->isZero()) {
2872     Operands.pop_back();
2873     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2874   }
2875 
2876   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2877   // use that information to infer NUW and NSW flags. However, computing a
2878   // BE count requires calling getAddRecExpr, so we may not yet have a
2879   // meaningful BE count at this point (and if we don't, we'd be stuck
2880   // with a SCEVCouldNotCompute as the cached BE count).
2881 
2882   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2883 
2884   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2885   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2886     const Loop *NestedLoop = NestedAR->getLoop();
2887     if (L->contains(NestedLoop)
2888             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2889             : (!NestedLoop->contains(L) &&
2890                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
2891       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2892                                                   NestedAR->op_end());
2893       Operands[0] = NestedAR->getStart();
2894       // AddRecs require their operands be loop-invariant with respect to their
2895       // loops. Don't perform this transformation if it would break this
2896       // requirement.
2897       bool AllInvariant = all_of(
2898           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
2899 
2900       if (AllInvariant) {
2901         // Create a recurrence for the outer loop with the same step size.
2902         //
2903         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2904         // inner recurrence has the same property.
2905         SCEV::NoWrapFlags OuterFlags =
2906           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2907 
2908         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2909         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2910           return isLoopInvariant(Op, NestedLoop);
2911         });
2912 
2913         if (AllInvariant) {
2914           // Ok, both add recurrences are valid after the transformation.
2915           //
2916           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2917           // the outer recurrence has the same property.
2918           SCEV::NoWrapFlags InnerFlags =
2919             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2920           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2921         }
2922       }
2923       // Reset Operands to its original state.
2924       Operands[0] = NestedAR;
2925     }
2926   }
2927 
2928   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
2929   // already have one, otherwise create a new one.
2930   FoldingSetNodeID ID;
2931   ID.AddInteger(scAddRecExpr);
2932   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2933     ID.AddPointer(Operands[i]);
2934   ID.AddPointer(L);
2935   void *IP = nullptr;
2936   SCEVAddRecExpr *S =
2937     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2938   if (!S) {
2939     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2940     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2941     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2942                                            O, Operands.size(), L);
2943     UniqueSCEVs.InsertNode(S, IP);
2944   }
2945   S->setNoWrapFlags(Flags);
2946   return S;
2947 }
2948 
2949 const SCEV *
2950 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2951                             const SmallVectorImpl<const SCEV *> &IndexExprs,
2952                             bool InBounds) {
2953   // getSCEV(Base)->getType() has the same address space as Base->getType()
2954   // because SCEV::getType() preserves the address space.
2955   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2956   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2957   // instruction to its SCEV, because the Instruction may be guarded by control
2958   // flow and the no-overflow bits may not be valid for the expression in any
2959   // context. This can be fixed similarly to how these flags are handled for
2960   // adds.
2961   SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2962 
2963   const SCEV *TotalOffset = getZero(IntPtrTy);
2964   // The address space is unimportant. The first thing we do on CurTy is getting
2965   // its element type.
2966   Type *CurTy = PointerType::getUnqual(PointeeType);
2967   for (const SCEV *IndexExpr : IndexExprs) {
2968     // Compute the (potentially symbolic) offset in bytes for this index.
2969     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2970       // For a struct, add the member offset.
2971       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2972       unsigned FieldNo = Index->getZExtValue();
2973       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2974 
2975       // Add the field offset to the running total offset.
2976       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2977 
2978       // Update CurTy to the type of the field at Index.
2979       CurTy = STy->getTypeAtIndex(Index);
2980     } else {
2981       // Update CurTy to its element type.
2982       CurTy = cast<SequentialType>(CurTy)->getElementType();
2983       // For an array, add the element offset, explicitly scaled.
2984       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2985       // Getelementptr indices are signed.
2986       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2987 
2988       // Multiply the index by the element size to compute the element offset.
2989       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
2990 
2991       // Add the element offset to the running total offset.
2992       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2993     }
2994   }
2995 
2996   // Add the total offset from all the GEP indices to the base.
2997   return getAddExpr(BaseExpr, TotalOffset, Wrap);
2998 }
2999 
3000 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3001                                          const SCEV *RHS) {
3002   SmallVector<const SCEV *, 2> Ops;
3003   Ops.push_back(LHS);
3004   Ops.push_back(RHS);
3005   return getSMaxExpr(Ops);
3006 }
3007 
3008 const SCEV *
3009 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3010   assert(!Ops.empty() && "Cannot get empty smax!");
3011   if (Ops.size() == 1) return Ops[0];
3012 #ifndef NDEBUG
3013   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3014   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3015     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3016            "SCEVSMaxExpr operand types don't match!");
3017 #endif
3018 
3019   // Sort by complexity, this groups all similar expression types together.
3020   GroupByComplexity(Ops, &LI);
3021 
3022   // If there are any constants, fold them together.
3023   unsigned Idx = 0;
3024   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3025     ++Idx;
3026     assert(Idx < Ops.size());
3027     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3028       // We found two constants, fold them together!
3029       ConstantInt *Fold = ConstantInt::get(
3030           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3031       Ops[0] = getConstant(Fold);
3032       Ops.erase(Ops.begin()+1);  // Erase the folded element
3033       if (Ops.size() == 1) return Ops[0];
3034       LHSC = cast<SCEVConstant>(Ops[0]);
3035     }
3036 
3037     // If we are left with a constant minimum-int, strip it off.
3038     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3039       Ops.erase(Ops.begin());
3040       --Idx;
3041     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3042       // If we have an smax with a constant maximum-int, it will always be
3043       // maximum-int.
3044       return Ops[0];
3045     }
3046 
3047     if (Ops.size() == 1) return Ops[0];
3048   }
3049 
3050   // Find the first SMax
3051   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3052     ++Idx;
3053 
3054   // Check to see if one of the operands is an SMax. If so, expand its operands
3055   // onto our operand list, and recurse to simplify.
3056   if (Idx < Ops.size()) {
3057     bool DeletedSMax = false;
3058     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3059       Ops.erase(Ops.begin()+Idx);
3060       Ops.append(SMax->op_begin(), SMax->op_end());
3061       DeletedSMax = true;
3062     }
3063 
3064     if (DeletedSMax)
3065       return getSMaxExpr(Ops);
3066   }
3067 
3068   // Okay, check to see if the same value occurs in the operand list twice.  If
3069   // so, delete one.  Since we sorted the list, these values are required to
3070   // be adjacent.
3071   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3072     //  X smax Y smax Y  -->  X smax Y
3073     //  X smax Y         -->  X, if X is always greater than Y
3074     if (Ops[i] == Ops[i+1] ||
3075         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3076       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3077       --i; --e;
3078     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3079       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3080       --i; --e;
3081     }
3082 
3083   if (Ops.size() == 1) return Ops[0];
3084 
3085   assert(!Ops.empty() && "Reduced smax down to nothing!");
3086 
3087   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3088   // already have one, otherwise create a new one.
3089   FoldingSetNodeID ID;
3090   ID.AddInteger(scSMaxExpr);
3091   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3092     ID.AddPointer(Ops[i]);
3093   void *IP = nullptr;
3094   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3095   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3096   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3097   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3098                                              O, Ops.size());
3099   UniqueSCEVs.InsertNode(S, IP);
3100   return S;
3101 }
3102 
3103 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3104                                          const SCEV *RHS) {
3105   SmallVector<const SCEV *, 2> Ops;
3106   Ops.push_back(LHS);
3107   Ops.push_back(RHS);
3108   return getUMaxExpr(Ops);
3109 }
3110 
3111 const SCEV *
3112 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3113   assert(!Ops.empty() && "Cannot get empty umax!");
3114   if (Ops.size() == 1) return Ops[0];
3115 #ifndef NDEBUG
3116   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3117   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3118     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3119            "SCEVUMaxExpr operand types don't match!");
3120 #endif
3121 
3122   // Sort by complexity, this groups all similar expression types together.
3123   GroupByComplexity(Ops, &LI);
3124 
3125   // If there are any constants, fold them together.
3126   unsigned Idx = 0;
3127   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3128     ++Idx;
3129     assert(Idx < Ops.size());
3130     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3131       // We found two constants, fold them together!
3132       ConstantInt *Fold = ConstantInt::get(
3133           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3134       Ops[0] = getConstant(Fold);
3135       Ops.erase(Ops.begin()+1);  // Erase the folded element
3136       if (Ops.size() == 1) return Ops[0];
3137       LHSC = cast<SCEVConstant>(Ops[0]);
3138     }
3139 
3140     // If we are left with a constant minimum-int, strip it off.
3141     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3142       Ops.erase(Ops.begin());
3143       --Idx;
3144     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3145       // If we have an umax with a constant maximum-int, it will always be
3146       // maximum-int.
3147       return Ops[0];
3148     }
3149 
3150     if (Ops.size() == 1) return Ops[0];
3151   }
3152 
3153   // Find the first UMax
3154   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3155     ++Idx;
3156 
3157   // Check to see if one of the operands is a UMax. If so, expand its operands
3158   // onto our operand list, and recurse to simplify.
3159   if (Idx < Ops.size()) {
3160     bool DeletedUMax = false;
3161     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3162       Ops.erase(Ops.begin()+Idx);
3163       Ops.append(UMax->op_begin(), UMax->op_end());
3164       DeletedUMax = true;
3165     }
3166 
3167     if (DeletedUMax)
3168       return getUMaxExpr(Ops);
3169   }
3170 
3171   // Okay, check to see if the same value occurs in the operand list twice.  If
3172   // so, delete one.  Since we sorted the list, these values are required to
3173   // be adjacent.
3174   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3175     //  X umax Y umax Y  -->  X umax Y
3176     //  X umax Y         -->  X, if X is always greater than Y
3177     if (Ops[i] == Ops[i+1] ||
3178         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3179       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3180       --i; --e;
3181     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3182       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3183       --i; --e;
3184     }
3185 
3186   if (Ops.size() == 1) return Ops[0];
3187 
3188   assert(!Ops.empty() && "Reduced umax down to nothing!");
3189 
3190   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3191   // already have one, otherwise create a new one.
3192   FoldingSetNodeID ID;
3193   ID.AddInteger(scUMaxExpr);
3194   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3195     ID.AddPointer(Ops[i]);
3196   void *IP = nullptr;
3197   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3198   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3199   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3200   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3201                                              O, Ops.size());
3202   UniqueSCEVs.InsertNode(S, IP);
3203   return S;
3204 }
3205 
3206 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3207                                          const SCEV *RHS) {
3208   // ~smax(~x, ~y) == smin(x, y).
3209   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3210 }
3211 
3212 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3213                                          const SCEV *RHS) {
3214   // ~umax(~x, ~y) == umin(x, y)
3215   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3216 }
3217 
3218 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3219   // We can bypass creating a target-independent
3220   // constant expression and then folding it back into a ConstantInt.
3221   // This is just a compile-time optimization.
3222   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3223 }
3224 
3225 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3226                                              StructType *STy,
3227                                              unsigned FieldNo) {
3228   // We can bypass creating a target-independent
3229   // constant expression and then folding it back into a ConstantInt.
3230   // This is just a compile-time optimization.
3231   return getConstant(
3232       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3233 }
3234 
3235 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3236   // Don't attempt to do anything other than create a SCEVUnknown object
3237   // here.  createSCEV only calls getUnknown after checking for all other
3238   // interesting possibilities, and any other code that calls getUnknown
3239   // is doing so in order to hide a value from SCEV canonicalization.
3240 
3241   FoldingSetNodeID ID;
3242   ID.AddInteger(scUnknown);
3243   ID.AddPointer(V);
3244   void *IP = nullptr;
3245   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3246     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3247            "Stale SCEVUnknown in uniquing map!");
3248     return S;
3249   }
3250   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3251                                             FirstUnknown);
3252   FirstUnknown = cast<SCEVUnknown>(S);
3253   UniqueSCEVs.InsertNode(S, IP);
3254   return S;
3255 }
3256 
3257 //===----------------------------------------------------------------------===//
3258 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3259 //
3260 
3261 /// isSCEVable - Test if values of the given type are analyzable within
3262 /// the SCEV framework. This primarily includes integer types, and it
3263 /// can optionally include pointer types if the ScalarEvolution class
3264 /// has access to target-specific information.
3265 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3266   // Integers and pointers are always SCEVable.
3267   return Ty->isIntegerTy() || Ty->isPointerTy();
3268 }
3269 
3270 /// getTypeSizeInBits - Return the size in bits of the specified type,
3271 /// for which isSCEVable must return true.
3272 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3273   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3274   return getDataLayout().getTypeSizeInBits(Ty);
3275 }
3276 
3277 /// getEffectiveSCEVType - Return a type with the same bitwidth as
3278 /// the given type and which represents how SCEV will treat the given
3279 /// type, for which isSCEVable must return true. For pointer types,
3280 /// this is the pointer-sized integer type.
3281 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3282   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3283 
3284   if (Ty->isIntegerTy())
3285     return Ty;
3286 
3287   // The only other support type is pointer.
3288   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3289   return getDataLayout().getIntPtrType(Ty);
3290 }
3291 
3292 const SCEV *ScalarEvolution::getCouldNotCompute() {
3293   return CouldNotCompute.get();
3294 }
3295 
3296 
3297 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3298   // Helper class working with SCEVTraversal to figure out if a SCEV contains
3299   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3300   // is set iff if find such SCEVUnknown.
3301   //
3302   struct FindInvalidSCEVUnknown {
3303     bool FindOne;
3304     FindInvalidSCEVUnknown() { FindOne = false; }
3305     bool follow(const SCEV *S) {
3306       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3307       case scConstant:
3308         return false;
3309       case scUnknown:
3310         if (!cast<SCEVUnknown>(S)->getValue())
3311           FindOne = true;
3312         return false;
3313       default:
3314         return true;
3315       }
3316     }
3317     bool isDone() const { return FindOne; }
3318   };
3319 
3320   FindInvalidSCEVUnknown F;
3321   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3322   ST.visitAll(S);
3323 
3324   return !F.FindOne;
3325 }
3326 
3327 namespace {
3328 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3329 // a sub SCEV of scAddRecExpr type.  FindInvalidSCEVUnknown::FoundOne is set
3330 // iff if such sub scAddRecExpr type SCEV is found.
3331 struct FindAddRecurrence {
3332   bool FoundOne;
3333   FindAddRecurrence() : FoundOne(false) {}
3334 
3335   bool follow(const SCEV *S) {
3336     switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3337     case scAddRecExpr:
3338       FoundOne = true;
3339     case scConstant:
3340     case scUnknown:
3341     case scCouldNotCompute:
3342       return false;
3343     default:
3344       return true;
3345     }
3346   }
3347   bool isDone() const { return FoundOne; }
3348 };
3349 }
3350 
3351 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3352   HasRecMapType::iterator I = HasRecMap.find_as(S);
3353   if (I != HasRecMap.end())
3354     return I->second;
3355 
3356   FindAddRecurrence F;
3357   SCEVTraversal<FindAddRecurrence> ST(F);
3358   ST.visitAll(S);
3359   HasRecMap.insert({S, F.FoundOne});
3360   return F.FoundOne;
3361 }
3362 
3363 /// getSCEVValues - Return the Value set from S.
3364 SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) {
3365   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3366   if (SI == ExprValueMap.end())
3367     return nullptr;
3368 #ifndef NDEBUG
3369   if (VerifySCEVMap) {
3370     // Check there is no dangling Value in the set returned.
3371     for (const auto &VE : SI->second)
3372       assert(ValueExprMap.count(VE));
3373   }
3374 #endif
3375   return &SI->second;
3376 }
3377 
3378 /// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap.
3379 /// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S),
3380 /// eraseValueFromMap should be used instead to ensure whenever V->S is removed
3381 /// from ValueExprMap, V is also removed from the set of ExprValueMap[S].
3382 void ScalarEvolution::eraseValueFromMap(Value *V) {
3383   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3384   if (I != ValueExprMap.end()) {
3385     const SCEV *S = I->second;
3386     SetVector<Value *> *SV = getSCEVValues(S);
3387     // Remove V from the set of ExprValueMap[S]
3388     if (SV)
3389       SV->remove(V);
3390     ValueExprMap.erase(V);
3391   }
3392 }
3393 
3394 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3395 /// expression and create a new one.
3396 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3397   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3398 
3399   const SCEV *S = getExistingSCEV(V);
3400   if (S == nullptr) {
3401     S = createSCEV(V);
3402     // During PHI resolution, it is possible to create two SCEVs for the same
3403     // V, so it is needed to double check whether V->S is inserted into
3404     // ValueExprMap before insert S->V into ExprValueMap.
3405     std::pair<ValueExprMapType::iterator, bool> Pair =
3406         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3407     if (Pair.second)
3408       ExprValueMap[S].insert(V);
3409   }
3410   return S;
3411 }
3412 
3413 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3414   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3415 
3416   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3417   if (I != ValueExprMap.end()) {
3418     const SCEV *S = I->second;
3419     if (checkValidity(S))
3420       return S;
3421     forgetMemoizedResults(S);
3422     ValueExprMap.erase(I);
3423   }
3424   return nullptr;
3425 }
3426 
3427 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3428 ///
3429 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3430                                              SCEV::NoWrapFlags Flags) {
3431   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3432     return getConstant(
3433                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3434 
3435   Type *Ty = V->getType();
3436   Ty = getEffectiveSCEVType(Ty);
3437   return getMulExpr(
3438       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3439 }
3440 
3441 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3442 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3443   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3444     return getConstant(
3445                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3446 
3447   Type *Ty = V->getType();
3448   Ty = getEffectiveSCEVType(Ty);
3449   const SCEV *AllOnes =
3450                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3451   return getMinusSCEV(AllOnes, V);
3452 }
3453 
3454 /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
3455 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3456                                           SCEV::NoWrapFlags Flags) {
3457   // Fast path: X - X --> 0.
3458   if (LHS == RHS)
3459     return getZero(LHS->getType());
3460 
3461   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3462   // makes it so that we cannot make much use of NUW.
3463   auto AddFlags = SCEV::FlagAnyWrap;
3464   const bool RHSIsNotMinSigned =
3465       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3466   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3467     // Let M be the minimum representable signed value. Then (-1)*RHS
3468     // signed-wraps if and only if RHS is M. That can happen even for
3469     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3470     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3471     // (-1)*RHS, we need to prove that RHS != M.
3472     //
3473     // If LHS is non-negative and we know that LHS - RHS does not
3474     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3475     // either by proving that RHS > M or that LHS >= 0.
3476     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3477       AddFlags = SCEV::FlagNSW;
3478     }
3479   }
3480 
3481   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3482   // RHS is NSW and LHS >= 0.
3483   //
3484   // The difficulty here is that the NSW flag may have been proven
3485   // relative to a loop that is to be found in a recurrence in LHS and
3486   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3487   // larger scope than intended.
3488   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3489 
3490   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3491 }
3492 
3493 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3494 /// input value to the specified type.  If the type must be extended, it is zero
3495 /// extended.
3496 const SCEV *
3497 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3498   Type *SrcTy = V->getType();
3499   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3500          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3501          "Cannot truncate or zero extend with non-integer arguments!");
3502   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3503     return V;  // No conversion
3504   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3505     return getTruncateExpr(V, Ty);
3506   return getZeroExtendExpr(V, Ty);
3507 }
3508 
3509 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3510 /// input value to the specified type.  If the type must be extended, it is sign
3511 /// extended.
3512 const SCEV *
3513 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3514                                          Type *Ty) {
3515   Type *SrcTy = V->getType();
3516   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3517          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3518          "Cannot truncate or zero extend with non-integer arguments!");
3519   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3520     return V;  // No conversion
3521   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3522     return getTruncateExpr(V, Ty);
3523   return getSignExtendExpr(V, Ty);
3524 }
3525 
3526 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3527 /// input value to the specified type.  If the type must be extended, it is zero
3528 /// extended.  The conversion must not be narrowing.
3529 const SCEV *
3530 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3531   Type *SrcTy = V->getType();
3532   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3533          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3534          "Cannot noop or zero extend with non-integer arguments!");
3535   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3536          "getNoopOrZeroExtend cannot truncate!");
3537   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3538     return V;  // No conversion
3539   return getZeroExtendExpr(V, Ty);
3540 }
3541 
3542 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3543 /// input value to the specified type.  If the type must be extended, it is sign
3544 /// extended.  The conversion must not be narrowing.
3545 const SCEV *
3546 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3547   Type *SrcTy = V->getType();
3548   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3549          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3550          "Cannot noop or sign extend with non-integer arguments!");
3551   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3552          "getNoopOrSignExtend cannot truncate!");
3553   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3554     return V;  // No conversion
3555   return getSignExtendExpr(V, Ty);
3556 }
3557 
3558 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3559 /// the input value to the specified type. If the type must be extended,
3560 /// it is extended with unspecified bits. The conversion must not be
3561 /// narrowing.
3562 const SCEV *
3563 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3564   Type *SrcTy = V->getType();
3565   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3566          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3567          "Cannot noop or any extend with non-integer arguments!");
3568   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3569          "getNoopOrAnyExtend cannot truncate!");
3570   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3571     return V;  // No conversion
3572   return getAnyExtendExpr(V, Ty);
3573 }
3574 
3575 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3576 /// input value to the specified type.  The conversion must not be widening.
3577 const SCEV *
3578 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3579   Type *SrcTy = V->getType();
3580   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3581          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3582          "Cannot truncate or noop with non-integer arguments!");
3583   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3584          "getTruncateOrNoop cannot extend!");
3585   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3586     return V;  // No conversion
3587   return getTruncateExpr(V, Ty);
3588 }
3589 
3590 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3591 /// the types using zero-extension, and then perform a umax operation
3592 /// with them.
3593 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3594                                                         const SCEV *RHS) {
3595   const SCEV *PromotedLHS = LHS;
3596   const SCEV *PromotedRHS = RHS;
3597 
3598   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3599     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3600   else
3601     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3602 
3603   return getUMaxExpr(PromotedLHS, PromotedRHS);
3604 }
3605 
3606 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
3607 /// the types using zero-extension, and then perform a umin operation
3608 /// with them.
3609 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3610                                                         const SCEV *RHS) {
3611   const SCEV *PromotedLHS = LHS;
3612   const SCEV *PromotedRHS = RHS;
3613 
3614   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3615     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3616   else
3617     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3618 
3619   return getUMinExpr(PromotedLHS, PromotedRHS);
3620 }
3621 
3622 /// getPointerBase - Transitively follow the chain of pointer-type operands
3623 /// until reaching a SCEV that does not have a single pointer operand. This
3624 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3625 /// but corner cases do exist.
3626 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3627   // A pointer operand may evaluate to a nonpointer expression, such as null.
3628   if (!V->getType()->isPointerTy())
3629     return V;
3630 
3631   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3632     return getPointerBase(Cast->getOperand());
3633   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3634     const SCEV *PtrOp = nullptr;
3635     for (const SCEV *NAryOp : NAry->operands()) {
3636       if (NAryOp->getType()->isPointerTy()) {
3637         // Cannot find the base of an expression with multiple pointer operands.
3638         if (PtrOp)
3639           return V;
3640         PtrOp = NAryOp;
3641       }
3642     }
3643     if (!PtrOp)
3644       return V;
3645     return getPointerBase(PtrOp);
3646   }
3647   return V;
3648 }
3649 
3650 /// PushDefUseChildren - Push users of the given Instruction
3651 /// onto the given Worklist.
3652 static void
3653 PushDefUseChildren(Instruction *I,
3654                    SmallVectorImpl<Instruction *> &Worklist) {
3655   // Push the def-use children onto the Worklist stack.
3656   for (User *U : I->users())
3657     Worklist.push_back(cast<Instruction>(U));
3658 }
3659 
3660 /// ForgetSymbolicValue - This looks up computed SCEV values for all
3661 /// instructions that depend on the given instruction and removes them from
3662 /// the ValueExprMapType map if they reference SymName. This is used during PHI
3663 /// resolution.
3664 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3665   SmallVector<Instruction *, 16> Worklist;
3666   PushDefUseChildren(PN, Worklist);
3667 
3668   SmallPtrSet<Instruction *, 8> Visited;
3669   Visited.insert(PN);
3670   while (!Worklist.empty()) {
3671     Instruction *I = Worklist.pop_back_val();
3672     if (!Visited.insert(I).second)
3673       continue;
3674 
3675     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3676     if (It != ValueExprMap.end()) {
3677       const SCEV *Old = It->second;
3678 
3679       // Short-circuit the def-use traversal if the symbolic name
3680       // ceases to appear in expressions.
3681       if (Old != SymName && !hasOperand(Old, SymName))
3682         continue;
3683 
3684       // SCEVUnknown for a PHI either means that it has an unrecognized
3685       // structure, it's a PHI that's in the progress of being computed
3686       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3687       // additional loop trip count information isn't going to change anything.
3688       // In the second case, createNodeForPHI will perform the necessary
3689       // updates on its own when it gets to that point. In the third, we do
3690       // want to forget the SCEVUnknown.
3691       if (!isa<PHINode>(I) ||
3692           !isa<SCEVUnknown>(Old) ||
3693           (I != PN && Old == SymName)) {
3694         forgetMemoizedResults(Old);
3695         ValueExprMap.erase(It);
3696       }
3697     }
3698 
3699     PushDefUseChildren(I, Worklist);
3700   }
3701 }
3702 
3703 namespace {
3704 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3705 public:
3706   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3707                              ScalarEvolution &SE) {
3708     SCEVInitRewriter Rewriter(L, SE);
3709     const SCEV *Result = Rewriter.visit(S);
3710     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3711   }
3712 
3713   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3714       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3715 
3716   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3717     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3718       Valid = false;
3719     return Expr;
3720   }
3721 
3722   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3723     // Only allow AddRecExprs for this loop.
3724     if (Expr->getLoop() == L)
3725       return Expr->getStart();
3726     Valid = false;
3727     return Expr;
3728   }
3729 
3730   bool isValid() { return Valid; }
3731 
3732 private:
3733   const Loop *L;
3734   bool Valid;
3735 };
3736 
3737 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3738 public:
3739   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3740                              ScalarEvolution &SE) {
3741     SCEVShiftRewriter Rewriter(L, SE);
3742     const SCEV *Result = Rewriter.visit(S);
3743     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3744   }
3745 
3746   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3747       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3748 
3749   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3750     // Only allow AddRecExprs for this loop.
3751     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3752       Valid = false;
3753     return Expr;
3754   }
3755 
3756   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3757     if (Expr->getLoop() == L && Expr->isAffine())
3758       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3759     Valid = false;
3760     return Expr;
3761   }
3762   bool isValid() { return Valid; }
3763 
3764 private:
3765   const Loop *L;
3766   bool Valid;
3767 };
3768 } // end anonymous namespace
3769 
3770 SCEV::NoWrapFlags
3771 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3772   if (!AR->isAffine())
3773     return SCEV::FlagAnyWrap;
3774 
3775   typedef OverflowingBinaryOperator OBO;
3776   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3777 
3778   if (!AR->hasNoSignedWrap()) {
3779     ConstantRange AddRecRange = getSignedRange(AR);
3780     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3781 
3782     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3783         Instruction::Add, IncRange, OBO::NoSignedWrap);
3784     if (NSWRegion.contains(AddRecRange))
3785       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3786   }
3787 
3788   if (!AR->hasNoUnsignedWrap()) {
3789     ConstantRange AddRecRange = getUnsignedRange(AR);
3790     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3791 
3792     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3793         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3794     if (NUWRegion.contains(AddRecRange))
3795       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3796   }
3797 
3798   return Result;
3799 }
3800 
3801 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3802   const Loop *L = LI.getLoopFor(PN->getParent());
3803   if (!L || L->getHeader() != PN->getParent())
3804     return nullptr;
3805 
3806   // The loop may have multiple entrances or multiple exits; we can analyze
3807   // this phi as an addrec if it has a unique entry value and a unique
3808   // backedge value.
3809   Value *BEValueV = nullptr, *StartValueV = nullptr;
3810   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3811     Value *V = PN->getIncomingValue(i);
3812     if (L->contains(PN->getIncomingBlock(i))) {
3813       if (!BEValueV) {
3814         BEValueV = V;
3815       } else if (BEValueV != V) {
3816         BEValueV = nullptr;
3817         break;
3818       }
3819     } else if (!StartValueV) {
3820       StartValueV = V;
3821     } else if (StartValueV != V) {
3822       StartValueV = nullptr;
3823       break;
3824     }
3825   }
3826   if (BEValueV && StartValueV) {
3827     // While we are analyzing this PHI node, handle its value symbolically.
3828     const SCEV *SymbolicName = getUnknown(PN);
3829     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3830            "PHI node already processed?");
3831     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
3832 
3833     // Using this symbolic name for the PHI, analyze the value coming around
3834     // the back-edge.
3835     const SCEV *BEValue = getSCEV(BEValueV);
3836 
3837     // NOTE: If BEValue is loop invariant, we know that the PHI node just
3838     // has a special value for the first iteration of the loop.
3839 
3840     // If the value coming around the backedge is an add with the symbolic
3841     // value we just inserted, then we found a simple induction variable!
3842     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3843       // If there is a single occurrence of the symbolic value, replace it
3844       // with a recurrence.
3845       unsigned FoundIndex = Add->getNumOperands();
3846       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3847         if (Add->getOperand(i) == SymbolicName)
3848           if (FoundIndex == e) {
3849             FoundIndex = i;
3850             break;
3851           }
3852 
3853       if (FoundIndex != Add->getNumOperands()) {
3854         // Create an add with everything but the specified operand.
3855         SmallVector<const SCEV *, 8> Ops;
3856         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3857           if (i != FoundIndex)
3858             Ops.push_back(Add->getOperand(i));
3859         const SCEV *Accum = getAddExpr(Ops);
3860 
3861         // This is not a valid addrec if the step amount is varying each
3862         // loop iteration, but is not itself an addrec in this loop.
3863         if (isLoopInvariant(Accum, L) ||
3864             (isa<SCEVAddRecExpr>(Accum) &&
3865              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3866           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3867 
3868           // If the increment doesn't overflow, then neither the addrec nor
3869           // the post-increment will overflow.
3870           if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3871             if (OBO->getOperand(0) == PN) {
3872               if (OBO->hasNoUnsignedWrap())
3873                 Flags = setFlags(Flags, SCEV::FlagNUW);
3874               if (OBO->hasNoSignedWrap())
3875                 Flags = setFlags(Flags, SCEV::FlagNSW);
3876             }
3877           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
3878             // If the increment is an inbounds GEP, then we know the address
3879             // space cannot be wrapped around. We cannot make any guarantee
3880             // about signed or unsigned overflow because pointers are
3881             // unsigned but we may have a negative index from the base
3882             // pointer. We can guarantee that no unsigned wrap occurs if the
3883             // indices form a positive value.
3884             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
3885               Flags = setFlags(Flags, SCEV::FlagNW);
3886 
3887               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3888               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3889                 Flags = setFlags(Flags, SCEV::FlagNUW);
3890             }
3891 
3892             // We cannot transfer nuw and nsw flags from subtraction
3893             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
3894             // for instance.
3895           }
3896 
3897           const SCEV *StartVal = getSCEV(StartValueV);
3898           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3899 
3900           // Since the no-wrap flags are on the increment, they apply to the
3901           // post-incremented value as well.
3902           if (isLoopInvariant(Accum, L))
3903             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
3904 
3905           // Okay, for the entire analysis of this edge we assumed the PHI
3906           // to be symbolic.  We now need to go back and purge all of the
3907           // entries for the scalars that use the symbolic expression.
3908           forgetSymbolicName(PN, SymbolicName);
3909           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3910           return PHISCEV;
3911         }
3912       }
3913     } else {
3914       // Otherwise, this could be a loop like this:
3915       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
3916       // In this case, j = {1,+,1}  and BEValue is j.
3917       // Because the other in-value of i (0) fits the evolution of BEValue
3918       // i really is an addrec evolution.
3919       //
3920       // We can generalize this saying that i is the shifted value of BEValue
3921       // by one iteration:
3922       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
3923       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
3924       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
3925       if (Shifted != getCouldNotCompute() &&
3926           Start != getCouldNotCompute()) {
3927         const SCEV *StartVal = getSCEV(StartValueV);
3928         if (Start == StartVal) {
3929           // Okay, for the entire analysis of this edge we assumed the PHI
3930           // to be symbolic.  We now need to go back and purge all of the
3931           // entries for the scalars that use the symbolic expression.
3932           forgetSymbolicName(PN, SymbolicName);
3933           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
3934           return Shifted;
3935         }
3936       }
3937     }
3938 
3939     // Remove the temporary PHI node SCEV that has been inserted while intending
3940     // to create an AddRecExpr for this PHI node. We can not keep this temporary
3941     // as it will prevent later (possibly simpler) SCEV expressions to be added
3942     // to the ValueExprMap.
3943     ValueExprMap.erase(PN);
3944   }
3945 
3946   return nullptr;
3947 }
3948 
3949 // Checks if the SCEV S is available at BB.  S is considered available at BB
3950 // if S can be materialized at BB without introducing a fault.
3951 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
3952                                BasicBlock *BB) {
3953   struct CheckAvailable {
3954     bool TraversalDone = false;
3955     bool Available = true;
3956 
3957     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
3958     BasicBlock *BB = nullptr;
3959     DominatorTree &DT;
3960 
3961     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
3962       : L(L), BB(BB), DT(DT) {}
3963 
3964     bool setUnavailable() {
3965       TraversalDone = true;
3966       Available = false;
3967       return false;
3968     }
3969 
3970     bool follow(const SCEV *S) {
3971       switch (S->getSCEVType()) {
3972       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
3973       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
3974         // These expressions are available if their operand(s) is/are.
3975         return true;
3976 
3977       case scAddRecExpr: {
3978         // We allow add recurrences that are on the loop BB is in, or some
3979         // outer loop.  This guarantees availability because the value of the
3980         // add recurrence at BB is simply the "current" value of the induction
3981         // variable.  We can relax this in the future; for instance an add
3982         // recurrence on a sibling dominating loop is also available at BB.
3983         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
3984         if (L && (ARLoop == L || ARLoop->contains(L)))
3985           return true;
3986 
3987         return setUnavailable();
3988       }
3989 
3990       case scUnknown: {
3991         // For SCEVUnknown, we check for simple dominance.
3992         const auto *SU = cast<SCEVUnknown>(S);
3993         Value *V = SU->getValue();
3994 
3995         if (isa<Argument>(V))
3996           return false;
3997 
3998         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
3999           return false;
4000 
4001         return setUnavailable();
4002       }
4003 
4004       case scUDivExpr:
4005       case scCouldNotCompute:
4006         // We do not try to smart about these at all.
4007         return setUnavailable();
4008       }
4009       llvm_unreachable("switch should be fully covered!");
4010     }
4011 
4012     bool isDone() { return TraversalDone; }
4013   };
4014 
4015   CheckAvailable CA(L, BB, DT);
4016   SCEVTraversal<CheckAvailable> ST(CA);
4017 
4018   ST.visitAll(S);
4019   return CA.Available;
4020 }
4021 
4022 // Try to match a control flow sequence that branches out at BI and merges back
4023 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4024 // match.
4025 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4026                           Value *&C, Value *&LHS, Value *&RHS) {
4027   C = BI->getCondition();
4028 
4029   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4030   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4031 
4032   if (!LeftEdge.isSingleEdge())
4033     return false;
4034 
4035   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4036 
4037   Use &LeftUse = Merge->getOperandUse(0);
4038   Use &RightUse = Merge->getOperandUse(1);
4039 
4040   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4041     LHS = LeftUse;
4042     RHS = RightUse;
4043     return true;
4044   }
4045 
4046   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4047     LHS = RightUse;
4048     RHS = LeftUse;
4049     return true;
4050   }
4051 
4052   return false;
4053 }
4054 
4055 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4056   if (PN->getNumIncomingValues() == 2) {
4057     const Loop *L = LI.getLoopFor(PN->getParent());
4058 
4059     // We don't want to break LCSSA, even in a SCEV expression tree.
4060     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4061       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4062         return nullptr;
4063 
4064     // Try to match
4065     //
4066     //  br %cond, label %left, label %right
4067     // left:
4068     //  br label %merge
4069     // right:
4070     //  br label %merge
4071     // merge:
4072     //  V = phi [ %x, %left ], [ %y, %right ]
4073     //
4074     // as "select %cond, %x, %y"
4075 
4076     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4077     assert(IDom && "At least the entry block should dominate PN");
4078 
4079     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4080     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4081 
4082     if (BI && BI->isConditional() &&
4083         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4084         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4085         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4086       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4087   }
4088 
4089   return nullptr;
4090 }
4091 
4092 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4093   if (const SCEV *S = createAddRecFromPHI(PN))
4094     return S;
4095 
4096   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4097     return S;
4098 
4099   // If the PHI has a single incoming value, follow that value, unless the
4100   // PHI's incoming blocks are in a different loop, in which case doing so
4101   // risks breaking LCSSA form. Instcombine would normally zap these, but
4102   // it doesn't have DominatorTree information, so it may miss cases.
4103   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4104     if (LI.replacementPreservesLCSSAForm(PN, V))
4105       return getSCEV(V);
4106 
4107   // If it's not a loop phi, we can't handle it yet.
4108   return getUnknown(PN);
4109 }
4110 
4111 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4112                                                       Value *Cond,
4113                                                       Value *TrueVal,
4114                                                       Value *FalseVal) {
4115   // Handle "constant" branch or select. This can occur for instance when a
4116   // loop pass transforms an inner loop and moves on to process the outer loop.
4117   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4118     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4119 
4120   // Try to match some simple smax or umax patterns.
4121   auto *ICI = dyn_cast<ICmpInst>(Cond);
4122   if (!ICI)
4123     return getUnknown(I);
4124 
4125   Value *LHS = ICI->getOperand(0);
4126   Value *RHS = ICI->getOperand(1);
4127 
4128   switch (ICI->getPredicate()) {
4129   case ICmpInst::ICMP_SLT:
4130   case ICmpInst::ICMP_SLE:
4131     std::swap(LHS, RHS);
4132   // fall through
4133   case ICmpInst::ICMP_SGT:
4134   case ICmpInst::ICMP_SGE:
4135     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4136     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4137     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4138       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4139       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4140       const SCEV *LA = getSCEV(TrueVal);
4141       const SCEV *RA = getSCEV(FalseVal);
4142       const SCEV *LDiff = getMinusSCEV(LA, LS);
4143       const SCEV *RDiff = getMinusSCEV(RA, RS);
4144       if (LDiff == RDiff)
4145         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4146       LDiff = getMinusSCEV(LA, RS);
4147       RDiff = getMinusSCEV(RA, LS);
4148       if (LDiff == RDiff)
4149         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4150     }
4151     break;
4152   case ICmpInst::ICMP_ULT:
4153   case ICmpInst::ICMP_ULE:
4154     std::swap(LHS, RHS);
4155   // fall through
4156   case ICmpInst::ICMP_UGT:
4157   case ICmpInst::ICMP_UGE:
4158     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4159     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4160     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4161       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4162       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4163       const SCEV *LA = getSCEV(TrueVal);
4164       const SCEV *RA = getSCEV(FalseVal);
4165       const SCEV *LDiff = getMinusSCEV(LA, LS);
4166       const SCEV *RDiff = getMinusSCEV(RA, RS);
4167       if (LDiff == RDiff)
4168         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4169       LDiff = getMinusSCEV(LA, RS);
4170       RDiff = getMinusSCEV(RA, LS);
4171       if (LDiff == RDiff)
4172         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4173     }
4174     break;
4175   case ICmpInst::ICMP_NE:
4176     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4177     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4178         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4179       const SCEV *One = getOne(I->getType());
4180       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4181       const SCEV *LA = getSCEV(TrueVal);
4182       const SCEV *RA = getSCEV(FalseVal);
4183       const SCEV *LDiff = getMinusSCEV(LA, LS);
4184       const SCEV *RDiff = getMinusSCEV(RA, One);
4185       if (LDiff == RDiff)
4186         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4187     }
4188     break;
4189   case ICmpInst::ICMP_EQ:
4190     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4191     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4192         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4193       const SCEV *One = getOne(I->getType());
4194       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4195       const SCEV *LA = getSCEV(TrueVal);
4196       const SCEV *RA = getSCEV(FalseVal);
4197       const SCEV *LDiff = getMinusSCEV(LA, One);
4198       const SCEV *RDiff = getMinusSCEV(RA, LS);
4199       if (LDiff == RDiff)
4200         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4201     }
4202     break;
4203   default:
4204     break;
4205   }
4206 
4207   return getUnknown(I);
4208 }
4209 
4210 /// createNodeForGEP - Expand GEP instructions into add and multiply
4211 /// operations. This allows them to be analyzed by regular SCEV code.
4212 ///
4213 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4214   // Don't attempt to analyze GEPs over unsized objects.
4215   if (!GEP->getSourceElementType()->isSized())
4216     return getUnknown(GEP);
4217 
4218   SmallVector<const SCEV *, 4> IndexExprs;
4219   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4220     IndexExprs.push_back(getSCEV(*Index));
4221   return getGEPExpr(GEP->getSourceElementType(),
4222                     getSCEV(GEP->getPointerOperand()),
4223                     IndexExprs, GEP->isInBounds());
4224 }
4225 
4226 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4227 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
4228 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
4229 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
4230 uint32_t
4231 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4232   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4233     return C->getAPInt().countTrailingZeros();
4234 
4235   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4236     return std::min(GetMinTrailingZeros(T->getOperand()),
4237                     (uint32_t)getTypeSizeInBits(T->getType()));
4238 
4239   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4240     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4241     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4242              getTypeSizeInBits(E->getType()) : OpRes;
4243   }
4244 
4245   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4246     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4247     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4248              getTypeSizeInBits(E->getType()) : OpRes;
4249   }
4250 
4251   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4252     // The result is the min of all operands results.
4253     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4254     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4255       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4256     return MinOpRes;
4257   }
4258 
4259   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4260     // The result is the sum of all operands results.
4261     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4262     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4263     for (unsigned i = 1, e = M->getNumOperands();
4264          SumOpRes != BitWidth && i != e; ++i)
4265       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
4266                           BitWidth);
4267     return SumOpRes;
4268   }
4269 
4270   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4271     // The result is the min of all operands results.
4272     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4273     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4274       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4275     return MinOpRes;
4276   }
4277 
4278   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4279     // The result is the min of all operands results.
4280     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4281     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4282       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4283     return MinOpRes;
4284   }
4285 
4286   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4287     // The result is the min of all operands results.
4288     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4289     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4290       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4291     return MinOpRes;
4292   }
4293 
4294   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4295     // For a SCEVUnknown, ask ValueTracking.
4296     unsigned BitWidth = getTypeSizeInBits(U->getType());
4297     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4298     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4299                      nullptr, &DT);
4300     return Zeros.countTrailingOnes();
4301   }
4302 
4303   // SCEVUDivExpr
4304   return 0;
4305 }
4306 
4307 /// GetRangeFromMetadata - Helper method to assign a range to V from
4308 /// metadata present in the IR.
4309 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4310   if (Instruction *I = dyn_cast<Instruction>(V))
4311     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4312       return getConstantRangeFromMetadata(*MD);
4313 
4314   return None;
4315 }
4316 
4317 /// getRange - Determine the range for a particular SCEV.  If SignHint is
4318 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4319 /// with a "cleaner" unsigned (resp. signed) representation.
4320 ///
4321 ConstantRange
4322 ScalarEvolution::getRange(const SCEV *S,
4323                           ScalarEvolution::RangeSignHint SignHint) {
4324   DenseMap<const SCEV *, ConstantRange> &Cache =
4325       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4326                                                        : SignedRanges;
4327 
4328   // See if we've computed this range already.
4329   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4330   if (I != Cache.end())
4331     return I->second;
4332 
4333   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4334     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4335 
4336   unsigned BitWidth = getTypeSizeInBits(S->getType());
4337   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4338 
4339   // If the value has known zeros, the maximum value will have those known zeros
4340   // as well.
4341   uint32_t TZ = GetMinTrailingZeros(S);
4342   if (TZ != 0) {
4343     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4344       ConservativeResult =
4345           ConstantRange(APInt::getMinValue(BitWidth),
4346                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4347     else
4348       ConservativeResult = ConstantRange(
4349           APInt::getSignedMinValue(BitWidth),
4350           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4351   }
4352 
4353   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4354     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4355     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4356       X = X.add(getRange(Add->getOperand(i), SignHint));
4357     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4358   }
4359 
4360   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4361     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4362     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4363       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4364     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4365   }
4366 
4367   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4368     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4369     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4370       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4371     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4372   }
4373 
4374   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4375     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4376     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4377       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4378     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4379   }
4380 
4381   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4382     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4383     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4384     return setRange(UDiv, SignHint,
4385                     ConservativeResult.intersectWith(X.udiv(Y)));
4386   }
4387 
4388   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4389     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4390     return setRange(ZExt, SignHint,
4391                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4392   }
4393 
4394   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4395     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4396     return setRange(SExt, SignHint,
4397                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4398   }
4399 
4400   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4401     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4402     return setRange(Trunc, SignHint,
4403                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4404   }
4405 
4406   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4407     // If there's no unsigned wrap, the value will never be less than its
4408     // initial value.
4409     if (AddRec->hasNoUnsignedWrap())
4410       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4411         if (!C->getValue()->isZero())
4412           ConservativeResult = ConservativeResult.intersectWith(
4413               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4414 
4415     // If there's no signed wrap, and all the operands have the same sign or
4416     // zero, the value won't ever change sign.
4417     if (AddRec->hasNoSignedWrap()) {
4418       bool AllNonNeg = true;
4419       bool AllNonPos = true;
4420       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4421         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4422         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4423       }
4424       if (AllNonNeg)
4425         ConservativeResult = ConservativeResult.intersectWith(
4426           ConstantRange(APInt(BitWidth, 0),
4427                         APInt::getSignedMinValue(BitWidth)));
4428       else if (AllNonPos)
4429         ConservativeResult = ConservativeResult.intersectWith(
4430           ConstantRange(APInt::getSignedMinValue(BitWidth),
4431                         APInt(BitWidth, 1)));
4432     }
4433 
4434     // TODO: non-affine addrec
4435     if (AddRec->isAffine()) {
4436       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4437       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4438           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4439         auto RangeFromAffine = getRangeForAffineAR(
4440             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4441             BitWidth);
4442         if (!RangeFromAffine.isFullSet())
4443           ConservativeResult =
4444               ConservativeResult.intersectWith(RangeFromAffine);
4445 
4446         auto RangeFromFactoring = getRangeViaFactoring(
4447             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4448             BitWidth);
4449         if (!RangeFromFactoring.isFullSet())
4450           ConservativeResult =
4451               ConservativeResult.intersectWith(RangeFromFactoring);
4452       }
4453     }
4454 
4455     return setRange(AddRec, SignHint, ConservativeResult);
4456   }
4457 
4458   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4459     // Check if the IR explicitly contains !range metadata.
4460     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4461     if (MDRange.hasValue())
4462       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4463 
4464     // Split here to avoid paying the compile-time cost of calling both
4465     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4466     // if needed.
4467     const DataLayout &DL = getDataLayout();
4468     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4469       // For a SCEVUnknown, ask ValueTracking.
4470       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4471       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4472       if (Ones != ~Zeros + 1)
4473         ConservativeResult =
4474             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4475     } else {
4476       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4477              "generalize as needed!");
4478       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4479       if (NS > 1)
4480         ConservativeResult = ConservativeResult.intersectWith(
4481             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4482                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4483     }
4484 
4485     return setRange(U, SignHint, ConservativeResult);
4486   }
4487 
4488   return setRange(S, SignHint, ConservativeResult);
4489 }
4490 
4491 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4492                                                    const SCEV *Step,
4493                                                    const SCEV *MaxBECount,
4494                                                    unsigned BitWidth) {
4495   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4496          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4497          "Precondition!");
4498 
4499   ConstantRange Result(BitWidth, /* isFullSet = */ true);
4500 
4501   // Check for overflow.  This must be done with ConstantRange arithmetic
4502   // because we could be called from within the ScalarEvolution overflow
4503   // checking code.
4504 
4505   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4506   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4507   ConstantRange ZExtMaxBECountRange =
4508       MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4509 
4510   ConstantRange StepSRange = getSignedRange(Step);
4511   ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4512 
4513   ConstantRange StartURange = getUnsignedRange(Start);
4514   ConstantRange EndURange =
4515       StartURange.add(MaxBECountRange.multiply(StepSRange));
4516 
4517   // Check for unsigned overflow.
4518   ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4519   ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4520   if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4521       ZExtEndURange) {
4522     APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4523                                EndURange.getUnsignedMin());
4524     APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4525                                EndURange.getUnsignedMax());
4526     bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4527     if (!IsFullRange)
4528       Result =
4529           Result.intersectWith(ConstantRange(Min, Max + 1));
4530   }
4531 
4532   ConstantRange StartSRange = getSignedRange(Start);
4533   ConstantRange EndSRange =
4534       StartSRange.add(MaxBECountRange.multiply(StepSRange));
4535 
4536   // Check for signed overflow. This must be done with ConstantRange
4537   // arithmetic because we could be called from within the ScalarEvolution
4538   // overflow checking code.
4539   ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4540   ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4541   if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4542       SExtEndSRange) {
4543     APInt Min =
4544         APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4545     APInt Max =
4546         APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4547     bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4548     if (!IsFullRange)
4549       Result =
4550           Result.intersectWith(ConstantRange(Min, Max + 1));
4551   }
4552 
4553   return Result;
4554 }
4555 
4556 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4557                                                     const SCEV *Step,
4558                                                     const SCEV *MaxBECount,
4559                                                     unsigned BitWidth) {
4560   APInt Offset(BitWidth, 0);
4561 
4562   if (auto *SA = dyn_cast<SCEVAddExpr>(Start)) {
4563     // Peel off a constant offset, if possible.  In the future we could consider
4564     // being smarter here and handle {Start+Step,+,Step} too.
4565     if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4566       return ConstantRange(BitWidth, /* isFullSet = */ true);
4567     Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4568     Start = SA->getOperand(1);
4569   }
4570 
4571   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4572   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4573 
4574   struct SelectPattern {
4575     Value *Condition = nullptr;
4576     APInt TrueValue;
4577     APInt FalseValue;
4578 
4579     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4580                            const SCEV *S) {
4581       Optional<unsigned> CastOp;
4582 
4583       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4584              "Should be!");
4585 
4586       // Peel off a cast operation
4587       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4588         CastOp = SCast->getSCEVType();
4589         S = SCast->getOperand();
4590       }
4591 
4592       using namespace llvm::PatternMatch;
4593 
4594       auto *SU = dyn_cast<SCEVUnknown>(S);
4595       const APInt *TrueVal, *FalseVal;
4596       if (!SU ||
4597           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4598                                           m_APInt(FalseVal)))) {
4599         Condition = nullptr;
4600         return;
4601       }
4602 
4603       TrueValue = *TrueVal;
4604       FalseValue = *FalseVal;
4605 
4606       // Re-apply the cast we peeled off earlier
4607       if (CastOp.hasValue())
4608         switch (*CastOp) {
4609         default:
4610           llvm_unreachable("Unknown SCEV cast type!");
4611 
4612         case scTruncate:
4613           TrueValue = TrueValue.trunc(BitWidth);
4614           FalseValue = FalseValue.trunc(BitWidth);
4615           break;
4616         case scZeroExtend:
4617           TrueValue = TrueValue.zext(BitWidth);
4618           FalseValue = FalseValue.zext(BitWidth);
4619           break;
4620         case scSignExtend:
4621           TrueValue = TrueValue.sext(BitWidth);
4622           FalseValue = FalseValue.sext(BitWidth);
4623           break;
4624         }
4625     }
4626 
4627     bool isRecognized() { return Condition != nullptr; }
4628   };
4629 
4630   SelectPattern StartPattern(*this, BitWidth, Start);
4631   if (!StartPattern.isRecognized())
4632     return ConstantRange(BitWidth, /* isFullSet = */ true);
4633 
4634   SelectPattern StepPattern(*this, BitWidth, Step);
4635   if (!StepPattern.isRecognized())
4636     return ConstantRange(BitWidth, /* isFullSet = */ true);
4637 
4638   if (StartPattern.Condition != StepPattern.Condition) {
4639     // We don't handle this case today; but we could, by considering four
4640     // possibilities below instead of two. I'm not sure if there are cases where
4641     // that will help over what getRange already does, though.
4642     return ConstantRange(BitWidth, /* isFullSet = */ true);
4643   }
4644 
4645   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4646   // construct arbitrary general SCEV expressions here.  This function is called
4647   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4648   // say) can end up caching a suboptimal value.
4649 
4650   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4651   // C2352 and C2512 (otherwise it isn't needed).
4652 
4653   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue + Offset);
4654   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4655   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue + Offset);
4656   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4657 
4658   ConstantRange TrueRange =
4659       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4660   ConstantRange FalseRange =
4661       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4662 
4663   return TrueRange.unionWith(FalseRange);
4664 }
4665 
4666 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4667   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4668   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4669 
4670   // Return early if there are no flags to propagate to the SCEV.
4671   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4672   if (BinOp->hasNoUnsignedWrap())
4673     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4674   if (BinOp->hasNoSignedWrap())
4675     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4676   if (Flags == SCEV::FlagAnyWrap)
4677     return SCEV::FlagAnyWrap;
4678 
4679   // Here we check that BinOp is in the header of the innermost loop
4680   // containing BinOp, since we only deal with instructions in the loop
4681   // header. The actual loop we need to check later will come from an add
4682   // recurrence, but getting that requires computing the SCEV of the operands,
4683   // which can be expensive. This check we can do cheaply to rule out some
4684   // cases early.
4685   Loop *InnermostContainingLoop = LI.getLoopFor(BinOp->getParent());
4686   if (InnermostContainingLoop == nullptr ||
4687       InnermostContainingLoop->getHeader() != BinOp->getParent())
4688     return SCEV::FlagAnyWrap;
4689 
4690   // Only proceed if we can prove that BinOp does not yield poison.
4691   if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap;
4692 
4693   // At this point we know that if V is executed, then it does not wrap
4694   // according to at least one of NSW or NUW. If V is not executed, then we do
4695   // not know if the calculation that V represents would wrap. Multiple
4696   // instructions can map to the same SCEV. If we apply NSW or NUW from V to
4697   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4698   // derived from other instructions that map to the same SCEV. We cannot make
4699   // that guarantee for cases where V is not executed. So we need to find the
4700   // loop that V is considered in relation to and prove that V is executed for
4701   // every iteration of that loop. That implies that the value that V
4702   // calculates does not wrap anywhere in the loop, so then we can apply the
4703   // flags to the SCEV.
4704   //
4705   // We check isLoopInvariant to disambiguate in case we are adding two
4706   // recurrences from different loops, so that we know which loop to prove
4707   // that V is executed in.
4708   for (int OpIndex = 0; OpIndex < 2; ++OpIndex) {
4709     const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex));
4710     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4711       const int OtherOpIndex = 1 - OpIndex;
4712       const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex));
4713       if (isLoopInvariant(OtherOp, AddRec->getLoop()) &&
4714           isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop()))
4715         return Flags;
4716     }
4717   }
4718   return SCEV::FlagAnyWrap;
4719 }
4720 
4721 /// createSCEV - We know that there is no SCEV for the specified value.  Analyze
4722 /// the expression.
4723 ///
4724 const SCEV *ScalarEvolution::createSCEV(Value *V) {
4725   if (!isSCEVable(V->getType()))
4726     return getUnknown(V);
4727 
4728   unsigned Opcode = Instruction::UserOp1;
4729   if (Instruction *I = dyn_cast<Instruction>(V)) {
4730     Opcode = I->getOpcode();
4731 
4732     // Don't attempt to analyze instructions in blocks that aren't
4733     // reachable. Such instructions don't matter, and they aren't required
4734     // to obey basic rules for definitions dominating uses which this
4735     // analysis depends on.
4736     if (!DT.isReachableFromEntry(I->getParent()))
4737       return getUnknown(V);
4738   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
4739     Opcode = CE->getOpcode();
4740   else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4741     return getConstant(CI);
4742   else if (isa<ConstantPointerNull>(V))
4743     return getZero(V->getType());
4744   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4745     return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
4746   else
4747     return getUnknown(V);
4748 
4749   Operator *U = cast<Operator>(V);
4750   switch (Opcode) {
4751   case Instruction::Add: {
4752     // The simple thing to do would be to just call getSCEV on both operands
4753     // and call getAddExpr with the result. However if we're looking at a
4754     // bunch of things all added together, this can be quite inefficient,
4755     // because it leads to N-1 getAddExpr calls for N ultimate operands.
4756     // Instead, gather up all the operands and make a single getAddExpr call.
4757     // LLVM IR canonical form means we need only traverse the left operands.
4758     SmallVector<const SCEV *, 4> AddOps;
4759     for (Value *Op = U;; Op = U->getOperand(0)) {
4760       U = dyn_cast<Operator>(Op);
4761       unsigned Opcode = U ? U->getOpcode() : 0;
4762       if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) {
4763         assert(Op != V && "V should be an add");
4764         AddOps.push_back(getSCEV(Op));
4765         break;
4766       }
4767 
4768       if (auto *OpSCEV = getExistingSCEV(U)) {
4769         AddOps.push_back(OpSCEV);
4770         break;
4771       }
4772 
4773       // If a NUW or NSW flag can be applied to the SCEV for this
4774       // addition, then compute the SCEV for this addition by itself
4775       // with a separate call to getAddExpr. We need to do that
4776       // instead of pushing the operands of the addition onto AddOps,
4777       // since the flags are only known to apply to this particular
4778       // addition - they may not apply to other additions that can be
4779       // formed with operands from AddOps.
4780       const SCEV *RHS = getSCEV(U->getOperand(1));
4781       SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4782       if (Flags != SCEV::FlagAnyWrap) {
4783         const SCEV *LHS = getSCEV(U->getOperand(0));
4784         if (Opcode == Instruction::Sub)
4785           AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4786         else
4787           AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4788         break;
4789       }
4790 
4791       if (Opcode == Instruction::Sub)
4792         AddOps.push_back(getNegativeSCEV(RHS));
4793       else
4794         AddOps.push_back(RHS);
4795     }
4796     return getAddExpr(AddOps);
4797   }
4798 
4799   case Instruction::Mul: {
4800     SmallVector<const SCEV *, 4> MulOps;
4801     for (Value *Op = U;; Op = U->getOperand(0)) {
4802       U = dyn_cast<Operator>(Op);
4803       if (!U || U->getOpcode() != Instruction::Mul) {
4804         assert(Op != V && "V should be a mul");
4805         MulOps.push_back(getSCEV(Op));
4806         break;
4807       }
4808 
4809       if (auto *OpSCEV = getExistingSCEV(U)) {
4810         MulOps.push_back(OpSCEV);
4811         break;
4812       }
4813 
4814       SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U);
4815       if (Flags != SCEV::FlagAnyWrap) {
4816         MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)),
4817                                     getSCEV(U->getOperand(1)), Flags));
4818         break;
4819       }
4820 
4821       MulOps.push_back(getSCEV(U->getOperand(1)));
4822     }
4823     return getMulExpr(MulOps);
4824   }
4825   case Instruction::UDiv:
4826     return getUDivExpr(getSCEV(U->getOperand(0)),
4827                        getSCEV(U->getOperand(1)));
4828   case Instruction::Sub:
4829     return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)),
4830                         getNoWrapFlagsFromUB(U));
4831   case Instruction::And:
4832     // For an expression like x&255 that merely masks off the high bits,
4833     // use zext(trunc(x)) as the SCEV expression.
4834     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4835       if (CI->isNullValue())
4836         return getSCEV(U->getOperand(1));
4837       if (CI->isAllOnesValue())
4838         return getSCEV(U->getOperand(0));
4839       const APInt &A = CI->getValue();
4840 
4841       // Instcombine's ShrinkDemandedConstant may strip bits out of
4842       // constants, obscuring what would otherwise be a low-bits mask.
4843       // Use computeKnownBits to compute what ShrinkDemandedConstant
4844       // knew about to reconstruct a low-bits mask value.
4845       unsigned LZ = A.countLeadingZeros();
4846       unsigned TZ = A.countTrailingZeros();
4847       unsigned BitWidth = A.getBitWidth();
4848       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4849       computeKnownBits(U->getOperand(0), KnownZero, KnownOne, getDataLayout(),
4850                        0, &AC, nullptr, &DT);
4851 
4852       APInt EffectiveMask =
4853           APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4854       if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4855         const SCEV *MulCount = getConstant(
4856             ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4857         return getMulExpr(
4858             getZeroExtendExpr(
4859                 getTruncateExpr(
4860                     getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4861                     IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4862                 U->getType()),
4863             MulCount);
4864       }
4865     }
4866     break;
4867 
4868   case Instruction::Or:
4869     // If the RHS of the Or is a constant, we may have something like:
4870     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
4871     // optimizations will transparently handle this case.
4872     //
4873     // In order for this transformation to be safe, the LHS must be of the
4874     // form X*(2^n) and the Or constant must be less than 2^n.
4875     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4876       const SCEV *LHS = getSCEV(U->getOperand(0));
4877       const APInt &CIVal = CI->getValue();
4878       if (GetMinTrailingZeros(LHS) >=
4879           (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4880         // Build a plain add SCEV.
4881         const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4882         // If the LHS of the add was an addrec and it has no-wrap flags,
4883         // transfer the no-wrap flags, since an or won't introduce a wrap.
4884         if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4885           const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
4886           const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4887             OldAR->getNoWrapFlags());
4888         }
4889         return S;
4890       }
4891     }
4892     break;
4893   case Instruction::Xor:
4894     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
4895       // If the RHS of the xor is a signbit, then this is just an add.
4896       // Instcombine turns add of signbit into xor as a strength reduction step.
4897       if (CI->getValue().isSignBit())
4898         return getAddExpr(getSCEV(U->getOperand(0)),
4899                           getSCEV(U->getOperand(1)));
4900 
4901       // If the RHS of xor is -1, then this is a not operation.
4902       if (CI->isAllOnesValue())
4903         return getNotSCEV(getSCEV(U->getOperand(0)));
4904 
4905       // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4906       // This is a variant of the check for xor with -1, and it handles
4907       // the case where instcombine has trimmed non-demanded bits out
4908       // of an xor with -1.
4909       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4910         if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4911           if (BO->getOpcode() == Instruction::And &&
4912               LCI->getValue() == CI->getValue())
4913             if (const SCEVZeroExtendExpr *Z =
4914                   dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
4915               Type *UTy = U->getType();
4916               const SCEV *Z0 = Z->getOperand();
4917               Type *Z0Ty = Z0->getType();
4918               unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4919 
4920               // If C is a low-bits mask, the zero extend is serving to
4921               // mask off the high bits. Complement the operand and
4922               // re-apply the zext.
4923               if (APIntOps::isMask(Z0TySize, CI->getValue()))
4924                 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4925 
4926               // If C is a single bit, it may be in the sign-bit position
4927               // before the zero-extend. In this case, represent the xor
4928               // using an add, which is equivalent, and re-apply the zext.
4929               APInt Trunc = CI->getValue().trunc(Z0TySize);
4930               if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
4931                   Trunc.isSignBit())
4932                 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4933                                          UTy);
4934             }
4935     }
4936     break;
4937 
4938   case Instruction::Shl:
4939     // Turn shift left of a constant amount into a multiply.
4940     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4941       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4942 
4943       // If the shift count is not less than the bitwidth, the result of
4944       // the shift is undefined. Don't try to analyze it, because the
4945       // resolution chosen here may differ from the resolution chosen in
4946       // other parts of the compiler.
4947       if (SA->getValue().uge(BitWidth))
4948         break;
4949 
4950       // It is currently not resolved how to interpret NSW for left
4951       // shift by BitWidth - 1, so we avoid applying flags in that
4952       // case. Remove this check (or this comment) once the situation
4953       // is resolved. See
4954       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
4955       // and http://reviews.llvm.org/D8890 .
4956       auto Flags = SCEV::FlagAnyWrap;
4957       if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U);
4958 
4959       Constant *X = ConstantInt::get(getContext(),
4960         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4961       return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags);
4962     }
4963     break;
4964 
4965   case Instruction::LShr:
4966     // Turn logical shift right of a constant into a unsigned divide.
4967     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
4968       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
4969 
4970       // If the shift count is not less than the bitwidth, the result of
4971       // the shift is undefined. Don't try to analyze it, because the
4972       // resolution chosen here may differ from the resolution chosen in
4973       // other parts of the compiler.
4974       if (SA->getValue().uge(BitWidth))
4975         break;
4976 
4977       Constant *X = ConstantInt::get(getContext(),
4978         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4979       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
4980     }
4981     break;
4982 
4983   case Instruction::AShr:
4984     // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4985     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
4986       if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
4987         if (L->getOpcode() == Instruction::Shl &&
4988             L->getOperand(1) == U->getOperand(1)) {
4989           uint64_t BitWidth = getTypeSizeInBits(U->getType());
4990 
4991           // If the shift count is not less than the bitwidth, the result of
4992           // the shift is undefined. Don't try to analyze it, because the
4993           // resolution chosen here may differ from the resolution chosen in
4994           // other parts of the compiler.
4995           if (CI->getValue().uge(BitWidth))
4996             break;
4997 
4998           uint64_t Amt = BitWidth - CI->getZExtValue();
4999           if (Amt == BitWidth)
5000             return getSCEV(L->getOperand(0));       // shift by zero --> noop
5001           return
5002             getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
5003                                               IntegerType::get(getContext(),
5004                                                                Amt)),
5005                               U->getType());
5006         }
5007     break;
5008 
5009   case Instruction::Trunc:
5010     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5011 
5012   case Instruction::ZExt:
5013     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5014 
5015   case Instruction::SExt:
5016     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5017 
5018   case Instruction::BitCast:
5019     // BitCasts are no-op casts so we just eliminate the cast.
5020     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5021       return getSCEV(U->getOperand(0));
5022     break;
5023 
5024   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5025   // lead to pointer expressions which cannot safely be expanded to GEPs,
5026   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5027   // simplifying integer expressions.
5028 
5029   case Instruction::GetElementPtr:
5030     return createNodeForGEP(cast<GEPOperator>(U));
5031 
5032   case Instruction::PHI:
5033     return createNodeForPHI(cast<PHINode>(U));
5034 
5035   case Instruction::Select:
5036     // U can also be a select constant expr, which let fall through.  Since
5037     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5038     // constant expressions cannot have instructions as operands, we'd have
5039     // returned getUnknown for a select constant expressions anyway.
5040     if (isa<Instruction>(U))
5041       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5042                                       U->getOperand(1), U->getOperand(2));
5043 
5044   default: // We cannot analyze this expression.
5045     break;
5046   }
5047 
5048   return getUnknown(V);
5049 }
5050 
5051 
5052 
5053 //===----------------------------------------------------------------------===//
5054 //                   Iteration Count Computation Code
5055 //
5056 
5057 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5058   if (BasicBlock *ExitingBB = L->getExitingBlock())
5059     return getSmallConstantTripCount(L, ExitingBB);
5060 
5061   // No trip count information for multiple exits.
5062   return 0;
5063 }
5064 
5065 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
5066 /// normal unsigned value. Returns 0 if the trip count is unknown or not
5067 /// constant. Will also return 0 if the maximum trip count is very large (>=
5068 /// 2^32).
5069 ///
5070 /// This "trip count" assumes that control exits via ExitingBlock. More
5071 /// precisely, it is the number of times that control may reach ExitingBlock
5072 /// before taking the branch. For loops with multiple exits, it may not be the
5073 /// number times that the loop header executes because the loop may exit
5074 /// prematurely via another branch.
5075 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5076                                                     BasicBlock *ExitingBlock) {
5077   assert(ExitingBlock && "Must pass a non-null exiting block!");
5078   assert(L->isLoopExiting(ExitingBlock) &&
5079          "Exiting block must actually branch out of the loop!");
5080   const SCEVConstant *ExitCount =
5081       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5082   if (!ExitCount)
5083     return 0;
5084 
5085   ConstantInt *ExitConst = ExitCount->getValue();
5086 
5087   // Guard against huge trip counts.
5088   if (ExitConst->getValue().getActiveBits() > 32)
5089     return 0;
5090 
5091   // In case of integer overflow, this returns 0, which is correct.
5092   return ((unsigned)ExitConst->getZExtValue()) + 1;
5093 }
5094 
5095 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5096   if (BasicBlock *ExitingBB = L->getExitingBlock())
5097     return getSmallConstantTripMultiple(L, ExitingBB);
5098 
5099   // No trip multiple information for multiple exits.
5100   return 0;
5101 }
5102 
5103 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
5104 /// trip count of this loop as a normal unsigned value, if possible. This
5105 /// means that the actual trip count is always a multiple of the returned
5106 /// value (don't forget the trip count could very well be zero as well!).
5107 ///
5108 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5109 /// multiple of a constant (which is also the case if the trip count is simply
5110 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5111 /// if the trip count is very large (>= 2^32).
5112 ///
5113 /// As explained in the comments for getSmallConstantTripCount, this assumes
5114 /// that control exits the loop via ExitingBlock.
5115 unsigned
5116 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5117                                               BasicBlock *ExitingBlock) {
5118   assert(ExitingBlock && "Must pass a non-null exiting block!");
5119   assert(L->isLoopExiting(ExitingBlock) &&
5120          "Exiting block must actually branch out of the loop!");
5121   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5122   if (ExitCount == getCouldNotCompute())
5123     return 1;
5124 
5125   // Get the trip count from the BE count by adding 1.
5126   const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5127   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5128   // to factor simple cases.
5129   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5130     TCMul = Mul->getOperand(0);
5131 
5132   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5133   if (!MulC)
5134     return 1;
5135 
5136   ConstantInt *Result = MulC->getValue();
5137 
5138   // Guard against huge trip counts (this requires checking
5139   // for zero to handle the case where the trip count == -1 and the
5140   // addition wraps).
5141   if (!Result || Result->getValue().getActiveBits() > 32 ||
5142       Result->getValue().getActiveBits() == 0)
5143     return 1;
5144 
5145   return (unsigned)Result->getZExtValue();
5146 }
5147 
5148 // getExitCount - Get the expression for the number of loop iterations for which
5149 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
5150 // SCEVCouldNotCompute.
5151 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5152   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5153 }
5154 
5155 /// getBackedgeTakenCount - If the specified loop has a predictable
5156 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
5157 /// object. The backedge-taken count is the number of times the loop header
5158 /// will be branched to from within the loop. This is one less than the
5159 /// trip count of the loop, since it doesn't count the first iteration,
5160 /// when the header is branched to from outside the loop.
5161 ///
5162 /// Note that it is not valid to call this method on a loop without a
5163 /// loop-invariant backedge-taken count (see
5164 /// hasLoopInvariantBackedgeTakenCount).
5165 ///
5166 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5167   return getBackedgeTakenInfo(L).getExact(this);
5168 }
5169 
5170 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
5171 /// return the least SCEV value that is known never to be less than the
5172 /// actual backedge taken count.
5173 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5174   return getBackedgeTakenInfo(L).getMax(this);
5175 }
5176 
5177 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
5178 /// onto the given Worklist.
5179 static void
5180 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5181   BasicBlock *Header = L->getHeader();
5182 
5183   // Push all Loop-header PHIs onto the Worklist stack.
5184   for (BasicBlock::iterator I = Header->begin();
5185        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5186     Worklist.push_back(PN);
5187 }
5188 
5189 const ScalarEvolution::BackedgeTakenInfo &
5190 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5191   // Initially insert an invalid entry for this loop. If the insertion
5192   // succeeds, proceed to actually compute a backedge-taken count and
5193   // update the value. The temporary CouldNotCompute value tells SCEV
5194   // code elsewhere that it shouldn't attempt to request a new
5195   // backedge-taken count, which could result in infinite recursion.
5196   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5197       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5198   if (!Pair.second)
5199     return Pair.first->second;
5200 
5201   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5202   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5203   // must be cleared in this scope.
5204   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5205 
5206   if (Result.getExact(this) != getCouldNotCompute()) {
5207     assert(isLoopInvariant(Result.getExact(this), L) &&
5208            isLoopInvariant(Result.getMax(this), L) &&
5209            "Computed backedge-taken count isn't loop invariant for loop!");
5210     ++NumTripCountsComputed;
5211   }
5212   else if (Result.getMax(this) == getCouldNotCompute() &&
5213            isa<PHINode>(L->getHeader()->begin())) {
5214     // Only count loops that have phi nodes as not being computable.
5215     ++NumTripCountsNotComputed;
5216   }
5217 
5218   // Now that we know more about the trip count for this loop, forget any
5219   // existing SCEV values for PHI nodes in this loop since they are only
5220   // conservative estimates made without the benefit of trip count
5221   // information. This is similar to the code in forgetLoop, except that
5222   // it handles SCEVUnknown PHI nodes specially.
5223   if (Result.hasAnyInfo()) {
5224     SmallVector<Instruction *, 16> Worklist;
5225     PushLoopPHIs(L, Worklist);
5226 
5227     SmallPtrSet<Instruction *, 8> Visited;
5228     while (!Worklist.empty()) {
5229       Instruction *I = Worklist.pop_back_val();
5230       if (!Visited.insert(I).second)
5231         continue;
5232 
5233       ValueExprMapType::iterator It =
5234         ValueExprMap.find_as(static_cast<Value *>(I));
5235       if (It != ValueExprMap.end()) {
5236         const SCEV *Old = It->second;
5237 
5238         // SCEVUnknown for a PHI either means that it has an unrecognized
5239         // structure, or it's a PHI that's in the progress of being computed
5240         // by createNodeForPHI.  In the former case, additional loop trip
5241         // count information isn't going to change anything. In the later
5242         // case, createNodeForPHI will perform the necessary updates on its
5243         // own when it gets to that point.
5244         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5245           forgetMemoizedResults(Old);
5246           ValueExprMap.erase(It);
5247         }
5248         if (PHINode *PN = dyn_cast<PHINode>(I))
5249           ConstantEvolutionLoopExitValue.erase(PN);
5250       }
5251 
5252       PushDefUseChildren(I, Worklist);
5253     }
5254   }
5255 
5256   // Re-lookup the insert position, since the call to
5257   // computeBackedgeTakenCount above could result in a
5258   // recusive call to getBackedgeTakenInfo (on a different
5259   // loop), which would invalidate the iterator computed
5260   // earlier.
5261   return BackedgeTakenCounts.find(L)->second = Result;
5262 }
5263 
5264 /// forgetLoop - This method should be called by the client when it has
5265 /// changed a loop in a way that may effect ScalarEvolution's ability to
5266 /// compute a trip count, or if the loop is deleted.
5267 void ScalarEvolution::forgetLoop(const Loop *L) {
5268   // Drop any stored trip count value.
5269   DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
5270     BackedgeTakenCounts.find(L);
5271   if (BTCPos != BackedgeTakenCounts.end()) {
5272     BTCPos->second.clear();
5273     BackedgeTakenCounts.erase(BTCPos);
5274   }
5275 
5276   // Drop information about expressions based on loop-header PHIs.
5277   SmallVector<Instruction *, 16> Worklist;
5278   PushLoopPHIs(L, Worklist);
5279 
5280   SmallPtrSet<Instruction *, 8> Visited;
5281   while (!Worklist.empty()) {
5282     Instruction *I = Worklist.pop_back_val();
5283     if (!Visited.insert(I).second)
5284       continue;
5285 
5286     ValueExprMapType::iterator It =
5287       ValueExprMap.find_as(static_cast<Value *>(I));
5288     if (It != ValueExprMap.end()) {
5289       forgetMemoizedResults(It->second);
5290       ValueExprMap.erase(It);
5291       if (PHINode *PN = dyn_cast<PHINode>(I))
5292         ConstantEvolutionLoopExitValue.erase(PN);
5293     }
5294 
5295     PushDefUseChildren(I, Worklist);
5296   }
5297 
5298   // Forget all contained loops too, to avoid dangling entries in the
5299   // ValuesAtScopes map.
5300   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5301     forgetLoop(*I);
5302 }
5303 
5304 /// forgetValue - This method should be called by the client when it has
5305 /// changed a value in a way that may effect its value, or which may
5306 /// disconnect it from a def-use chain linking it to a loop.
5307 void ScalarEvolution::forgetValue(Value *V) {
5308   Instruction *I = dyn_cast<Instruction>(V);
5309   if (!I) return;
5310 
5311   // Drop information about expressions based on loop-header PHIs.
5312   SmallVector<Instruction *, 16> Worklist;
5313   Worklist.push_back(I);
5314 
5315   SmallPtrSet<Instruction *, 8> Visited;
5316   while (!Worklist.empty()) {
5317     I = Worklist.pop_back_val();
5318     if (!Visited.insert(I).second)
5319       continue;
5320 
5321     ValueExprMapType::iterator It =
5322       ValueExprMap.find_as(static_cast<Value *>(I));
5323     if (It != ValueExprMap.end()) {
5324       forgetMemoizedResults(It->second);
5325       ValueExprMap.erase(It);
5326       if (PHINode *PN = dyn_cast<PHINode>(I))
5327         ConstantEvolutionLoopExitValue.erase(PN);
5328     }
5329 
5330     PushDefUseChildren(I, Worklist);
5331   }
5332 }
5333 
5334 /// getExact - Get the exact loop backedge taken count considering all loop
5335 /// exits. A computable result can only be returned for loops with a single
5336 /// exit.  Returning the minimum taken count among all exits is incorrect
5337 /// because one of the loop's exit limit's may have been skipped. HowFarToZero
5338 /// assumes that the limit of each loop test is never skipped. This is a valid
5339 /// assumption as long as the loop exits via that test. For precise results, it
5340 /// is the caller's responsibility to specify the relevant loop exit using
5341 /// getExact(ExitingBlock, SE).
5342 const SCEV *
5343 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
5344   // If any exits were not computable, the loop is not computable.
5345   if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5346 
5347   // We need exactly one computable exit.
5348   if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
5349   assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5350 
5351   const SCEV *BECount = nullptr;
5352   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
5353        ENT != nullptr; ENT = ENT->getNextExit()) {
5354 
5355     assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5356 
5357     if (!BECount)
5358       BECount = ENT->ExactNotTaken;
5359     else if (BECount != ENT->ExactNotTaken)
5360       return SE->getCouldNotCompute();
5361   }
5362   assert(BECount && "Invalid not taken count for loop exit");
5363   return BECount;
5364 }
5365 
5366 /// getExact - Get the exact not taken count for this loop exit.
5367 const SCEV *
5368 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5369                                              ScalarEvolution *SE) const {
5370   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
5371        ENT != nullptr; ENT = ENT->getNextExit()) {
5372 
5373     if (ENT->ExitingBlock == ExitingBlock)
5374       return ENT->ExactNotTaken;
5375   }
5376   return SE->getCouldNotCompute();
5377 }
5378 
5379 /// getMax - Get the max backedge taken count for the loop.
5380 const SCEV *
5381 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5382   return Max ? Max : SE->getCouldNotCompute();
5383 }
5384 
5385 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5386                                                     ScalarEvolution *SE) const {
5387   if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5388     return true;
5389 
5390   if (!ExitNotTaken.ExitingBlock)
5391     return false;
5392 
5393   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
5394        ENT != nullptr; ENT = ENT->getNextExit()) {
5395 
5396     if (ENT->ExactNotTaken != SE->getCouldNotCompute()
5397         && SE->hasOperand(ENT->ExactNotTaken, S)) {
5398       return true;
5399     }
5400   }
5401   return false;
5402 }
5403 
5404 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5405 /// computable exit into a persistent ExitNotTakenInfo array.
5406 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5407   SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
5408   bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
5409 
5410   if (!Complete)
5411     ExitNotTaken.setIncomplete();
5412 
5413   unsigned NumExits = ExitCounts.size();
5414   if (NumExits == 0) return;
5415 
5416   ExitNotTaken.ExitingBlock = ExitCounts[0].first;
5417   ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
5418   if (NumExits == 1) return;
5419 
5420   // Handle the rare case of multiple computable exits.
5421   ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
5422 
5423   ExitNotTakenInfo *PrevENT = &ExitNotTaken;
5424   for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
5425     PrevENT->setNextExit(ENT);
5426     ENT->ExitingBlock = ExitCounts[i].first;
5427     ENT->ExactNotTaken = ExitCounts[i].second;
5428   }
5429 }
5430 
5431 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
5432 void ScalarEvolution::BackedgeTakenInfo::clear() {
5433   ExitNotTaken.ExitingBlock = nullptr;
5434   ExitNotTaken.ExactNotTaken = nullptr;
5435   delete[] ExitNotTaken.getNextExit();
5436 }
5437 
5438 /// computeBackedgeTakenCount - Compute the number of times the backedge
5439 /// of the specified loop will execute.
5440 ScalarEvolution::BackedgeTakenInfo
5441 ScalarEvolution::computeBackedgeTakenCount(const Loop *L) {
5442   SmallVector<BasicBlock *, 8> ExitingBlocks;
5443   L->getExitingBlocks(ExitingBlocks);
5444 
5445   SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
5446   bool CouldComputeBECount = true;
5447   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5448   const SCEV *MustExitMaxBECount = nullptr;
5449   const SCEV *MayExitMaxBECount = nullptr;
5450 
5451   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5452   // and compute maxBECount.
5453   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5454     BasicBlock *ExitBB = ExitingBlocks[i];
5455     ExitLimit EL = computeExitLimit(L, ExitBB);
5456 
5457     // 1. For each exit that can be computed, add an entry to ExitCounts.
5458     // CouldComputeBECount is true only if all exits can be computed.
5459     if (EL.Exact == getCouldNotCompute())
5460       // We couldn't compute an exact value for this exit, so
5461       // we won't be able to compute an exact value for the loop.
5462       CouldComputeBECount = false;
5463     else
5464       ExitCounts.push_back({ExitBB, EL.Exact});
5465 
5466     // 2. Derive the loop's MaxBECount from each exit's max number of
5467     // non-exiting iterations. Partition the loop exits into two kinds:
5468     // LoopMustExits and LoopMayExits.
5469     //
5470     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5471     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5472     // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5473     // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5474     // considered greater than any computable EL.Max.
5475     if (EL.Max != getCouldNotCompute() && Latch &&
5476         DT.dominates(ExitBB, Latch)) {
5477       if (!MustExitMaxBECount)
5478         MustExitMaxBECount = EL.Max;
5479       else {
5480         MustExitMaxBECount =
5481           getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
5482       }
5483     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5484       if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5485         MayExitMaxBECount = EL.Max;
5486       else {
5487         MayExitMaxBECount =
5488           getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5489       }
5490     }
5491   }
5492   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5493     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5494   return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
5495 }
5496 
5497 ScalarEvolution::ExitLimit
5498 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
5499 
5500   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5501   // at this block and remember the exit block and whether all other targets
5502   // lead to the loop header.
5503   bool MustExecuteLoopHeader = true;
5504   BasicBlock *Exit = nullptr;
5505   for (auto *SBB : successors(ExitingBlock))
5506     if (!L->contains(SBB)) {
5507       if (Exit) // Multiple exit successors.
5508         return getCouldNotCompute();
5509       Exit = SBB;
5510     } else if (SBB != L->getHeader()) {
5511       MustExecuteLoopHeader = false;
5512     }
5513 
5514   // At this point, we know we have a conditional branch that determines whether
5515   // the loop is exited.  However, we don't know if the branch is executed each
5516   // time through the loop.  If not, then the execution count of the branch will
5517   // not be equal to the trip count of the loop.
5518   //
5519   // Currently we check for this by checking to see if the Exit branch goes to
5520   // the loop header.  If so, we know it will always execute the same number of
5521   // times as the loop.  We also handle the case where the exit block *is* the
5522   // loop header.  This is common for un-rotated loops.
5523   //
5524   // If both of those tests fail, walk up the unique predecessor chain to the
5525   // header, stopping if there is an edge that doesn't exit the loop. If the
5526   // header is reached, the execution count of the branch will be equal to the
5527   // trip count of the loop.
5528   //
5529   //  More extensive analysis could be done to handle more cases here.
5530   //
5531   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5532     // The simple checks failed, try climbing the unique predecessor chain
5533     // up to the header.
5534     bool Ok = false;
5535     for (BasicBlock *BB = ExitingBlock; BB; ) {
5536       BasicBlock *Pred = BB->getUniquePredecessor();
5537       if (!Pred)
5538         return getCouldNotCompute();
5539       TerminatorInst *PredTerm = Pred->getTerminator();
5540       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5541         if (PredSucc == BB)
5542           continue;
5543         // If the predecessor has a successor that isn't BB and isn't
5544         // outside the loop, assume the worst.
5545         if (L->contains(PredSucc))
5546           return getCouldNotCompute();
5547       }
5548       if (Pred == L->getHeader()) {
5549         Ok = true;
5550         break;
5551       }
5552       BB = Pred;
5553     }
5554     if (!Ok)
5555       return getCouldNotCompute();
5556   }
5557 
5558   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
5559   TerminatorInst *Term = ExitingBlock->getTerminator();
5560   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5561     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5562     // Proceed to the next level to examine the exit condition expression.
5563     return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
5564                                     BI->getSuccessor(1),
5565                                     /*ControlsExit=*/IsOnlyExit);
5566   }
5567 
5568   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
5569     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
5570                                                 /*ControlsExit=*/IsOnlyExit);
5571 
5572   return getCouldNotCompute();
5573 }
5574 
5575 /// computeExitLimitFromCond - Compute the number of times the
5576 /// backedge of the specified loop will execute if its exit condition
5577 /// were a conditional branch of ExitCond, TBB, and FBB.
5578 ///
5579 /// @param ControlsExit is true if ExitCond directly controls the exit
5580 /// branch. In this case, we can assume that the loop exits only if the
5581 /// condition is true and can infer that failing to meet the condition prior to
5582 /// integer wraparound results in undefined behavior.
5583 ScalarEvolution::ExitLimit
5584 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
5585                                           Value *ExitCond,
5586                                           BasicBlock *TBB,
5587                                           BasicBlock *FBB,
5588                                           bool ControlsExit) {
5589   // Check if the controlling expression for this loop is an And or Or.
5590   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5591     if (BO->getOpcode() == Instruction::And) {
5592       // Recurse on the operands of the and.
5593       bool EitherMayExit = L->contains(TBB);
5594       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5595                                                ControlsExit && !EitherMayExit);
5596       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5597                                                ControlsExit && !EitherMayExit);
5598       const SCEV *BECount = getCouldNotCompute();
5599       const SCEV *MaxBECount = getCouldNotCompute();
5600       if (EitherMayExit) {
5601         // Both conditions must be true for the loop to continue executing.
5602         // Choose the less conservative count.
5603         if (EL0.Exact == getCouldNotCompute() ||
5604             EL1.Exact == getCouldNotCompute())
5605           BECount = getCouldNotCompute();
5606         else
5607           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5608         if (EL0.Max == getCouldNotCompute())
5609           MaxBECount = EL1.Max;
5610         else if (EL1.Max == getCouldNotCompute())
5611           MaxBECount = EL0.Max;
5612         else
5613           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5614       } else {
5615         // Both conditions must be true at the same time for the loop to exit.
5616         // For now, be conservative.
5617         assert(L->contains(FBB) && "Loop block has no successor in loop!");
5618         if (EL0.Max == EL1.Max)
5619           MaxBECount = EL0.Max;
5620         if (EL0.Exact == EL1.Exact)
5621           BECount = EL0.Exact;
5622       }
5623 
5624       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5625       // to be more aggressive when computing BECount than when computing
5626       // MaxBECount.  In these cases it is possible for EL0.Exact and EL1.Exact
5627       // to match, but for EL0.Max and EL1.Max to not.
5628       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5629           !isa<SCEVCouldNotCompute>(BECount))
5630         MaxBECount = BECount;
5631 
5632       return ExitLimit(BECount, MaxBECount);
5633     }
5634     if (BO->getOpcode() == Instruction::Or) {
5635       // Recurse on the operands of the or.
5636       bool EitherMayExit = L->contains(FBB);
5637       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5638                                                ControlsExit && !EitherMayExit);
5639       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5640                                                ControlsExit && !EitherMayExit);
5641       const SCEV *BECount = getCouldNotCompute();
5642       const SCEV *MaxBECount = getCouldNotCompute();
5643       if (EitherMayExit) {
5644         // Both conditions must be false for the loop to continue executing.
5645         // Choose the less conservative count.
5646         if (EL0.Exact == getCouldNotCompute() ||
5647             EL1.Exact == getCouldNotCompute())
5648           BECount = getCouldNotCompute();
5649         else
5650           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5651         if (EL0.Max == getCouldNotCompute())
5652           MaxBECount = EL1.Max;
5653         else if (EL1.Max == getCouldNotCompute())
5654           MaxBECount = EL0.Max;
5655         else
5656           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
5657       } else {
5658         // Both conditions must be false at the same time for the loop to exit.
5659         // For now, be conservative.
5660         assert(L->contains(TBB) && "Loop block has no successor in loop!");
5661         if (EL0.Max == EL1.Max)
5662           MaxBECount = EL0.Max;
5663         if (EL0.Exact == EL1.Exact)
5664           BECount = EL0.Exact;
5665       }
5666 
5667       return ExitLimit(BECount, MaxBECount);
5668     }
5669   }
5670 
5671   // With an icmp, it may be feasible to compute an exact backedge-taken count.
5672   // Proceed to the next level to examine the icmp.
5673   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
5674     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5675 
5676   // Check for a constant condition. These are normally stripped out by
5677   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5678   // preserve the CFG and is temporarily leaving constant conditions
5679   // in place.
5680   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5681     if (L->contains(FBB) == !CI->getZExtValue())
5682       // The backedge is always taken.
5683       return getCouldNotCompute();
5684     else
5685       // The backedge is never taken.
5686       return getZero(CI->getType());
5687   }
5688 
5689   // If it's not an integer or pointer comparison then compute it the hard way.
5690   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5691 }
5692 
5693 ScalarEvolution::ExitLimit
5694 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
5695                                           ICmpInst *ExitCond,
5696                                           BasicBlock *TBB,
5697                                           BasicBlock *FBB,
5698                                           bool ControlsExit) {
5699 
5700   // If the condition was exit on true, convert the condition to exit on false
5701   ICmpInst::Predicate Cond;
5702   if (!L->contains(FBB))
5703     Cond = ExitCond->getPredicate();
5704   else
5705     Cond = ExitCond->getInversePredicate();
5706 
5707   // Handle common loops like: for (X = "string"; *X; ++X)
5708   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5709     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
5710       ExitLimit ItCnt =
5711         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
5712       if (ItCnt.hasAnyInfo())
5713         return ItCnt;
5714     }
5715 
5716   ExitLimit ShiftEL = computeShiftCompareExitLimit(
5717       ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond);
5718   if (ShiftEL.hasAnyInfo())
5719     return ShiftEL;
5720 
5721   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5722   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
5723 
5724   // Try to evaluate any dependencies out of the loop.
5725   LHS = getSCEVAtScope(LHS, L);
5726   RHS = getSCEVAtScope(RHS, L);
5727 
5728   // At this point, we would like to compute how many iterations of the
5729   // loop the predicate will return true for these inputs.
5730   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
5731     // If there is a loop-invariant, force it into the RHS.
5732     std::swap(LHS, RHS);
5733     Cond = ICmpInst::getSwappedPredicate(Cond);
5734   }
5735 
5736   // Simplify the operands before analyzing them.
5737   (void)SimplifyICmpOperands(Cond, LHS, RHS);
5738 
5739   // If we have a comparison of a chrec against a constant, try to use value
5740   // ranges to answer this query.
5741   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5742     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
5743       if (AddRec->getLoop() == L) {
5744         // Form the constant range.
5745         ConstantRange CompRange(
5746             ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
5747 
5748         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
5749         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
5750       }
5751 
5752   switch (Cond) {
5753   case ICmpInst::ICMP_NE: {                     // while (X != Y)
5754     // Convert to: while (X-Y != 0)
5755     ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5756     if (EL.hasAnyInfo()) return EL;
5757     break;
5758   }
5759   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
5760     // Convert to: while (X-Y == 0)
5761     ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5762     if (EL.hasAnyInfo()) return EL;
5763     break;
5764   }
5765   case ICmpInst::ICMP_SLT:
5766   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
5767     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
5768     ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
5769     if (EL.hasAnyInfo()) return EL;
5770     break;
5771   }
5772   case ICmpInst::ICMP_SGT:
5773   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
5774     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
5775     ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
5776     if (EL.hasAnyInfo()) return EL;
5777     break;
5778   }
5779   default:
5780     break;
5781   }
5782   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
5783 }
5784 
5785 ScalarEvolution::ExitLimit
5786 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
5787                                                       SwitchInst *Switch,
5788                                                       BasicBlock *ExitingBlock,
5789                                                       bool ControlsExit) {
5790   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5791 
5792   // Give up if the exit is the default dest of a switch.
5793   if (Switch->getDefaultDest() == ExitingBlock)
5794     return getCouldNotCompute();
5795 
5796   assert(L->contains(Switch->getDefaultDest()) &&
5797          "Default case must not exit the loop!");
5798   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5799   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5800 
5801   // while (X != Y) --> while (X-Y != 0)
5802   ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
5803   if (EL.hasAnyInfo())
5804     return EL;
5805 
5806   return getCouldNotCompute();
5807 }
5808 
5809 static ConstantInt *
5810 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5811                                 ScalarEvolution &SE) {
5812   const SCEV *InVal = SE.getConstant(C);
5813   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
5814   assert(isa<SCEVConstant>(Val) &&
5815          "Evaluation of SCEV at constant didn't fold correctly?");
5816   return cast<SCEVConstant>(Val)->getValue();
5817 }
5818 
5819 /// computeLoadConstantCompareExitLimit - Given an exit condition of
5820 /// 'icmp op load X, cst', try to see if we can compute the backedge
5821 /// execution count.
5822 ScalarEvolution::ExitLimit
5823 ScalarEvolution::computeLoadConstantCompareExitLimit(
5824   LoadInst *LI,
5825   Constant *RHS,
5826   const Loop *L,
5827   ICmpInst::Predicate predicate) {
5828 
5829   if (LI->isVolatile()) return getCouldNotCompute();
5830 
5831   // Check to see if the loaded pointer is a getelementptr of a global.
5832   // TODO: Use SCEV instead of manually grubbing with GEPs.
5833   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
5834   if (!GEP) return getCouldNotCompute();
5835 
5836   // Make sure that it is really a constant global we are gepping, with an
5837   // initializer, and make sure the first IDX is really 0.
5838   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
5839   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
5840       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5841       !cast<Constant>(GEP->getOperand(1))->isNullValue())
5842     return getCouldNotCompute();
5843 
5844   // Okay, we allow one non-constant index into the GEP instruction.
5845   Value *VarIdx = nullptr;
5846   std::vector<Constant*> Indexes;
5847   unsigned VarIdxNum = 0;
5848   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5849     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5850       Indexes.push_back(CI);
5851     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
5852       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
5853       VarIdx = GEP->getOperand(i);
5854       VarIdxNum = i-2;
5855       Indexes.push_back(nullptr);
5856     }
5857 
5858   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5859   if (!VarIdx)
5860     return getCouldNotCompute();
5861 
5862   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5863   // Check to see if X is a loop variant variable value now.
5864   const SCEV *Idx = getSCEV(VarIdx);
5865   Idx = getSCEVAtScope(Idx, L);
5866 
5867   // We can only recognize very limited forms of loop index expressions, in
5868   // particular, only affine AddRec's like {C1,+,C2}.
5869   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
5870   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
5871       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5872       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
5873     return getCouldNotCompute();
5874 
5875   unsigned MaxSteps = MaxBruteForceIterations;
5876   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
5877     ConstantInt *ItCst = ConstantInt::get(
5878                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
5879     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
5880 
5881     // Form the GEP offset.
5882     Indexes[VarIdxNum] = Val;
5883 
5884     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5885                                                          Indexes);
5886     if (!Result) break;  // Cannot compute!
5887 
5888     // Evaluate the condition for this iteration.
5889     Result = ConstantExpr::getICmp(predicate, Result, RHS);
5890     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
5891     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
5892       ++NumArrayLenItCounts;
5893       return getConstant(ItCst);   // Found terminating iteration!
5894     }
5895   }
5896   return getCouldNotCompute();
5897 }
5898 
5899 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
5900     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
5901   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
5902   if (!RHS)
5903     return getCouldNotCompute();
5904 
5905   const BasicBlock *Latch = L->getLoopLatch();
5906   if (!Latch)
5907     return getCouldNotCompute();
5908 
5909   const BasicBlock *Predecessor = L->getLoopPredecessor();
5910   if (!Predecessor)
5911     return getCouldNotCompute();
5912 
5913   // Return true if V is of the form "LHS `shift_op` <positive constant>".
5914   // Return LHS in OutLHS and shift_opt in OutOpCode.
5915   auto MatchPositiveShift =
5916       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
5917 
5918     using namespace PatternMatch;
5919 
5920     ConstantInt *ShiftAmt;
5921     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5922       OutOpCode = Instruction::LShr;
5923     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5924       OutOpCode = Instruction::AShr;
5925     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
5926       OutOpCode = Instruction::Shl;
5927     else
5928       return false;
5929 
5930     return ShiftAmt->getValue().isStrictlyPositive();
5931   };
5932 
5933   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
5934   //
5935   // loop:
5936   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
5937   //   %iv.shifted = lshr i32 %iv, <positive constant>
5938   //
5939   // Return true on a succesful match.  Return the corresponding PHI node (%iv
5940   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
5941   auto MatchShiftRecurrence =
5942       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
5943     Optional<Instruction::BinaryOps> PostShiftOpCode;
5944 
5945     {
5946       Instruction::BinaryOps OpC;
5947       Value *V;
5948 
5949       // If we encounter a shift instruction, "peel off" the shift operation,
5950       // and remember that we did so.  Later when we inspect %iv's backedge
5951       // value, we will make sure that the backedge value uses the same
5952       // operation.
5953       //
5954       // Note: the peeled shift operation does not have to be the same
5955       // instruction as the one feeding into the PHI's backedge value.  We only
5956       // really care about it being the same *kind* of shift instruction --
5957       // that's all that is required for our later inferences to hold.
5958       if (MatchPositiveShift(LHS, V, OpC)) {
5959         PostShiftOpCode = OpC;
5960         LHS = V;
5961       }
5962     }
5963 
5964     PNOut = dyn_cast<PHINode>(LHS);
5965     if (!PNOut || PNOut->getParent() != L->getHeader())
5966       return false;
5967 
5968     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
5969     Value *OpLHS;
5970 
5971     return
5972         // The backedge value for the PHI node must be a shift by a positive
5973         // amount
5974         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
5975 
5976         // of the PHI node itself
5977         OpLHS == PNOut &&
5978 
5979         // and the kind of shift should be match the kind of shift we peeled
5980         // off, if any.
5981         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
5982   };
5983 
5984   PHINode *PN;
5985   Instruction::BinaryOps OpCode;
5986   if (!MatchShiftRecurrence(LHS, PN, OpCode))
5987     return getCouldNotCompute();
5988 
5989   const DataLayout &DL = getDataLayout();
5990 
5991   // The key rationale for this optimization is that for some kinds of shift
5992   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
5993   // within a finite number of iterations.  If the condition guarding the
5994   // backedge (in the sense that the backedge is taken if the condition is true)
5995   // is false for the value the shift recurrence stabilizes to, then we know
5996   // that the backedge is taken only a finite number of times.
5997 
5998   ConstantInt *StableValue = nullptr;
5999   switch (OpCode) {
6000   default:
6001     llvm_unreachable("Impossible case!");
6002 
6003   case Instruction::AShr: {
6004     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6005     // bitwidth(K) iterations.
6006     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6007     bool KnownZero, KnownOne;
6008     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6009                    Predecessor->getTerminator(), &DT);
6010     auto *Ty = cast<IntegerType>(RHS->getType());
6011     if (KnownZero)
6012       StableValue = ConstantInt::get(Ty, 0);
6013     else if (KnownOne)
6014       StableValue = ConstantInt::get(Ty, -1, true);
6015     else
6016       return getCouldNotCompute();
6017 
6018     break;
6019   }
6020   case Instruction::LShr:
6021   case Instruction::Shl:
6022     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6023     // stabilize to 0 in at most bitwidth(K) iterations.
6024     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6025     break;
6026   }
6027 
6028   auto *Result =
6029       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6030   assert(Result->getType()->isIntegerTy(1) &&
6031          "Otherwise cannot be an operand to a branch instruction");
6032 
6033   if (Result->isZeroValue()) {
6034     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6035     const SCEV *UpperBound =
6036         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6037     return ExitLimit(getCouldNotCompute(), UpperBound);
6038   }
6039 
6040   return getCouldNotCompute();
6041 }
6042 
6043 /// CanConstantFold - Return true if we can constant fold an instruction of the
6044 /// specified type, assuming that all operands were constants.
6045 static bool CanConstantFold(const Instruction *I) {
6046   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6047       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6048       isa<LoadInst>(I))
6049     return true;
6050 
6051   if (const CallInst *CI = dyn_cast<CallInst>(I))
6052     if (const Function *F = CI->getCalledFunction())
6053       return canConstantFoldCallTo(F);
6054   return false;
6055 }
6056 
6057 /// Determine whether this instruction can constant evolve within this loop
6058 /// assuming its operands can all constant evolve.
6059 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6060   // An instruction outside of the loop can't be derived from a loop PHI.
6061   if (!L->contains(I)) return false;
6062 
6063   if (isa<PHINode>(I)) {
6064     // We don't currently keep track of the control flow needed to evaluate
6065     // PHIs, so we cannot handle PHIs inside of loops.
6066     return L->getHeader() == I->getParent();
6067   }
6068 
6069   // If we won't be able to constant fold this expression even if the operands
6070   // are constants, bail early.
6071   return CanConstantFold(I);
6072 }
6073 
6074 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6075 /// recursing through each instruction operand until reaching a loop header phi.
6076 static PHINode *
6077 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6078                                DenseMap<Instruction *, PHINode *> &PHIMap) {
6079 
6080   // Otherwise, we can evaluate this instruction if all of its operands are
6081   // constant or derived from a PHI node themselves.
6082   PHINode *PHI = nullptr;
6083   for (Value *Op : UseInst->operands()) {
6084     if (isa<Constant>(Op)) continue;
6085 
6086     Instruction *OpInst = dyn_cast<Instruction>(Op);
6087     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6088 
6089     PHINode *P = dyn_cast<PHINode>(OpInst);
6090     if (!P)
6091       // If this operand is already visited, reuse the prior result.
6092       // We may have P != PHI if this is the deepest point at which the
6093       // inconsistent paths meet.
6094       P = PHIMap.lookup(OpInst);
6095     if (!P) {
6096       // Recurse and memoize the results, whether a phi is found or not.
6097       // This recursive call invalidates pointers into PHIMap.
6098       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6099       PHIMap[OpInst] = P;
6100     }
6101     if (!P)
6102       return nullptr;  // Not evolving from PHI
6103     if (PHI && PHI != P)
6104       return nullptr;  // Evolving from multiple different PHIs.
6105     PHI = P;
6106   }
6107   // This is a expression evolving from a constant PHI!
6108   return PHI;
6109 }
6110 
6111 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6112 /// in the loop that V is derived from.  We allow arbitrary operations along the
6113 /// way, but the operands of an operation must either be constants or a value
6114 /// derived from a constant PHI.  If this expression does not fit with these
6115 /// constraints, return null.
6116 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6117   Instruction *I = dyn_cast<Instruction>(V);
6118   if (!I || !canConstantEvolve(I, L)) return nullptr;
6119 
6120   if (PHINode *PN = dyn_cast<PHINode>(I))
6121     return PN;
6122 
6123   // Record non-constant instructions contained by the loop.
6124   DenseMap<Instruction *, PHINode *> PHIMap;
6125   return getConstantEvolvingPHIOperands(I, L, PHIMap);
6126 }
6127 
6128 /// EvaluateExpression - Given an expression that passes the
6129 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6130 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6131 /// reason, return null.
6132 static Constant *EvaluateExpression(Value *V, const Loop *L,
6133                                     DenseMap<Instruction *, Constant *> &Vals,
6134                                     const DataLayout &DL,
6135                                     const TargetLibraryInfo *TLI) {
6136   // Convenient constant check, but redundant for recursive calls.
6137   if (Constant *C = dyn_cast<Constant>(V)) return C;
6138   Instruction *I = dyn_cast<Instruction>(V);
6139   if (!I) return nullptr;
6140 
6141   if (Constant *C = Vals.lookup(I)) return C;
6142 
6143   // An instruction inside the loop depends on a value outside the loop that we
6144   // weren't given a mapping for, or a value such as a call inside the loop.
6145   if (!canConstantEvolve(I, L)) return nullptr;
6146 
6147   // An unmapped PHI can be due to a branch or another loop inside this loop,
6148   // or due to this not being the initial iteration through a loop where we
6149   // couldn't compute the evolution of this particular PHI last time.
6150   if (isa<PHINode>(I)) return nullptr;
6151 
6152   std::vector<Constant*> Operands(I->getNumOperands());
6153 
6154   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6155     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6156     if (!Operand) {
6157       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6158       if (!Operands[i]) return nullptr;
6159       continue;
6160     }
6161     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6162     Vals[Operand] = C;
6163     if (!C) return nullptr;
6164     Operands[i] = C;
6165   }
6166 
6167   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6168     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6169                                            Operands[1], DL, TLI);
6170   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6171     if (!LI->isVolatile())
6172       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6173   }
6174   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6175 }
6176 
6177 
6178 // If every incoming value to PN except the one for BB is a specific Constant,
6179 // return that, else return nullptr.
6180 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6181   Constant *IncomingVal = nullptr;
6182 
6183   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6184     if (PN->getIncomingBlock(i) == BB)
6185       continue;
6186 
6187     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6188     if (!CurrentVal)
6189       return nullptr;
6190 
6191     if (IncomingVal != CurrentVal) {
6192       if (IncomingVal)
6193         return nullptr;
6194       IncomingVal = CurrentVal;
6195     }
6196   }
6197 
6198   return IncomingVal;
6199 }
6200 
6201 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6202 /// in the header of its containing loop, we know the loop executes a
6203 /// constant number of times, and the PHI node is just a recurrence
6204 /// involving constants, fold it.
6205 Constant *
6206 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6207                                                    const APInt &BEs,
6208                                                    const Loop *L) {
6209   auto I = ConstantEvolutionLoopExitValue.find(PN);
6210   if (I != ConstantEvolutionLoopExitValue.end())
6211     return I->second;
6212 
6213   if (BEs.ugt(MaxBruteForceIterations))
6214     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6215 
6216   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6217 
6218   DenseMap<Instruction *, Constant *> CurrentIterVals;
6219   BasicBlock *Header = L->getHeader();
6220   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6221 
6222   BasicBlock *Latch = L->getLoopLatch();
6223   if (!Latch)
6224     return nullptr;
6225 
6226   for (auto &I : *Header) {
6227     PHINode *PHI = dyn_cast<PHINode>(&I);
6228     if (!PHI) break;
6229     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6230     if (!StartCST) continue;
6231     CurrentIterVals[PHI] = StartCST;
6232   }
6233   if (!CurrentIterVals.count(PN))
6234     return RetVal = nullptr;
6235 
6236   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6237 
6238   // Execute the loop symbolically to determine the exit value.
6239   if (BEs.getActiveBits() >= 32)
6240     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6241 
6242   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6243   unsigned IterationNum = 0;
6244   const DataLayout &DL = getDataLayout();
6245   for (; ; ++IterationNum) {
6246     if (IterationNum == NumIterations)
6247       return RetVal = CurrentIterVals[PN];  // Got exit value!
6248 
6249     // Compute the value of the PHIs for the next iteration.
6250     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6251     DenseMap<Instruction *, Constant *> NextIterVals;
6252     Constant *NextPHI =
6253         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6254     if (!NextPHI)
6255       return nullptr;        // Couldn't evaluate!
6256     NextIterVals[PN] = NextPHI;
6257 
6258     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6259 
6260     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6261     // cease to be able to evaluate one of them or if they stop evolving,
6262     // because that doesn't necessarily prevent us from computing PN.
6263     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6264     for (const auto &I : CurrentIterVals) {
6265       PHINode *PHI = dyn_cast<PHINode>(I.first);
6266       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6267       PHIsToCompute.emplace_back(PHI, I.second);
6268     }
6269     // We use two distinct loops because EvaluateExpression may invalidate any
6270     // iterators into CurrentIterVals.
6271     for (const auto &I : PHIsToCompute) {
6272       PHINode *PHI = I.first;
6273       Constant *&NextPHI = NextIterVals[PHI];
6274       if (!NextPHI) {   // Not already computed.
6275         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6276         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6277       }
6278       if (NextPHI != I.second)
6279         StoppedEvolving = false;
6280     }
6281 
6282     // If all entries in CurrentIterVals == NextIterVals then we can stop
6283     // iterating, the loop can't continue to change.
6284     if (StoppedEvolving)
6285       return RetVal = CurrentIterVals[PN];
6286 
6287     CurrentIterVals.swap(NextIterVals);
6288   }
6289 }
6290 
6291 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6292                                                           Value *Cond,
6293                                                           bool ExitWhen) {
6294   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6295   if (!PN) return getCouldNotCompute();
6296 
6297   // If the loop is canonicalized, the PHI will have exactly two entries.
6298   // That's the only form we support here.
6299   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6300 
6301   DenseMap<Instruction *, Constant *> CurrentIterVals;
6302   BasicBlock *Header = L->getHeader();
6303   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6304 
6305   BasicBlock *Latch = L->getLoopLatch();
6306   assert(Latch && "Should follow from NumIncomingValues == 2!");
6307 
6308   for (auto &I : *Header) {
6309     PHINode *PHI = dyn_cast<PHINode>(&I);
6310     if (!PHI)
6311       break;
6312     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6313     if (!StartCST) continue;
6314     CurrentIterVals[PHI] = StartCST;
6315   }
6316   if (!CurrentIterVals.count(PN))
6317     return getCouldNotCompute();
6318 
6319   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6320   // the loop symbolically to determine when the condition gets a value of
6321   // "ExitWhen".
6322   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6323   const DataLayout &DL = getDataLayout();
6324   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6325     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6326         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6327 
6328     // Couldn't symbolically evaluate.
6329     if (!CondVal) return getCouldNotCompute();
6330 
6331     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6332       ++NumBruteForceTripCountsComputed;
6333       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6334     }
6335 
6336     // Update all the PHI nodes for the next iteration.
6337     DenseMap<Instruction *, Constant *> NextIterVals;
6338 
6339     // Create a list of which PHIs we need to compute. We want to do this before
6340     // calling EvaluateExpression on them because that may invalidate iterators
6341     // into CurrentIterVals.
6342     SmallVector<PHINode *, 8> PHIsToCompute;
6343     for (const auto &I : CurrentIterVals) {
6344       PHINode *PHI = dyn_cast<PHINode>(I.first);
6345       if (!PHI || PHI->getParent() != Header) continue;
6346       PHIsToCompute.push_back(PHI);
6347     }
6348     for (PHINode *PHI : PHIsToCompute) {
6349       Constant *&NextPHI = NextIterVals[PHI];
6350       if (NextPHI) continue;    // Already computed!
6351 
6352       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6353       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6354     }
6355     CurrentIterVals.swap(NextIterVals);
6356   }
6357 
6358   // Too many iterations were needed to evaluate.
6359   return getCouldNotCompute();
6360 }
6361 
6362 /// getSCEVAtScope - Return a SCEV expression for the specified value
6363 /// at the specified scope in the program.  The L value specifies a loop
6364 /// nest to evaluate the expression at, where null is the top-level or a
6365 /// specified loop is immediately inside of the loop.
6366 ///
6367 /// This method can be used to compute the exit value for a variable defined
6368 /// in a loop by querying what the value will hold in the parent loop.
6369 ///
6370 /// In the case that a relevant loop exit value cannot be computed, the
6371 /// original value V is returned.
6372 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6373   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6374       ValuesAtScopes[V];
6375   // Check to see if we've folded this expression at this loop before.
6376   for (auto &LS : Values)
6377     if (LS.first == L)
6378       return LS.second ? LS.second : V;
6379 
6380   Values.emplace_back(L, nullptr);
6381 
6382   // Otherwise compute it.
6383   const SCEV *C = computeSCEVAtScope(V, L);
6384   for (auto &LS : reverse(ValuesAtScopes[V]))
6385     if (LS.first == L) {
6386       LS.second = C;
6387       break;
6388     }
6389   return C;
6390 }
6391 
6392 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6393 /// will return Constants for objects which aren't represented by a
6394 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6395 /// Returns NULL if the SCEV isn't representable as a Constant.
6396 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6397   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6398     case scCouldNotCompute:
6399     case scAddRecExpr:
6400       break;
6401     case scConstant:
6402       return cast<SCEVConstant>(V)->getValue();
6403     case scUnknown:
6404       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6405     case scSignExtend: {
6406       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6407       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6408         return ConstantExpr::getSExt(CastOp, SS->getType());
6409       break;
6410     }
6411     case scZeroExtend: {
6412       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6413       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6414         return ConstantExpr::getZExt(CastOp, SZ->getType());
6415       break;
6416     }
6417     case scTruncate: {
6418       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6419       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6420         return ConstantExpr::getTrunc(CastOp, ST->getType());
6421       break;
6422     }
6423     case scAddExpr: {
6424       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6425       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6426         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6427           unsigned AS = PTy->getAddressSpace();
6428           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6429           C = ConstantExpr::getBitCast(C, DestPtrTy);
6430         }
6431         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6432           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6433           if (!C2) return nullptr;
6434 
6435           // First pointer!
6436           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6437             unsigned AS = C2->getType()->getPointerAddressSpace();
6438             std::swap(C, C2);
6439             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6440             // The offsets have been converted to bytes.  We can add bytes to an
6441             // i8* by GEP with the byte count in the first index.
6442             C = ConstantExpr::getBitCast(C, DestPtrTy);
6443           }
6444 
6445           // Don't bother trying to sum two pointers. We probably can't
6446           // statically compute a load that results from it anyway.
6447           if (C2->getType()->isPointerTy())
6448             return nullptr;
6449 
6450           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6451             if (PTy->getElementType()->isStructTy())
6452               C2 = ConstantExpr::getIntegerCast(
6453                   C2, Type::getInt32Ty(C->getContext()), true);
6454             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6455           } else
6456             C = ConstantExpr::getAdd(C, C2);
6457         }
6458         return C;
6459       }
6460       break;
6461     }
6462     case scMulExpr: {
6463       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6464       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6465         // Don't bother with pointers at all.
6466         if (C->getType()->isPointerTy()) return nullptr;
6467         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6468           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6469           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6470           C = ConstantExpr::getMul(C, C2);
6471         }
6472         return C;
6473       }
6474       break;
6475     }
6476     case scUDivExpr: {
6477       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6478       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6479         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6480           if (LHS->getType() == RHS->getType())
6481             return ConstantExpr::getUDiv(LHS, RHS);
6482       break;
6483     }
6484     case scSMaxExpr:
6485     case scUMaxExpr:
6486       break; // TODO: smax, umax.
6487   }
6488   return nullptr;
6489 }
6490 
6491 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6492   if (isa<SCEVConstant>(V)) return V;
6493 
6494   // If this instruction is evolved from a constant-evolving PHI, compute the
6495   // exit value from the loop without using SCEVs.
6496   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6497     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6498       const Loop *LI = this->LI[I->getParent()];
6499       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6500         if (PHINode *PN = dyn_cast<PHINode>(I))
6501           if (PN->getParent() == LI->getHeader()) {
6502             // Okay, there is no closed form solution for the PHI node.  Check
6503             // to see if the loop that contains it has a known backedge-taken
6504             // count.  If so, we may be able to force computation of the exit
6505             // value.
6506             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6507             if (const SCEVConstant *BTCC =
6508                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6509               // Okay, we know how many times the containing loop executes.  If
6510               // this is a constant evolving PHI node, get the final value at
6511               // the specified iteration number.
6512               Constant *RV =
6513                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
6514               if (RV) return getSCEV(RV);
6515             }
6516           }
6517 
6518       // Okay, this is an expression that we cannot symbolically evaluate
6519       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6520       // the arguments into constants, and if so, try to constant propagate the
6521       // result.  This is particularly useful for computing loop exit values.
6522       if (CanConstantFold(I)) {
6523         SmallVector<Constant *, 4> Operands;
6524         bool MadeImprovement = false;
6525         for (Value *Op : I->operands()) {
6526           if (Constant *C = dyn_cast<Constant>(Op)) {
6527             Operands.push_back(C);
6528             continue;
6529           }
6530 
6531           // If any of the operands is non-constant and if they are
6532           // non-integer and non-pointer, don't even try to analyze them
6533           // with scev techniques.
6534           if (!isSCEVable(Op->getType()))
6535             return V;
6536 
6537           const SCEV *OrigV = getSCEV(Op);
6538           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6539           MadeImprovement |= OrigV != OpV;
6540 
6541           Constant *C = BuildConstantFromSCEV(OpV);
6542           if (!C) return V;
6543           if (C->getType() != Op->getType())
6544             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6545                                                               Op->getType(),
6546                                                               false),
6547                                       C, Op->getType());
6548           Operands.push_back(C);
6549         }
6550 
6551         // Check to see if getSCEVAtScope actually made an improvement.
6552         if (MadeImprovement) {
6553           Constant *C = nullptr;
6554           const DataLayout &DL = getDataLayout();
6555           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
6556             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6557                                                 Operands[1], DL, &TLI);
6558           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6559             if (!LI->isVolatile())
6560               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6561           } else
6562             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
6563           if (!C) return V;
6564           return getSCEV(C);
6565         }
6566       }
6567     }
6568 
6569     // This is some other type of SCEVUnknown, just return it.
6570     return V;
6571   }
6572 
6573   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
6574     // Avoid performing the look-up in the common case where the specified
6575     // expression has no loop-variant portions.
6576     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
6577       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6578       if (OpAtScope != Comm->getOperand(i)) {
6579         // Okay, at least one of these operands is loop variant but might be
6580         // foldable.  Build a new instance of the folded commutative expression.
6581         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6582                                             Comm->op_begin()+i);
6583         NewOps.push_back(OpAtScope);
6584 
6585         for (++i; i != e; ++i) {
6586           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6587           NewOps.push_back(OpAtScope);
6588         }
6589         if (isa<SCEVAddExpr>(Comm))
6590           return getAddExpr(NewOps);
6591         if (isa<SCEVMulExpr>(Comm))
6592           return getMulExpr(NewOps);
6593         if (isa<SCEVSMaxExpr>(Comm))
6594           return getSMaxExpr(NewOps);
6595         if (isa<SCEVUMaxExpr>(Comm))
6596           return getUMaxExpr(NewOps);
6597         llvm_unreachable("Unknown commutative SCEV type!");
6598       }
6599     }
6600     // If we got here, all operands are loop invariant.
6601     return Comm;
6602   }
6603 
6604   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
6605     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6606     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
6607     if (LHS == Div->getLHS() && RHS == Div->getRHS())
6608       return Div;   // must be loop invariant
6609     return getUDivExpr(LHS, RHS);
6610   }
6611 
6612   // If this is a loop recurrence for a loop that does not contain L, then we
6613   // are dealing with the final value computed by the loop.
6614   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
6615     // First, attempt to evaluate each operand.
6616     // Avoid performing the look-up in the common case where the specified
6617     // expression has no loop-variant portions.
6618     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6619       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6620       if (OpAtScope == AddRec->getOperand(i))
6621         continue;
6622 
6623       // Okay, at least one of these operands is loop variant but might be
6624       // foldable.  Build a new instance of the folded commutative expression.
6625       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6626                                           AddRec->op_begin()+i);
6627       NewOps.push_back(OpAtScope);
6628       for (++i; i != e; ++i)
6629         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6630 
6631       const SCEV *FoldedRec =
6632         getAddRecExpr(NewOps, AddRec->getLoop(),
6633                       AddRec->getNoWrapFlags(SCEV::FlagNW));
6634       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
6635       // The addrec may be folded to a nonrecurrence, for example, if the
6636       // induction variable is multiplied by zero after constant folding. Go
6637       // ahead and return the folded value.
6638       if (!AddRec)
6639         return FoldedRec;
6640       break;
6641     }
6642 
6643     // If the scope is outside the addrec's loop, evaluate it by using the
6644     // loop exit value of the addrec.
6645     if (!AddRec->getLoop()->contains(L)) {
6646       // To evaluate this recurrence, we need to know how many times the AddRec
6647       // loop iterates.  Compute this now.
6648       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
6649       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
6650 
6651       // Then, evaluate the AddRec.
6652       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
6653     }
6654 
6655     return AddRec;
6656   }
6657 
6658   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
6659     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6660     if (Op == Cast->getOperand())
6661       return Cast;  // must be loop invariant
6662     return getZeroExtendExpr(Op, Cast->getType());
6663   }
6664 
6665   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
6666     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6667     if (Op == Cast->getOperand())
6668       return Cast;  // must be loop invariant
6669     return getSignExtendExpr(Op, Cast->getType());
6670   }
6671 
6672   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
6673     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
6674     if (Op == Cast->getOperand())
6675       return Cast;  // must be loop invariant
6676     return getTruncateExpr(Op, Cast->getType());
6677   }
6678 
6679   llvm_unreachable("Unknown SCEV type!");
6680 }
6681 
6682 /// getSCEVAtScope - This is a convenience function which does
6683 /// getSCEVAtScope(getSCEV(V), L).
6684 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
6685   return getSCEVAtScope(getSCEV(V), L);
6686 }
6687 
6688 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
6689 /// following equation:
6690 ///
6691 ///     A * X = B (mod N)
6692 ///
6693 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6694 /// A and B isn't important.
6695 ///
6696 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
6697 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
6698                                                ScalarEvolution &SE) {
6699   uint32_t BW = A.getBitWidth();
6700   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6701   assert(A != 0 && "A must be non-zero.");
6702 
6703   // 1. D = gcd(A, N)
6704   //
6705   // The gcd of A and N may have only one prime factor: 2. The number of
6706   // trailing zeros in A is its multiplicity
6707   uint32_t Mult2 = A.countTrailingZeros();
6708   // D = 2^Mult2
6709 
6710   // 2. Check if B is divisible by D.
6711   //
6712   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6713   // is not less than multiplicity of this prime factor for D.
6714   if (B.countTrailingZeros() < Mult2)
6715     return SE.getCouldNotCompute();
6716 
6717   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6718   // modulo (N / D).
6719   //
6720   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
6721   // bit width during computations.
6722   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
6723   APInt Mod(BW + 1, 0);
6724   Mod.setBit(BW - Mult2);  // Mod = N / D
6725   APInt I = AD.multiplicativeInverse(Mod);
6726 
6727   // 4. Compute the minimum unsigned root of the equation:
6728   // I * (B / D) mod (N / D)
6729   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6730 
6731   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6732   // bits.
6733   return SE.getConstant(Result.trunc(BW));
6734 }
6735 
6736 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6737 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
6738 /// might be the same) or two SCEVCouldNotCompute objects.
6739 ///
6740 static std::pair<const SCEV *,const SCEV *>
6741 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
6742   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
6743   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6744   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6745   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
6746 
6747   // We currently can only solve this if the coefficients are constants.
6748   if (!LC || !MC || !NC) {
6749     const SCEV *CNC = SE.getCouldNotCompute();
6750     return {CNC, CNC};
6751   }
6752 
6753   uint32_t BitWidth = LC->getAPInt().getBitWidth();
6754   const APInt &L = LC->getAPInt();
6755   const APInt &M = MC->getAPInt();
6756   const APInt &N = NC->getAPInt();
6757   APInt Two(BitWidth, 2);
6758   APInt Four(BitWidth, 4);
6759 
6760   {
6761     using namespace APIntOps;
6762     const APInt& C = L;
6763     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6764     // The B coefficient is M-N/2
6765     APInt B(M);
6766     B -= sdiv(N,Two);
6767 
6768     // The A coefficient is N/2
6769     APInt A(N.sdiv(Two));
6770 
6771     // Compute the B^2-4ac term.
6772     APInt SqrtTerm(B);
6773     SqrtTerm *= B;
6774     SqrtTerm -= Four * (A * C);
6775 
6776     if (SqrtTerm.isNegative()) {
6777       // The loop is provably infinite.
6778       const SCEV *CNC = SE.getCouldNotCompute();
6779       return {CNC, CNC};
6780     }
6781 
6782     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6783     // integer value or else APInt::sqrt() will assert.
6784     APInt SqrtVal(SqrtTerm.sqrt());
6785 
6786     // Compute the two solutions for the quadratic formula.
6787     // The divisions must be performed as signed divisions.
6788     APInt NegB(-B);
6789     APInt TwoA(A << 1);
6790     if (TwoA.isMinValue()) {
6791       const SCEV *CNC = SE.getCouldNotCompute();
6792       return {CNC, CNC};
6793     }
6794 
6795     LLVMContext &Context = SE.getContext();
6796 
6797     ConstantInt *Solution1 =
6798       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
6799     ConstantInt *Solution2 =
6800       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
6801 
6802     return {SE.getConstant(Solution1), SE.getConstant(Solution2)};
6803   } // end APIntOps namespace
6804 }
6805 
6806 /// HowFarToZero - Return the number of times a backedge comparing the specified
6807 /// value to zero will execute.  If not computable, return CouldNotCompute.
6808 ///
6809 /// This is only used for loops with a "x != y" exit test. The exit condition is
6810 /// now expressed as a single expression, V = x-y. So the exit test is
6811 /// effectively V != 0.  We know and take advantage of the fact that this
6812 /// expression only being used in a comparison by zero context.
6813 ScalarEvolution::ExitLimit
6814 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
6815   // If the value is a constant
6816   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6817     // If the value is already zero, the branch will execute zero times.
6818     if (C->getValue()->isZero()) return C;
6819     return getCouldNotCompute();  // Otherwise it will loop infinitely.
6820   }
6821 
6822   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
6823   if (!AddRec || AddRec->getLoop() != L)
6824     return getCouldNotCompute();
6825 
6826   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
6827   // the quadratic equation to solve it.
6828   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
6829     std::pair<const SCEV *,const SCEV *> Roots =
6830       SolveQuadraticEquation(AddRec, *this);
6831     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6832     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6833     if (R1 && R2) {
6834       // Pick the smallest positive root value.
6835       if (ConstantInt *CB =
6836           dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
6837                                                       R1->getValue(),
6838                                                       R2->getValue()))) {
6839         if (!CB->getZExtValue())
6840           std::swap(R1, R2);   // R1 is the minimum root now.
6841 
6842         // We can only use this value if the chrec ends up with an exact zero
6843         // value at this index.  When solving for "X*X != 5", for example, we
6844         // should not accept a root of 2.
6845         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
6846         if (Val->isZero())
6847           return R1;  // We found a quadratic root!
6848       }
6849     }
6850     return getCouldNotCompute();
6851   }
6852 
6853   // Otherwise we can only handle this if it is affine.
6854   if (!AddRec->isAffine())
6855     return getCouldNotCompute();
6856 
6857   // If this is an affine expression, the execution count of this branch is
6858   // the minimum unsigned root of the following equation:
6859   //
6860   //     Start + Step*N = 0 (mod 2^BW)
6861   //
6862   // equivalent to:
6863   //
6864   //             Step*N = -Start (mod 2^BW)
6865   //
6866   // where BW is the common bit width of Start and Step.
6867 
6868   // Get the initial value for the loop.
6869   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6870   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6871 
6872   // For now we handle only constant steps.
6873   //
6874   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6875   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6876   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6877   // We have not yet seen any such cases.
6878   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
6879   if (!StepC || StepC->getValue()->equalsInt(0))
6880     return getCouldNotCompute();
6881 
6882   // For positive steps (counting up until unsigned overflow):
6883   //   N = -Start/Step (as unsigned)
6884   // For negative steps (counting down to zero):
6885   //   N = Start/-Step
6886   // First compute the unsigned distance from zero in the direction of Step.
6887   bool CountDown = StepC->getAPInt().isNegative();
6888   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
6889 
6890   // Handle unitary steps, which cannot wraparound.
6891   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6892   //   N = Distance (as unsigned)
6893   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6894     ConstantRange CR = getUnsignedRange(Start);
6895     const SCEV *MaxBECount;
6896     if (!CountDown && CR.getUnsignedMin().isMinValue())
6897       // When counting up, the worst starting value is 1, not 0.
6898       MaxBECount = CR.getUnsignedMax().isMinValue()
6899         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6900         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6901     else
6902       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6903                                          : -CR.getUnsignedMin());
6904     return ExitLimit(Distance, MaxBECount);
6905   }
6906 
6907   // As a special case, handle the instance where Step is a positive power of
6908   // two. In this case, determining whether Step divides Distance evenly can be
6909   // done by counting and comparing the number of trailing zeros of Step and
6910   // Distance.
6911   if (!CountDown) {
6912     const APInt &StepV = StepC->getAPInt();
6913     // StepV.isPowerOf2() returns true if StepV is an positive power of two.  It
6914     // also returns true if StepV is maximally negative (eg, INT_MIN), but that
6915     // case is not handled as this code is guarded by !CountDown.
6916     if (StepV.isPowerOf2() &&
6917         GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
6918       // Here we've constrained the equation to be of the form
6919       //
6920       //   2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W)  ... (0)
6921       //
6922       // where we're operating on a W bit wide integer domain and k is
6923       // non-negative.  The smallest unsigned solution for X is the trip count.
6924       //
6925       // (0) is equivalent to:
6926       //
6927       //      2^(N + k) * Distance' - 2^N * X = L * 2^W
6928       // <=>  2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
6929       // <=>  2^k * Distance' - X = L * 2^(W - N)
6930       // <=>  2^k * Distance'     = L * 2^(W - N) + X    ... (1)
6931       //
6932       // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
6933       // by 2^(W - N).
6934       //
6935       // <=>  X = 2^k * Distance' URem 2^(W - N)   ... (2)
6936       //
6937       // E.g. say we're solving
6938       //
6939       //   2 * Val = 2 * X  (in i8)   ... (3)
6940       //
6941       // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
6942       //
6943       // Note: It is tempting to solve (3) by setting X = Val, but Val is not
6944       // necessarily the smallest unsigned value of X that satisfies (3).
6945       // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
6946       // is i8 1, not i8 -127
6947 
6948       const auto *ModuloResult = getUDivExactExpr(Distance, Step);
6949 
6950       // Since SCEV does not have a URem node, we construct one using a truncate
6951       // and a zero extend.
6952 
6953       unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
6954       auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
6955       auto *WideTy = Distance->getType();
6956 
6957       return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
6958     }
6959   }
6960 
6961   // If the condition controls loop exit (the loop exits only if the expression
6962   // is true) and the addition is no-wrap we can use unsigned divide to
6963   // compute the backedge count.  In this case, the step may not divide the
6964   // distance, but we don't care because if the condition is "missed" the loop
6965   // will have undefined behavior due to wrapping.
6966   if (ControlsExit && AddRec->hasNoSelfWrap()) {
6967     const SCEV *Exact =
6968         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6969     return ExitLimit(Exact, Exact);
6970   }
6971 
6972   // Then, try to solve the above equation provided that Start is constant.
6973   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6974     return SolveLinEquationWithOverflow(StepC->getAPInt(), -StartC->getAPInt(),
6975                                         *this);
6976   return getCouldNotCompute();
6977 }
6978 
6979 /// HowFarToNonZero - Return the number of times a backedge checking the
6980 /// specified value for nonzero will execute.  If not computable, return
6981 /// CouldNotCompute
6982 ScalarEvolution::ExitLimit
6983 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
6984   // Loops that look like: while (X == 0) are very strange indeed.  We don't
6985   // handle them yet except for the trivial case.  This could be expanded in the
6986   // future as needed.
6987 
6988   // If the value is a constant, check to see if it is known to be non-zero
6989   // already.  If so, the backedge will execute zero times.
6990   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
6991     if (!C->getValue()->isNullValue())
6992       return getZero(C->getType());
6993     return getCouldNotCompute();  // Otherwise it will loop infinitely.
6994   }
6995 
6996   // We could implement others, but I really doubt anyone writes loops like
6997   // this, and if they did, they would already be constant folded.
6998   return getCouldNotCompute();
6999 }
7000 
7001 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
7002 /// (which may not be an immediate predecessor) which has exactly one
7003 /// successor from which BB is reachable, or null if no such block is
7004 /// found.
7005 ///
7006 std::pair<BasicBlock *, BasicBlock *>
7007 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7008   // If the block has a unique predecessor, then there is no path from the
7009   // predecessor to the block that does not go through the direct edge
7010   // from the predecessor to the block.
7011   if (BasicBlock *Pred = BB->getSinglePredecessor())
7012     return {Pred, BB};
7013 
7014   // A loop's header is defined to be a block that dominates the loop.
7015   // If the header has a unique predecessor outside the loop, it must be
7016   // a block that has exactly one successor that can reach the loop.
7017   if (Loop *L = LI.getLoopFor(BB))
7018     return {L->getLoopPredecessor(), L->getHeader()};
7019 
7020   return {nullptr, nullptr};
7021 }
7022 
7023 /// HasSameValue - SCEV structural equivalence is usually sufficient for
7024 /// testing whether two expressions are equal, however for the purposes of
7025 /// looking for a condition guarding a loop, it can be useful to be a little
7026 /// more general, since a front-end may have replicated the controlling
7027 /// expression.
7028 ///
7029 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7030   // Quick check to see if they are the same SCEV.
7031   if (A == B) return true;
7032 
7033   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7034     // Not all instructions that are "identical" compute the same value.  For
7035     // instance, two distinct alloca instructions allocating the same type are
7036     // identical and do not read memory; but compute distinct values.
7037     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7038   };
7039 
7040   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7041   // two different instructions with the same value. Check for this case.
7042   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7043     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7044       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7045         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7046           if (ComputesEqualValues(AI, BI))
7047             return true;
7048 
7049   // Otherwise assume they may have a different value.
7050   return false;
7051 }
7052 
7053 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
7054 /// predicate Pred. Return true iff any changes were made.
7055 ///
7056 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7057                                            const SCEV *&LHS, const SCEV *&RHS,
7058                                            unsigned Depth) {
7059   bool Changed = false;
7060 
7061   // If we hit the max recursion limit bail out.
7062   if (Depth >= 3)
7063     return false;
7064 
7065   // Canonicalize a constant to the right side.
7066   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7067     // Check for both operands constant.
7068     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7069       if (ConstantExpr::getICmp(Pred,
7070                                 LHSC->getValue(),
7071                                 RHSC->getValue())->isNullValue())
7072         goto trivially_false;
7073       else
7074         goto trivially_true;
7075     }
7076     // Otherwise swap the operands to put the constant on the right.
7077     std::swap(LHS, RHS);
7078     Pred = ICmpInst::getSwappedPredicate(Pred);
7079     Changed = true;
7080   }
7081 
7082   // If we're comparing an addrec with a value which is loop-invariant in the
7083   // addrec's loop, put the addrec on the left. Also make a dominance check,
7084   // as both operands could be addrecs loop-invariant in each other's loop.
7085   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7086     const Loop *L = AR->getLoop();
7087     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7088       std::swap(LHS, RHS);
7089       Pred = ICmpInst::getSwappedPredicate(Pred);
7090       Changed = true;
7091     }
7092   }
7093 
7094   // If there's a constant operand, canonicalize comparisons with boundary
7095   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7096   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7097     const APInt &RA = RC->getAPInt();
7098     switch (Pred) {
7099     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7100     case ICmpInst::ICMP_EQ:
7101     case ICmpInst::ICMP_NE:
7102       // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7103       if (!RA)
7104         if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7105           if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7106             if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7107                 ME->getOperand(0)->isAllOnesValue()) {
7108               RHS = AE->getOperand(1);
7109               LHS = ME->getOperand(1);
7110               Changed = true;
7111             }
7112       break;
7113     case ICmpInst::ICMP_UGE:
7114       if ((RA - 1).isMinValue()) {
7115         Pred = ICmpInst::ICMP_NE;
7116         RHS = getConstant(RA - 1);
7117         Changed = true;
7118         break;
7119       }
7120       if (RA.isMaxValue()) {
7121         Pred = ICmpInst::ICMP_EQ;
7122         Changed = true;
7123         break;
7124       }
7125       if (RA.isMinValue()) goto trivially_true;
7126 
7127       Pred = ICmpInst::ICMP_UGT;
7128       RHS = getConstant(RA - 1);
7129       Changed = true;
7130       break;
7131     case ICmpInst::ICMP_ULE:
7132       if ((RA + 1).isMaxValue()) {
7133         Pred = ICmpInst::ICMP_NE;
7134         RHS = getConstant(RA + 1);
7135         Changed = true;
7136         break;
7137       }
7138       if (RA.isMinValue()) {
7139         Pred = ICmpInst::ICMP_EQ;
7140         Changed = true;
7141         break;
7142       }
7143       if (RA.isMaxValue()) goto trivially_true;
7144 
7145       Pred = ICmpInst::ICMP_ULT;
7146       RHS = getConstant(RA + 1);
7147       Changed = true;
7148       break;
7149     case ICmpInst::ICMP_SGE:
7150       if ((RA - 1).isMinSignedValue()) {
7151         Pred = ICmpInst::ICMP_NE;
7152         RHS = getConstant(RA - 1);
7153         Changed = true;
7154         break;
7155       }
7156       if (RA.isMaxSignedValue()) {
7157         Pred = ICmpInst::ICMP_EQ;
7158         Changed = true;
7159         break;
7160       }
7161       if (RA.isMinSignedValue()) goto trivially_true;
7162 
7163       Pred = ICmpInst::ICMP_SGT;
7164       RHS = getConstant(RA - 1);
7165       Changed = true;
7166       break;
7167     case ICmpInst::ICMP_SLE:
7168       if ((RA + 1).isMaxSignedValue()) {
7169         Pred = ICmpInst::ICMP_NE;
7170         RHS = getConstant(RA + 1);
7171         Changed = true;
7172         break;
7173       }
7174       if (RA.isMinSignedValue()) {
7175         Pred = ICmpInst::ICMP_EQ;
7176         Changed = true;
7177         break;
7178       }
7179       if (RA.isMaxSignedValue()) goto trivially_true;
7180 
7181       Pred = ICmpInst::ICMP_SLT;
7182       RHS = getConstant(RA + 1);
7183       Changed = true;
7184       break;
7185     case ICmpInst::ICMP_UGT:
7186       if (RA.isMinValue()) {
7187         Pred = ICmpInst::ICMP_NE;
7188         Changed = true;
7189         break;
7190       }
7191       if ((RA + 1).isMaxValue()) {
7192         Pred = ICmpInst::ICMP_EQ;
7193         RHS = getConstant(RA + 1);
7194         Changed = true;
7195         break;
7196       }
7197       if (RA.isMaxValue()) goto trivially_false;
7198       break;
7199     case ICmpInst::ICMP_ULT:
7200       if (RA.isMaxValue()) {
7201         Pred = ICmpInst::ICMP_NE;
7202         Changed = true;
7203         break;
7204       }
7205       if ((RA - 1).isMinValue()) {
7206         Pred = ICmpInst::ICMP_EQ;
7207         RHS = getConstant(RA - 1);
7208         Changed = true;
7209         break;
7210       }
7211       if (RA.isMinValue()) goto trivially_false;
7212       break;
7213     case ICmpInst::ICMP_SGT:
7214       if (RA.isMinSignedValue()) {
7215         Pred = ICmpInst::ICMP_NE;
7216         Changed = true;
7217         break;
7218       }
7219       if ((RA + 1).isMaxSignedValue()) {
7220         Pred = ICmpInst::ICMP_EQ;
7221         RHS = getConstant(RA + 1);
7222         Changed = true;
7223         break;
7224       }
7225       if (RA.isMaxSignedValue()) goto trivially_false;
7226       break;
7227     case ICmpInst::ICMP_SLT:
7228       if (RA.isMaxSignedValue()) {
7229         Pred = ICmpInst::ICMP_NE;
7230         Changed = true;
7231         break;
7232       }
7233       if ((RA - 1).isMinSignedValue()) {
7234        Pred = ICmpInst::ICMP_EQ;
7235        RHS = getConstant(RA - 1);
7236         Changed = true;
7237        break;
7238       }
7239       if (RA.isMinSignedValue()) goto trivially_false;
7240       break;
7241     }
7242   }
7243 
7244   // Check for obvious equality.
7245   if (HasSameValue(LHS, RHS)) {
7246     if (ICmpInst::isTrueWhenEqual(Pred))
7247       goto trivially_true;
7248     if (ICmpInst::isFalseWhenEqual(Pred))
7249       goto trivially_false;
7250   }
7251 
7252   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7253   // adding or subtracting 1 from one of the operands.
7254   switch (Pred) {
7255   case ICmpInst::ICMP_SLE:
7256     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7257       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7258                        SCEV::FlagNSW);
7259       Pred = ICmpInst::ICMP_SLT;
7260       Changed = true;
7261     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7262       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7263                        SCEV::FlagNSW);
7264       Pred = ICmpInst::ICMP_SLT;
7265       Changed = true;
7266     }
7267     break;
7268   case ICmpInst::ICMP_SGE:
7269     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7270       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7271                        SCEV::FlagNSW);
7272       Pred = ICmpInst::ICMP_SGT;
7273       Changed = true;
7274     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7275       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7276                        SCEV::FlagNSW);
7277       Pred = ICmpInst::ICMP_SGT;
7278       Changed = true;
7279     }
7280     break;
7281   case ICmpInst::ICMP_ULE:
7282     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7283       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7284                        SCEV::FlagNUW);
7285       Pred = ICmpInst::ICMP_ULT;
7286       Changed = true;
7287     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7288       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7289       Pred = ICmpInst::ICMP_ULT;
7290       Changed = true;
7291     }
7292     break;
7293   case ICmpInst::ICMP_UGE:
7294     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7295       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7296       Pred = ICmpInst::ICMP_UGT;
7297       Changed = true;
7298     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7299       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7300                        SCEV::FlagNUW);
7301       Pred = ICmpInst::ICMP_UGT;
7302       Changed = true;
7303     }
7304     break;
7305   default:
7306     break;
7307   }
7308 
7309   // TODO: More simplifications are possible here.
7310 
7311   // Recursively simplify until we either hit a recursion limit or nothing
7312   // changes.
7313   if (Changed)
7314     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7315 
7316   return Changed;
7317 
7318 trivially_true:
7319   // Return 0 == 0.
7320   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7321   Pred = ICmpInst::ICMP_EQ;
7322   return true;
7323 
7324 trivially_false:
7325   // Return 0 != 0.
7326   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7327   Pred = ICmpInst::ICMP_NE;
7328   return true;
7329 }
7330 
7331 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7332   return getSignedRange(S).getSignedMax().isNegative();
7333 }
7334 
7335 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7336   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7337 }
7338 
7339 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7340   return !getSignedRange(S).getSignedMin().isNegative();
7341 }
7342 
7343 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7344   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7345 }
7346 
7347 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7348   return isKnownNegative(S) || isKnownPositive(S);
7349 }
7350 
7351 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7352                                        const SCEV *LHS, const SCEV *RHS) {
7353   // Canonicalize the inputs first.
7354   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7355 
7356   // If LHS or RHS is an addrec, check to see if the condition is true in
7357   // every iteration of the loop.
7358   // If LHS and RHS are both addrec, both conditions must be true in
7359   // every iteration of the loop.
7360   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7361   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7362   bool LeftGuarded = false;
7363   bool RightGuarded = false;
7364   if (LAR) {
7365     const Loop *L = LAR->getLoop();
7366     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7367         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7368       if (!RAR) return true;
7369       LeftGuarded = true;
7370     }
7371   }
7372   if (RAR) {
7373     const Loop *L = RAR->getLoop();
7374     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7375         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7376       if (!LAR) return true;
7377       RightGuarded = true;
7378     }
7379   }
7380   if (LeftGuarded && RightGuarded)
7381     return true;
7382 
7383   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7384     return true;
7385 
7386   // Otherwise see what can be done with known constant ranges.
7387   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7388 }
7389 
7390 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7391                                            ICmpInst::Predicate Pred,
7392                                            bool &Increasing) {
7393   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7394 
7395 #ifndef NDEBUG
7396   // Verify an invariant: inverting the predicate should turn a monotonically
7397   // increasing change to a monotonically decreasing one, and vice versa.
7398   bool IncreasingSwapped;
7399   bool ResultSwapped = isMonotonicPredicateImpl(
7400       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7401 
7402   assert(Result == ResultSwapped && "should be able to analyze both!");
7403   if (ResultSwapped)
7404     assert(Increasing == !IncreasingSwapped &&
7405            "monotonicity should flip as we flip the predicate");
7406 #endif
7407 
7408   return Result;
7409 }
7410 
7411 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7412                                                ICmpInst::Predicate Pred,
7413                                                bool &Increasing) {
7414 
7415   // A zero step value for LHS means the induction variable is essentially a
7416   // loop invariant value. We don't really depend on the predicate actually
7417   // flipping from false to true (for increasing predicates, and the other way
7418   // around for decreasing predicates), all we care about is that *if* the
7419   // predicate changes then it only changes from false to true.
7420   //
7421   // A zero step value in itself is not very useful, but there may be places
7422   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7423   // as general as possible.
7424 
7425   switch (Pred) {
7426   default:
7427     return false; // Conservative answer
7428 
7429   case ICmpInst::ICMP_UGT:
7430   case ICmpInst::ICMP_UGE:
7431   case ICmpInst::ICMP_ULT:
7432   case ICmpInst::ICMP_ULE:
7433     if (!LHS->hasNoUnsignedWrap())
7434       return false;
7435 
7436     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7437     return true;
7438 
7439   case ICmpInst::ICMP_SGT:
7440   case ICmpInst::ICMP_SGE:
7441   case ICmpInst::ICMP_SLT:
7442   case ICmpInst::ICMP_SLE: {
7443     if (!LHS->hasNoSignedWrap())
7444       return false;
7445 
7446     const SCEV *Step = LHS->getStepRecurrence(*this);
7447 
7448     if (isKnownNonNegative(Step)) {
7449       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7450       return true;
7451     }
7452 
7453     if (isKnownNonPositive(Step)) {
7454       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7455       return true;
7456     }
7457 
7458     return false;
7459   }
7460 
7461   }
7462 
7463   llvm_unreachable("switch has default clause!");
7464 }
7465 
7466 bool ScalarEvolution::isLoopInvariantPredicate(
7467     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7468     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7469     const SCEV *&InvariantRHS) {
7470 
7471   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7472   if (!isLoopInvariant(RHS, L)) {
7473     if (!isLoopInvariant(LHS, L))
7474       return false;
7475 
7476     std::swap(LHS, RHS);
7477     Pred = ICmpInst::getSwappedPredicate(Pred);
7478   }
7479 
7480   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7481   if (!ArLHS || ArLHS->getLoop() != L)
7482     return false;
7483 
7484   bool Increasing;
7485   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7486     return false;
7487 
7488   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7489   // true as the loop iterates, and the backedge is control dependent on
7490   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7491   //
7492   //   * if the predicate was false in the first iteration then the predicate
7493   //     is never evaluated again, since the loop exits without taking the
7494   //     backedge.
7495   //   * if the predicate was true in the first iteration then it will
7496   //     continue to be true for all future iterations since it is
7497   //     monotonically increasing.
7498   //
7499   // For both the above possibilities, we can replace the loop varying
7500   // predicate with its value on the first iteration of the loop (which is
7501   // loop invariant).
7502   //
7503   // A similar reasoning applies for a monotonically decreasing predicate, by
7504   // replacing true with false and false with true in the above two bullets.
7505 
7506   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7507 
7508   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7509     return false;
7510 
7511   InvariantPred = Pred;
7512   InvariantLHS = ArLHS->getStart();
7513   InvariantRHS = RHS;
7514   return true;
7515 }
7516 
7517 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7518     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7519   if (HasSameValue(LHS, RHS))
7520     return ICmpInst::isTrueWhenEqual(Pred);
7521 
7522   // This code is split out from isKnownPredicate because it is called from
7523   // within isLoopEntryGuardedByCond.
7524 
7525   auto CheckRanges =
7526       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7527     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7528         .contains(RangeLHS);
7529   };
7530 
7531   // The check at the top of the function catches the case where the values are
7532   // known to be equal.
7533   if (Pred == CmpInst::ICMP_EQ)
7534     return false;
7535 
7536   if (Pred == CmpInst::ICMP_NE)
7537     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7538            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7539            isKnownNonZero(getMinusSCEV(LHS, RHS));
7540 
7541   if (CmpInst::isSigned(Pred))
7542     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7543 
7544   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7545 }
7546 
7547 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7548                                                     const SCEV *LHS,
7549                                                     const SCEV *RHS) {
7550 
7551   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7552   // Return Y via OutY.
7553   auto MatchBinaryAddToConst =
7554       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7555              SCEV::NoWrapFlags ExpectedFlags) {
7556     const SCEV *NonConstOp, *ConstOp;
7557     SCEV::NoWrapFlags FlagsPresent;
7558 
7559     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7560         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7561       return false;
7562 
7563     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7564     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7565   };
7566 
7567   APInt C;
7568 
7569   switch (Pred) {
7570   default:
7571     break;
7572 
7573   case ICmpInst::ICMP_SGE:
7574     std::swap(LHS, RHS);
7575   case ICmpInst::ICMP_SLE:
7576     // X s<= (X + C)<nsw> if C >= 0
7577     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7578       return true;
7579 
7580     // (X + C)<nsw> s<= X if C <= 0
7581     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7582         !C.isStrictlyPositive())
7583       return true;
7584     break;
7585 
7586   case ICmpInst::ICMP_SGT:
7587     std::swap(LHS, RHS);
7588   case ICmpInst::ICMP_SLT:
7589     // X s< (X + C)<nsw> if C > 0
7590     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7591         C.isStrictlyPositive())
7592       return true;
7593 
7594     // (X + C)<nsw> s< X if C < 0
7595     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7596       return true;
7597     break;
7598   }
7599 
7600   return false;
7601 }
7602 
7603 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7604                                                    const SCEV *LHS,
7605                                                    const SCEV *RHS) {
7606   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7607     return false;
7608 
7609   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7610   // the stack can result in exponential time complexity.
7611   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7612 
7613   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7614   //
7615   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7616   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7617   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7618   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7619   // use isKnownPredicate later if needed.
7620   return isKnownNonNegative(RHS) &&
7621          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7622          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7623 }
7624 
7625 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7626 /// protected by a conditional between LHS and RHS.  This is used to
7627 /// to eliminate casts.
7628 bool
7629 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7630                                              ICmpInst::Predicate Pred,
7631                                              const SCEV *LHS, const SCEV *RHS) {
7632   // Interpret a null as meaning no loop, where there is obviously no guard
7633   // (interprocedural conditions notwithstanding).
7634   if (!L) return true;
7635 
7636   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7637     return true;
7638 
7639   BasicBlock *Latch = L->getLoopLatch();
7640   if (!Latch)
7641     return false;
7642 
7643   BranchInst *LoopContinuePredicate =
7644     dyn_cast<BranchInst>(Latch->getTerminator());
7645   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7646       isImpliedCond(Pred, LHS, RHS,
7647                     LoopContinuePredicate->getCondition(),
7648                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7649     return true;
7650 
7651   // We don't want more than one activation of the following loops on the stack
7652   // -- that can lead to O(n!) time complexity.
7653   if (WalkingBEDominatingConds)
7654     return false;
7655 
7656   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7657 
7658   // See if we can exploit a trip count to prove the predicate.
7659   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7660   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7661   if (LatchBECount != getCouldNotCompute()) {
7662     // We know that Latch branches back to the loop header exactly
7663     // LatchBECount times.  This means the backdege condition at Latch is
7664     // equivalent to  "{0,+,1} u< LatchBECount".
7665     Type *Ty = LatchBECount->getType();
7666     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7667     const SCEV *LoopCounter =
7668       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7669     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7670                       LatchBECount))
7671       return true;
7672   }
7673 
7674   // Check conditions due to any @llvm.assume intrinsics.
7675   for (auto &AssumeVH : AC.assumptions()) {
7676     if (!AssumeVH)
7677       continue;
7678     auto *CI = cast<CallInst>(AssumeVH);
7679     if (!DT.dominates(CI, Latch->getTerminator()))
7680       continue;
7681 
7682     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7683       return true;
7684   }
7685 
7686   // If the loop is not reachable from the entry block, we risk running into an
7687   // infinite loop as we walk up into the dom tree.  These loops do not matter
7688   // anyway, so we just return a conservative answer when we see them.
7689   if (!DT.isReachableFromEntry(L->getHeader()))
7690     return false;
7691 
7692   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7693        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7694 
7695     assert(DTN && "should reach the loop header before reaching the root!");
7696 
7697     BasicBlock *BB = DTN->getBlock();
7698     BasicBlock *PBB = BB->getSinglePredecessor();
7699     if (!PBB)
7700       continue;
7701 
7702     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7703     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7704       continue;
7705 
7706     Value *Condition = ContinuePredicate->getCondition();
7707 
7708     // If we have an edge `E` within the loop body that dominates the only
7709     // latch, the condition guarding `E` also guards the backedge.  This
7710     // reasoning works only for loops with a single latch.
7711 
7712     BasicBlockEdge DominatingEdge(PBB, BB);
7713     if (DominatingEdge.isSingleEdge()) {
7714       // We're constructively (and conservatively) enumerating edges within the
7715       // loop body that dominate the latch.  The dominator tree better agree
7716       // with us on this:
7717       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
7718 
7719       if (isImpliedCond(Pred, LHS, RHS, Condition,
7720                         BB != ContinuePredicate->getSuccessor(0)))
7721         return true;
7722     }
7723   }
7724 
7725   return false;
7726 }
7727 
7728 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
7729 /// by a conditional between LHS and RHS.  This is used to help avoid max
7730 /// expressions in loop trip counts, and to eliminate casts.
7731 bool
7732 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7733                                           ICmpInst::Predicate Pred,
7734                                           const SCEV *LHS, const SCEV *RHS) {
7735   // Interpret a null as meaning no loop, where there is obviously no guard
7736   // (interprocedural conditions notwithstanding).
7737   if (!L) return false;
7738 
7739   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7740     return true;
7741 
7742   // Starting at the loop predecessor, climb up the predecessor chain, as long
7743   // as there are predecessors that can be found that have unique successors
7744   // leading to the original header.
7745   for (std::pair<BasicBlock *, BasicBlock *>
7746          Pair(L->getLoopPredecessor(), L->getHeader());
7747        Pair.first;
7748        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
7749 
7750     BranchInst *LoopEntryPredicate =
7751       dyn_cast<BranchInst>(Pair.first->getTerminator());
7752     if (!LoopEntryPredicate ||
7753         LoopEntryPredicate->isUnconditional())
7754       continue;
7755 
7756     if (isImpliedCond(Pred, LHS, RHS,
7757                       LoopEntryPredicate->getCondition(),
7758                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
7759       return true;
7760   }
7761 
7762   // Check conditions due to any @llvm.assume intrinsics.
7763   for (auto &AssumeVH : AC.assumptions()) {
7764     if (!AssumeVH)
7765       continue;
7766     auto *CI = cast<CallInst>(AssumeVH);
7767     if (!DT.dominates(CI, L->getHeader()))
7768       continue;
7769 
7770     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7771       return true;
7772   }
7773 
7774   return false;
7775 }
7776 
7777 namespace {
7778 /// RAII wrapper to prevent recursive application of isImpliedCond.
7779 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
7780 /// currently evaluating isImpliedCond.
7781 struct MarkPendingLoopPredicate {
7782   Value *Cond;
7783   DenseSet<Value*> &LoopPreds;
7784   bool Pending;
7785 
7786   MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
7787     : Cond(C), LoopPreds(LP) {
7788     Pending = !LoopPreds.insert(Cond).second;
7789   }
7790   ~MarkPendingLoopPredicate() {
7791     if (!Pending)
7792       LoopPreds.erase(Cond);
7793   }
7794 };
7795 } // end anonymous namespace
7796 
7797 /// isImpliedCond - Test whether the condition described by Pred, LHS,
7798 /// and RHS is true whenever the given Cond value evaluates to true.
7799 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
7800                                     const SCEV *LHS, const SCEV *RHS,
7801                                     Value *FoundCondValue,
7802                                     bool Inverse) {
7803   MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
7804   if (Mark.Pending)
7805     return false;
7806 
7807   // Recursively handle And and Or conditions.
7808   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
7809     if (BO->getOpcode() == Instruction::And) {
7810       if (!Inverse)
7811         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7812                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
7813     } else if (BO->getOpcode() == Instruction::Or) {
7814       if (Inverse)
7815         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
7816                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
7817     }
7818   }
7819 
7820   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
7821   if (!ICI) return false;
7822 
7823   // Now that we found a conditional branch that dominates the loop or controls
7824   // the loop latch. Check to see if it is the comparison we are looking for.
7825   ICmpInst::Predicate FoundPred;
7826   if (Inverse)
7827     FoundPred = ICI->getInversePredicate();
7828   else
7829     FoundPred = ICI->getPredicate();
7830 
7831   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
7832   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
7833 
7834   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
7835 }
7836 
7837 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
7838                                     const SCEV *RHS,
7839                                     ICmpInst::Predicate FoundPred,
7840                                     const SCEV *FoundLHS,
7841                                     const SCEV *FoundRHS) {
7842   // Balance the types.
7843   if (getTypeSizeInBits(LHS->getType()) <
7844       getTypeSizeInBits(FoundLHS->getType())) {
7845     if (CmpInst::isSigned(Pred)) {
7846       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
7847       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
7848     } else {
7849       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
7850       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
7851     }
7852   } else if (getTypeSizeInBits(LHS->getType()) >
7853       getTypeSizeInBits(FoundLHS->getType())) {
7854     if (CmpInst::isSigned(FoundPred)) {
7855       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
7856       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
7857     } else {
7858       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
7859       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
7860     }
7861   }
7862 
7863   // Canonicalize the query to match the way instcombine will have
7864   // canonicalized the comparison.
7865   if (SimplifyICmpOperands(Pred, LHS, RHS))
7866     if (LHS == RHS)
7867       return CmpInst::isTrueWhenEqual(Pred);
7868   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
7869     if (FoundLHS == FoundRHS)
7870       return CmpInst::isFalseWhenEqual(FoundPred);
7871 
7872   // Check to see if we can make the LHS or RHS match.
7873   if (LHS == FoundRHS || RHS == FoundLHS) {
7874     if (isa<SCEVConstant>(RHS)) {
7875       std::swap(FoundLHS, FoundRHS);
7876       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
7877     } else {
7878       std::swap(LHS, RHS);
7879       Pred = ICmpInst::getSwappedPredicate(Pred);
7880     }
7881   }
7882 
7883   // Check whether the found predicate is the same as the desired predicate.
7884   if (FoundPred == Pred)
7885     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7886 
7887   // Check whether swapping the found predicate makes it the same as the
7888   // desired predicate.
7889   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
7890     if (isa<SCEVConstant>(RHS))
7891       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
7892     else
7893       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
7894                                    RHS, LHS, FoundLHS, FoundRHS);
7895   }
7896 
7897   // Unsigned comparison is the same as signed comparison when both the operands
7898   // are non-negative.
7899   if (CmpInst::isUnsigned(FoundPred) &&
7900       CmpInst::getSignedPredicate(FoundPred) == Pred &&
7901       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
7902     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
7903 
7904   // Check if we can make progress by sharpening ranges.
7905   if (FoundPred == ICmpInst::ICMP_NE &&
7906       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
7907 
7908     const SCEVConstant *C = nullptr;
7909     const SCEV *V = nullptr;
7910 
7911     if (isa<SCEVConstant>(FoundLHS)) {
7912       C = cast<SCEVConstant>(FoundLHS);
7913       V = FoundRHS;
7914     } else {
7915       C = cast<SCEVConstant>(FoundRHS);
7916       V = FoundLHS;
7917     }
7918 
7919     // The guarding predicate tells us that C != V. If the known range
7920     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
7921     // range we consider has to correspond to same signedness as the
7922     // predicate we're interested in folding.
7923 
7924     APInt Min = ICmpInst::isSigned(Pred) ?
7925         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
7926 
7927     if (Min == C->getAPInt()) {
7928       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
7929       // This is true even if (Min + 1) wraps around -- in case of
7930       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
7931 
7932       APInt SharperMin = Min + 1;
7933 
7934       switch (Pred) {
7935         case ICmpInst::ICMP_SGE:
7936         case ICmpInst::ICMP_UGE:
7937           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
7938           // RHS, we're done.
7939           if (isImpliedCondOperands(Pred, LHS, RHS, V,
7940                                     getConstant(SharperMin)))
7941             return true;
7942 
7943         case ICmpInst::ICMP_SGT:
7944         case ICmpInst::ICMP_UGT:
7945           // We know from the range information that (V `Pred` Min ||
7946           // V == Min).  We know from the guarding condition that !(V
7947           // == Min).  This gives us
7948           //
7949           //       V `Pred` Min || V == Min && !(V == Min)
7950           //   =>  V `Pred` Min
7951           //
7952           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
7953 
7954           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
7955             return true;
7956 
7957         default:
7958           // No change
7959           break;
7960       }
7961     }
7962   }
7963 
7964   // Check whether the actual condition is beyond sufficient.
7965   if (FoundPred == ICmpInst::ICMP_EQ)
7966     if (ICmpInst::isTrueWhenEqual(Pred))
7967       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
7968         return true;
7969   if (Pred == ICmpInst::ICMP_NE)
7970     if (!ICmpInst::isTrueWhenEqual(FoundPred))
7971       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
7972         return true;
7973 
7974   // Otherwise assume the worst.
7975   return false;
7976 }
7977 
7978 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
7979                                      const SCEV *&L, const SCEV *&R,
7980                                      SCEV::NoWrapFlags &Flags) {
7981   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
7982   if (!AE || AE->getNumOperands() != 2)
7983     return false;
7984 
7985   L = AE->getOperand(0);
7986   R = AE->getOperand(1);
7987   Flags = AE->getNoWrapFlags();
7988   return true;
7989 }
7990 
7991 bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
7992                                                 const SCEV *More,
7993                                                 APInt &C) {
7994   // We avoid subtracting expressions here because this function is usually
7995   // fairly deep in the call stack (i.e. is called many times).
7996 
7997   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
7998     const auto *LAR = cast<SCEVAddRecExpr>(Less);
7999     const auto *MAR = cast<SCEVAddRecExpr>(More);
8000 
8001     if (LAR->getLoop() != MAR->getLoop())
8002       return false;
8003 
8004     // We look at affine expressions only; not for correctness but to keep
8005     // getStepRecurrence cheap.
8006     if (!LAR->isAffine() || !MAR->isAffine())
8007       return false;
8008 
8009     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8010       return false;
8011 
8012     Less = LAR->getStart();
8013     More = MAR->getStart();
8014 
8015     // fall through
8016   }
8017 
8018   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8019     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8020     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8021     C = M - L;
8022     return true;
8023   }
8024 
8025   const SCEV *L, *R;
8026   SCEV::NoWrapFlags Flags;
8027   if (splitBinaryAdd(Less, L, R, Flags))
8028     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8029       if (R == More) {
8030         C = -(LC->getAPInt());
8031         return true;
8032       }
8033 
8034   if (splitBinaryAdd(More, L, R, Flags))
8035     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8036       if (R == Less) {
8037         C = LC->getAPInt();
8038         return true;
8039       }
8040 
8041   return false;
8042 }
8043 
8044 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8045     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8046     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8047   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8048     return false;
8049 
8050   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8051   if (!AddRecLHS)
8052     return false;
8053 
8054   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8055   if (!AddRecFoundLHS)
8056     return false;
8057 
8058   // We'd like to let SCEV reason about control dependencies, so we constrain
8059   // both the inequalities to be about add recurrences on the same loop.  This
8060   // way we can use isLoopEntryGuardedByCond later.
8061 
8062   const Loop *L = AddRecFoundLHS->getLoop();
8063   if (L != AddRecLHS->getLoop())
8064     return false;
8065 
8066   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8067   //
8068   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8069   //                                                                  ... (2)
8070   //
8071   // Informal proof for (2), assuming (1) [*]:
8072   //
8073   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8074   //
8075   // Then
8076   //
8077   //       FoundLHS s< FoundRHS s< INT_MIN - C
8078   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8079   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8080   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8081   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8082   // <=>  FoundLHS + C s< FoundRHS + C
8083   //
8084   // [*]: (1) can be proved by ruling out overflow.
8085   //
8086   // [**]: This can be proved by analyzing all the four possibilities:
8087   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8088   //    (A s>= 0, B s>= 0).
8089   //
8090   // Note:
8091   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8092   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8093   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8094   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8095   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8096   // C)".
8097 
8098   APInt LDiff, RDiff;
8099   if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
8100       !computeConstantDifference(FoundRHS, RHS, RDiff) ||
8101       LDiff != RDiff)
8102     return false;
8103 
8104   if (LDiff == 0)
8105     return true;
8106 
8107   APInt FoundRHSLimit;
8108 
8109   if (Pred == CmpInst::ICMP_ULT) {
8110     FoundRHSLimit = -RDiff;
8111   } else {
8112     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8113     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
8114   }
8115 
8116   // Try to prove (1) or (2), as needed.
8117   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8118                                   getConstant(FoundRHSLimit));
8119 }
8120 
8121 /// isImpliedCondOperands - Test whether the condition described by Pred,
8122 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
8123 /// and FoundRHS is true.
8124 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8125                                             const SCEV *LHS, const SCEV *RHS,
8126                                             const SCEV *FoundLHS,
8127                                             const SCEV *FoundRHS) {
8128   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8129     return true;
8130 
8131   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8132     return true;
8133 
8134   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8135                                      FoundLHS, FoundRHS) ||
8136          // ~x < ~y --> x > y
8137          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8138                                      getNotSCEV(FoundRHS),
8139                                      getNotSCEV(FoundLHS));
8140 }
8141 
8142 
8143 /// If Expr computes ~A, return A else return nullptr
8144 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8145   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8146   if (!Add || Add->getNumOperands() != 2 ||
8147       !Add->getOperand(0)->isAllOnesValue())
8148     return nullptr;
8149 
8150   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8151   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8152       !AddRHS->getOperand(0)->isAllOnesValue())
8153     return nullptr;
8154 
8155   return AddRHS->getOperand(1);
8156 }
8157 
8158 
8159 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8160 template<typename MaxExprType>
8161 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8162                               const SCEV *Candidate) {
8163   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8164   if (!MaxExpr) return false;
8165 
8166   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8167 }
8168 
8169 
8170 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8171 template<typename MaxExprType>
8172 static bool IsMinConsistingOf(ScalarEvolution &SE,
8173                               const SCEV *MaybeMinExpr,
8174                               const SCEV *Candidate) {
8175   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8176   if (!MaybeMaxExpr)
8177     return false;
8178 
8179   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8180 }
8181 
8182 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8183                                            ICmpInst::Predicate Pred,
8184                                            const SCEV *LHS, const SCEV *RHS) {
8185 
8186   // If both sides are affine addrecs for the same loop, with equal
8187   // steps, and we know the recurrences don't wrap, then we only
8188   // need to check the predicate on the starting values.
8189 
8190   if (!ICmpInst::isRelational(Pred))
8191     return false;
8192 
8193   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8194   if (!LAR)
8195     return false;
8196   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8197   if (!RAR)
8198     return false;
8199   if (LAR->getLoop() != RAR->getLoop())
8200     return false;
8201   if (!LAR->isAffine() || !RAR->isAffine())
8202     return false;
8203 
8204   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8205     return false;
8206 
8207   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8208                          SCEV::FlagNSW : SCEV::FlagNUW;
8209   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8210     return false;
8211 
8212   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8213 }
8214 
8215 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8216 /// expression?
8217 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8218                                         ICmpInst::Predicate Pred,
8219                                         const SCEV *LHS, const SCEV *RHS) {
8220   switch (Pred) {
8221   default:
8222     return false;
8223 
8224   case ICmpInst::ICMP_SGE:
8225     std::swap(LHS, RHS);
8226     // fall through
8227   case ICmpInst::ICMP_SLE:
8228     return
8229       // min(A, ...) <= A
8230       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8231       // A <= max(A, ...)
8232       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8233 
8234   case ICmpInst::ICMP_UGE:
8235     std::swap(LHS, RHS);
8236     // fall through
8237   case ICmpInst::ICMP_ULE:
8238     return
8239       // min(A, ...) <= A
8240       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8241       // A <= max(A, ...)
8242       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8243   }
8244 
8245   llvm_unreachable("covered switch fell through?!");
8246 }
8247 
8248 /// isImpliedCondOperandsHelper - Test whether the condition described by
8249 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
8250 /// FoundLHS, and FoundRHS is true.
8251 bool
8252 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8253                                              const SCEV *LHS, const SCEV *RHS,
8254                                              const SCEV *FoundLHS,
8255                                              const SCEV *FoundRHS) {
8256   auto IsKnownPredicateFull =
8257       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8258     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8259            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8260            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8261            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8262   };
8263 
8264   switch (Pred) {
8265   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8266   case ICmpInst::ICMP_EQ:
8267   case ICmpInst::ICMP_NE:
8268     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8269       return true;
8270     break;
8271   case ICmpInst::ICMP_SLT:
8272   case ICmpInst::ICMP_SLE:
8273     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8274         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8275       return true;
8276     break;
8277   case ICmpInst::ICMP_SGT:
8278   case ICmpInst::ICMP_SGE:
8279     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8280         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8281       return true;
8282     break;
8283   case ICmpInst::ICMP_ULT:
8284   case ICmpInst::ICMP_ULE:
8285     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8286         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8287       return true;
8288     break;
8289   case ICmpInst::ICMP_UGT:
8290   case ICmpInst::ICMP_UGE:
8291     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8292         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8293       return true;
8294     break;
8295   }
8296 
8297   return false;
8298 }
8299 
8300 /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
8301 /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
8302 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8303                                                      const SCEV *LHS,
8304                                                      const SCEV *RHS,
8305                                                      const SCEV *FoundLHS,
8306                                                      const SCEV *FoundRHS) {
8307   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8308     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8309     // reduce the compile time impact of this optimization.
8310     return false;
8311 
8312   const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
8313   if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
8314       !isa<SCEVConstant>(AddLHS->getOperand(0)))
8315     return false;
8316 
8317   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8318 
8319   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8320   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8321   ConstantRange FoundLHSRange =
8322       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8323 
8324   // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
8325   // for `LHS`:
8326   APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt();
8327   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
8328 
8329   // We can also compute the range of values for `LHS` that satisfy the
8330   // consequent, "`LHS` `Pred` `RHS`":
8331   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8332   ConstantRange SatisfyingLHSRange =
8333       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8334 
8335   // The antecedent implies the consequent if every value of `LHS` that
8336   // satisfies the antecedent also satisfies the consequent.
8337   return SatisfyingLHSRange.contains(LHSRange);
8338 }
8339 
8340 // Verify if an linear IV with positive stride can overflow when in a
8341 // less-than comparison, knowing the invariant term of the comparison, the
8342 // stride and the knowledge of NSW/NUW flags on the recurrence.
8343 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8344                                          bool IsSigned, bool NoWrap) {
8345   if (NoWrap) return false;
8346 
8347   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8348   const SCEV *One = getOne(Stride->getType());
8349 
8350   if (IsSigned) {
8351     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8352     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8353     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8354                                 .getSignedMax();
8355 
8356     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8357     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8358   }
8359 
8360   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8361   APInt MaxValue = APInt::getMaxValue(BitWidth);
8362   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8363                               .getUnsignedMax();
8364 
8365   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8366   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8367 }
8368 
8369 // Verify if an linear IV with negative stride can overflow when in a
8370 // greater-than comparison, knowing the invariant term of the comparison,
8371 // the stride and the knowledge of NSW/NUW flags on the recurrence.
8372 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8373                                          bool IsSigned, bool NoWrap) {
8374   if (NoWrap) return false;
8375 
8376   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8377   const SCEV *One = getOne(Stride->getType());
8378 
8379   if (IsSigned) {
8380     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8381     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8382     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8383                                .getSignedMax();
8384 
8385     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8386     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8387   }
8388 
8389   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8390   APInt MinValue = APInt::getMinValue(BitWidth);
8391   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8392                             .getUnsignedMax();
8393 
8394   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8395   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8396 }
8397 
8398 // Compute the backedge taken count knowing the interval difference, the
8399 // stride and presence of the equality in the comparison.
8400 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8401                                             bool Equality) {
8402   const SCEV *One = getOne(Step->getType());
8403   Delta = Equality ? getAddExpr(Delta, Step)
8404                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8405   return getUDivExpr(Delta, Step);
8406 }
8407 
8408 /// HowManyLessThans - Return the number of times a backedge containing the
8409 /// specified less-than comparison will execute.  If not computable, return
8410 /// CouldNotCompute.
8411 ///
8412 /// @param ControlsExit is true when the LHS < RHS condition directly controls
8413 /// the branch (loops exits only if condition is true). In this case, we can use
8414 /// NoWrapFlags to skip overflow checks.
8415 ScalarEvolution::ExitLimit
8416 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
8417                                   const Loop *L, bool IsSigned,
8418                                   bool ControlsExit) {
8419   // We handle only IV < Invariant
8420   if (!isLoopInvariant(RHS, L))
8421     return getCouldNotCompute();
8422 
8423   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8424 
8425   // Avoid weird loops
8426   if (!IV || IV->getLoop() != L || !IV->isAffine())
8427     return getCouldNotCompute();
8428 
8429   bool NoWrap = ControlsExit &&
8430                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8431 
8432   const SCEV *Stride = IV->getStepRecurrence(*this);
8433 
8434   // Avoid negative or zero stride values
8435   if (!isKnownPositive(Stride))
8436     return getCouldNotCompute();
8437 
8438   // Avoid proven overflow cases: this will ensure that the backedge taken count
8439   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8440   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8441   // behaviors like the case of C language.
8442   if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8443     return getCouldNotCompute();
8444 
8445   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8446                                       : ICmpInst::ICMP_ULT;
8447   const SCEV *Start = IV->getStart();
8448   const SCEV *End = RHS;
8449   if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
8450     const SCEV *Diff = getMinusSCEV(RHS, Start);
8451     // If we have NoWrap set, then we can assume that the increment won't
8452     // overflow, in which case if RHS - Start is a constant, we don't need to
8453     // do a max operation since we can just figure it out statically
8454     if (NoWrap && isa<SCEVConstant>(Diff)) {
8455       APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
8456       if (D.isNegative())
8457         End = Start;
8458     } else
8459       End = IsSigned ? getSMaxExpr(RHS, Start)
8460                      : getUMaxExpr(RHS, Start);
8461   }
8462 
8463   const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8464 
8465   APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8466                             : getUnsignedRange(Start).getUnsignedMin();
8467 
8468   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8469                              : getUnsignedRange(Stride).getUnsignedMin();
8470 
8471   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8472   APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8473                          : APInt::getMaxValue(BitWidth) - (MinStride - 1);
8474 
8475   // Although End can be a MAX expression we estimate MaxEnd considering only
8476   // the case End = RHS. This is safe because in the other case (End - Start)
8477   // is zero, leading to a zero maximum backedge taken count.
8478   APInt MaxEnd =
8479     IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8480              : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8481 
8482   const SCEV *MaxBECount;
8483   if (isa<SCEVConstant>(BECount))
8484     MaxBECount = BECount;
8485   else
8486     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8487                                 getConstant(MinStride), false);
8488 
8489   if (isa<SCEVCouldNotCompute>(MaxBECount))
8490     MaxBECount = BECount;
8491 
8492   return ExitLimit(BECount, MaxBECount);
8493 }
8494 
8495 ScalarEvolution::ExitLimit
8496 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8497                                      const Loop *L, bool IsSigned,
8498                                      bool ControlsExit) {
8499   // We handle only IV > Invariant
8500   if (!isLoopInvariant(RHS, L))
8501     return getCouldNotCompute();
8502 
8503   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8504 
8505   // Avoid weird loops
8506   if (!IV || IV->getLoop() != L || !IV->isAffine())
8507     return getCouldNotCompute();
8508 
8509   bool NoWrap = ControlsExit &&
8510                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8511 
8512   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8513 
8514   // Avoid negative or zero stride values
8515   if (!isKnownPositive(Stride))
8516     return getCouldNotCompute();
8517 
8518   // Avoid proven overflow cases: this will ensure that the backedge taken count
8519   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8520   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8521   // behaviors like the case of C language.
8522   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8523     return getCouldNotCompute();
8524 
8525   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8526                                       : ICmpInst::ICMP_UGT;
8527 
8528   const SCEV *Start = IV->getStart();
8529   const SCEV *End = RHS;
8530   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8531     const SCEV *Diff = getMinusSCEV(RHS, Start);
8532     // If we have NoWrap set, then we can assume that the increment won't
8533     // overflow, in which case if RHS - Start is a constant, we don't need to
8534     // do a max operation since we can just figure it out statically
8535     if (NoWrap && isa<SCEVConstant>(Diff)) {
8536       APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
8537       if (!D.isNegative())
8538         End = Start;
8539     } else
8540       End = IsSigned ? getSMinExpr(RHS, Start)
8541                      : getUMinExpr(RHS, Start);
8542   }
8543 
8544   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8545 
8546   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8547                             : getUnsignedRange(Start).getUnsignedMax();
8548 
8549   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8550                              : getUnsignedRange(Stride).getUnsignedMin();
8551 
8552   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8553   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8554                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8555 
8556   // Although End can be a MIN expression we estimate MinEnd considering only
8557   // the case End = RHS. This is safe because in the other case (Start - End)
8558   // is zero, leading to a zero maximum backedge taken count.
8559   APInt MinEnd =
8560     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8561              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8562 
8563 
8564   const SCEV *MaxBECount = getCouldNotCompute();
8565   if (isa<SCEVConstant>(BECount))
8566     MaxBECount = BECount;
8567   else
8568     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8569                                 getConstant(MinStride), false);
8570 
8571   if (isa<SCEVCouldNotCompute>(MaxBECount))
8572     MaxBECount = BECount;
8573 
8574   return ExitLimit(BECount, MaxBECount);
8575 }
8576 
8577 /// getNumIterationsInRange - Return the number of iterations of this loop that
8578 /// produce values in the specified constant range.  Another way of looking at
8579 /// this is that it returns the first iteration number where the value is not in
8580 /// the condition, thus computing the exit count. If the iteration count can't
8581 /// be computed, an instance of SCEVCouldNotCompute is returned.
8582 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
8583                                                     ScalarEvolution &SE) const {
8584   if (Range.isFullSet())  // Infinite loop.
8585     return SE.getCouldNotCompute();
8586 
8587   // If the start is a non-zero constant, shift the range to simplify things.
8588   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8589     if (!SC->getValue()->isZero()) {
8590       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8591       Operands[0] = SE.getZero(SC->getType());
8592       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8593                                              getNoWrapFlags(FlagNW));
8594       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8595         return ShiftedAddRec->getNumIterationsInRange(
8596             Range.subtract(SC->getAPInt()), SE);
8597       // This is strange and shouldn't happen.
8598       return SE.getCouldNotCompute();
8599     }
8600 
8601   // The only time we can solve this is when we have all constant indices.
8602   // Otherwise, we cannot determine the overflow conditions.
8603   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8604     return SE.getCouldNotCompute();
8605 
8606   // Okay at this point we know that all elements of the chrec are constants and
8607   // that the start element is zero.
8608 
8609   // First check to see if the range contains zero.  If not, the first
8610   // iteration exits.
8611   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8612   if (!Range.contains(APInt(BitWidth, 0)))
8613     return SE.getZero(getType());
8614 
8615   if (isAffine()) {
8616     // If this is an affine expression then we have this situation:
8617     //   Solve {0,+,A} in Range  ===  Ax in Range
8618 
8619     // We know that zero is in the range.  If A is positive then we know that
8620     // the upper value of the range must be the first possible exit value.
8621     // If A is negative then the lower of the range is the last possible loop
8622     // value.  Also note that we already checked for a full range.
8623     APInt One(BitWidth,1);
8624     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8625     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8626 
8627     // The exit value should be (End+A)/A.
8628     APInt ExitVal = (End + A).udiv(A);
8629     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8630 
8631     // Evaluate at the exit value.  If we really did fall out of the valid
8632     // range, then we computed our trip count, otherwise wrap around or other
8633     // things must have happened.
8634     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8635     if (Range.contains(Val->getValue()))
8636       return SE.getCouldNotCompute();  // Something strange happened
8637 
8638     // Ensure that the previous value is in the range.  This is a sanity check.
8639     assert(Range.contains(
8640            EvaluateConstantChrecAtConstant(this,
8641            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8642            "Linear scev computation is off in a bad way!");
8643     return SE.getConstant(ExitValue);
8644   } else if (isQuadratic()) {
8645     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8646     // quadratic equation to solve it.  To do this, we must frame our problem in
8647     // terms of figuring out when zero is crossed, instead of when
8648     // Range.getUpper() is crossed.
8649     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8650     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8651     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8652                                              // getNoWrapFlags(FlagNW)
8653                                              FlagAnyWrap);
8654 
8655     // Next, solve the constructed addrec
8656     auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
8657     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
8658     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
8659     if (R1) {
8660       // Pick the smallest positive root value.
8661       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8662               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8663         if (!CB->getZExtValue())
8664           std::swap(R1, R2);   // R1 is the minimum root now.
8665 
8666         // Make sure the root is not off by one.  The returned iteration should
8667         // not be in the range, but the previous one should be.  When solving
8668         // for "X*X < 5", for example, we should not return a root of 2.
8669         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
8670                                                              R1->getValue(),
8671                                                              SE);
8672         if (Range.contains(R1Val->getValue())) {
8673           // The next iteration must be out of the range...
8674           ConstantInt *NextVal =
8675               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
8676 
8677           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8678           if (!Range.contains(R1Val->getValue()))
8679             return SE.getConstant(NextVal);
8680           return SE.getCouldNotCompute();  // Something strange happened
8681         }
8682 
8683         // If R1 was not in the range, then it is a good return value.  Make
8684         // sure that R1-1 WAS in the range though, just in case.
8685         ConstantInt *NextVal =
8686             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
8687         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8688         if (Range.contains(R1Val->getValue()))
8689           return R1;
8690         return SE.getCouldNotCompute();  // Something strange happened
8691       }
8692     }
8693   }
8694 
8695   return SE.getCouldNotCompute();
8696 }
8697 
8698 namespace {
8699 struct FindUndefs {
8700   bool Found;
8701   FindUndefs() : Found(false) {}
8702 
8703   bool follow(const SCEV *S) {
8704     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8705       if (isa<UndefValue>(C->getValue()))
8706         Found = true;
8707     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8708       if (isa<UndefValue>(C->getValue()))
8709         Found = true;
8710     }
8711 
8712     // Keep looking if we haven't found it yet.
8713     return !Found;
8714   }
8715   bool isDone() const {
8716     // Stop recursion if we have found an undef.
8717     return Found;
8718   }
8719 };
8720 }
8721 
8722 // Return true when S contains at least an undef value.
8723 static inline bool
8724 containsUndefs(const SCEV *S) {
8725   FindUndefs F;
8726   SCEVTraversal<FindUndefs> ST(F);
8727   ST.visitAll(S);
8728 
8729   return F.Found;
8730 }
8731 
8732 namespace {
8733 // Collect all steps of SCEV expressions.
8734 struct SCEVCollectStrides {
8735   ScalarEvolution &SE;
8736   SmallVectorImpl<const SCEV *> &Strides;
8737 
8738   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8739       : SE(SE), Strides(S) {}
8740 
8741   bool follow(const SCEV *S) {
8742     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8743       Strides.push_back(AR->getStepRecurrence(SE));
8744     return true;
8745   }
8746   bool isDone() const { return false; }
8747 };
8748 
8749 // Collect all SCEVUnknown and SCEVMulExpr expressions.
8750 struct SCEVCollectTerms {
8751   SmallVectorImpl<const SCEV *> &Terms;
8752 
8753   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8754       : Terms(T) {}
8755 
8756   bool follow(const SCEV *S) {
8757     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
8758       if (!containsUndefs(S))
8759         Terms.push_back(S);
8760 
8761       // Stop recursion: once we collected a term, do not walk its operands.
8762       return false;
8763     }
8764 
8765     // Keep looking.
8766     return true;
8767   }
8768   bool isDone() const { return false; }
8769 };
8770 
8771 // Check if a SCEV contains an AddRecExpr.
8772 struct SCEVHasAddRec {
8773   bool &ContainsAddRec;
8774 
8775   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
8776    ContainsAddRec = false;
8777   }
8778 
8779   bool follow(const SCEV *S) {
8780     if (isa<SCEVAddRecExpr>(S)) {
8781       ContainsAddRec = true;
8782 
8783       // Stop recursion: once we collected a term, do not walk its operands.
8784       return false;
8785     }
8786 
8787     // Keep looking.
8788     return true;
8789   }
8790   bool isDone() const { return false; }
8791 };
8792 
8793 // Find factors that are multiplied with an expression that (possibly as a
8794 // subexpression) contains an AddRecExpr. In the expression:
8795 //
8796 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
8797 //
8798 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
8799 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
8800 // parameters as they form a product with an induction variable.
8801 //
8802 // This collector expects all array size parameters to be in the same MulExpr.
8803 // It might be necessary to later add support for collecting parameters that are
8804 // spread over different nested MulExpr.
8805 struct SCEVCollectAddRecMultiplies {
8806   SmallVectorImpl<const SCEV *> &Terms;
8807   ScalarEvolution &SE;
8808 
8809   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
8810       : Terms(T), SE(SE) {}
8811 
8812   bool follow(const SCEV *S) {
8813     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
8814       bool HasAddRec = false;
8815       SmallVector<const SCEV *, 0> Operands;
8816       for (auto Op : Mul->operands()) {
8817         if (isa<SCEVUnknown>(Op)) {
8818           Operands.push_back(Op);
8819         } else {
8820           bool ContainsAddRec;
8821           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
8822           visitAll(Op, ContiansAddRec);
8823           HasAddRec |= ContainsAddRec;
8824         }
8825       }
8826       if (Operands.size() == 0)
8827         return true;
8828 
8829       if (!HasAddRec)
8830         return false;
8831 
8832       Terms.push_back(SE.getMulExpr(Operands));
8833       // Stop recursion: once we collected a term, do not walk its operands.
8834       return false;
8835     }
8836 
8837     // Keep looking.
8838     return true;
8839   }
8840   bool isDone() const { return false; }
8841 };
8842 }
8843 
8844 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
8845 /// two places:
8846 ///   1) The strides of AddRec expressions.
8847 ///   2) Unknowns that are multiplied with AddRec expressions.
8848 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
8849     SmallVectorImpl<const SCEV *> &Terms) {
8850   SmallVector<const SCEV *, 4> Strides;
8851   SCEVCollectStrides StrideCollector(*this, Strides);
8852   visitAll(Expr, StrideCollector);
8853 
8854   DEBUG({
8855       dbgs() << "Strides:\n";
8856       for (const SCEV *S : Strides)
8857         dbgs() << *S << "\n";
8858     });
8859 
8860   for (const SCEV *S : Strides) {
8861     SCEVCollectTerms TermCollector(Terms);
8862     visitAll(S, TermCollector);
8863   }
8864 
8865   DEBUG({
8866       dbgs() << "Terms:\n";
8867       for (const SCEV *T : Terms)
8868         dbgs() << *T << "\n";
8869     });
8870 
8871   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
8872   visitAll(Expr, MulCollector);
8873 }
8874 
8875 static bool findArrayDimensionsRec(ScalarEvolution &SE,
8876                                    SmallVectorImpl<const SCEV *> &Terms,
8877                                    SmallVectorImpl<const SCEV *> &Sizes) {
8878   int Last = Terms.size() - 1;
8879   const SCEV *Step = Terms[Last];
8880 
8881   // End of recursion.
8882   if (Last == 0) {
8883     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
8884       SmallVector<const SCEV *, 2> Qs;
8885       for (const SCEV *Op : M->operands())
8886         if (!isa<SCEVConstant>(Op))
8887           Qs.push_back(Op);
8888 
8889       Step = SE.getMulExpr(Qs);
8890     }
8891 
8892     Sizes.push_back(Step);
8893     return true;
8894   }
8895 
8896   for (const SCEV *&Term : Terms) {
8897     // Normalize the terms before the next call to findArrayDimensionsRec.
8898     const SCEV *Q, *R;
8899     SCEVDivision::divide(SE, Term, Step, &Q, &R);
8900 
8901     // Bail out when GCD does not evenly divide one of the terms.
8902     if (!R->isZero())
8903       return false;
8904 
8905     Term = Q;
8906   }
8907 
8908   // Remove all SCEVConstants.
8909   Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
8910                 return isa<SCEVConstant>(E);
8911               }),
8912               Terms.end());
8913 
8914   if (Terms.size() > 0)
8915     if (!findArrayDimensionsRec(SE, Terms, Sizes))
8916       return false;
8917 
8918   Sizes.push_back(Step);
8919   return true;
8920 }
8921 
8922 // Returns true when S contains at least a SCEVUnknown parameter.
8923 static inline bool
8924 containsParameters(const SCEV *S) {
8925   struct FindParameter {
8926     bool FoundParameter;
8927     FindParameter() : FoundParameter(false) {}
8928 
8929     bool follow(const SCEV *S) {
8930       if (isa<SCEVUnknown>(S)) {
8931         FoundParameter = true;
8932         // Stop recursion: we found a parameter.
8933         return false;
8934       }
8935       // Keep looking.
8936       return true;
8937     }
8938     bool isDone() const {
8939       // Stop recursion if we have found a parameter.
8940       return FoundParameter;
8941     }
8942   };
8943 
8944   FindParameter F;
8945   SCEVTraversal<FindParameter> ST(F);
8946   ST.visitAll(S);
8947 
8948   return F.FoundParameter;
8949 }
8950 
8951 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
8952 static inline bool
8953 containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
8954   for (const SCEV *T : Terms)
8955     if (containsParameters(T))
8956       return true;
8957   return false;
8958 }
8959 
8960 // Return the number of product terms in S.
8961 static inline int numberOfTerms(const SCEV *S) {
8962   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
8963     return Expr->getNumOperands();
8964   return 1;
8965 }
8966 
8967 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
8968   if (isa<SCEVConstant>(T))
8969     return nullptr;
8970 
8971   if (isa<SCEVUnknown>(T))
8972     return T;
8973 
8974   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
8975     SmallVector<const SCEV *, 2> Factors;
8976     for (const SCEV *Op : M->operands())
8977       if (!isa<SCEVConstant>(Op))
8978         Factors.push_back(Op);
8979 
8980     return SE.getMulExpr(Factors);
8981   }
8982 
8983   return T;
8984 }
8985 
8986 /// Return the size of an element read or written by Inst.
8987 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
8988   Type *Ty;
8989   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
8990     Ty = Store->getValueOperand()->getType();
8991   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
8992     Ty = Load->getType();
8993   else
8994     return nullptr;
8995 
8996   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
8997   return getSizeOfExpr(ETy, Ty);
8998 }
8999 
9000 /// Second step of delinearization: compute the array dimensions Sizes from the
9001 /// set of Terms extracted from the memory access function of this SCEVAddRec.
9002 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9003                                           SmallVectorImpl<const SCEV *> &Sizes,
9004                                           const SCEV *ElementSize) const {
9005 
9006   if (Terms.size() < 1 || !ElementSize)
9007     return;
9008 
9009   // Early return when Terms do not contain parameters: we do not delinearize
9010   // non parametric SCEVs.
9011   if (!containsParameters(Terms))
9012     return;
9013 
9014   DEBUG({
9015       dbgs() << "Terms:\n";
9016       for (const SCEV *T : Terms)
9017         dbgs() << *T << "\n";
9018     });
9019 
9020   // Remove duplicates.
9021   std::sort(Terms.begin(), Terms.end());
9022   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9023 
9024   // Put larger terms first.
9025   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9026     return numberOfTerms(LHS) > numberOfTerms(RHS);
9027   });
9028 
9029   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9030 
9031   // Try to divide all terms by the element size. If term is not divisible by
9032   // element size, proceed with the original term.
9033   for (const SCEV *&Term : Terms) {
9034     const SCEV *Q, *R;
9035     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9036     if (!Q->isZero())
9037       Term = Q;
9038   }
9039 
9040   SmallVector<const SCEV *, 4> NewTerms;
9041 
9042   // Remove constant factors.
9043   for (const SCEV *T : Terms)
9044     if (const SCEV *NewT = removeConstantFactors(SE, T))
9045       NewTerms.push_back(NewT);
9046 
9047   DEBUG({
9048       dbgs() << "Terms after sorting:\n";
9049       for (const SCEV *T : NewTerms)
9050         dbgs() << *T << "\n";
9051     });
9052 
9053   if (NewTerms.empty() ||
9054       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9055     Sizes.clear();
9056     return;
9057   }
9058 
9059   // The last element to be pushed into Sizes is the size of an element.
9060   Sizes.push_back(ElementSize);
9061 
9062   DEBUG({
9063       dbgs() << "Sizes:\n";
9064       for (const SCEV *S : Sizes)
9065         dbgs() << *S << "\n";
9066     });
9067 }
9068 
9069 /// Third step of delinearization: compute the access functions for the
9070 /// Subscripts based on the dimensions in Sizes.
9071 void ScalarEvolution::computeAccessFunctions(
9072     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9073     SmallVectorImpl<const SCEV *> &Sizes) {
9074 
9075   // Early exit in case this SCEV is not an affine multivariate function.
9076   if (Sizes.empty())
9077     return;
9078 
9079   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9080     if (!AR->isAffine())
9081       return;
9082 
9083   const SCEV *Res = Expr;
9084   int Last = Sizes.size() - 1;
9085   for (int i = Last; i >= 0; i--) {
9086     const SCEV *Q, *R;
9087     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9088 
9089     DEBUG({
9090         dbgs() << "Res: " << *Res << "\n";
9091         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9092         dbgs() << "Res divided by Sizes[i]:\n";
9093         dbgs() << "Quotient: " << *Q << "\n";
9094         dbgs() << "Remainder: " << *R << "\n";
9095       });
9096 
9097     Res = Q;
9098 
9099     // Do not record the last subscript corresponding to the size of elements in
9100     // the array.
9101     if (i == Last) {
9102 
9103       // Bail out if the remainder is too complex.
9104       if (isa<SCEVAddRecExpr>(R)) {
9105         Subscripts.clear();
9106         Sizes.clear();
9107         return;
9108       }
9109 
9110       continue;
9111     }
9112 
9113     // Record the access function for the current subscript.
9114     Subscripts.push_back(R);
9115   }
9116 
9117   // Also push in last position the remainder of the last division: it will be
9118   // the access function of the innermost dimension.
9119   Subscripts.push_back(Res);
9120 
9121   std::reverse(Subscripts.begin(), Subscripts.end());
9122 
9123   DEBUG({
9124       dbgs() << "Subscripts:\n";
9125       for (const SCEV *S : Subscripts)
9126         dbgs() << *S << "\n";
9127     });
9128 }
9129 
9130 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9131 /// sizes of an array access. Returns the remainder of the delinearization that
9132 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9133 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9134 /// expressions in the stride and base of a SCEV corresponding to the
9135 /// computation of a GCD (greatest common divisor) of base and stride.  When
9136 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9137 ///
9138 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9139 ///
9140 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9141 ///
9142 ///    for (long i = 0; i < n; i++)
9143 ///      for (long j = 0; j < m; j++)
9144 ///        for (long k = 0; k < o; k++)
9145 ///          A[i][j][k] = 1.0;
9146 ///  }
9147 ///
9148 /// the delinearization input is the following AddRec SCEV:
9149 ///
9150 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9151 ///
9152 /// From this SCEV, we are able to say that the base offset of the access is %A
9153 /// because it appears as an offset that does not divide any of the strides in
9154 /// the loops:
9155 ///
9156 ///  CHECK: Base offset: %A
9157 ///
9158 /// and then SCEV->delinearize determines the size of some of the dimensions of
9159 /// the array as these are the multiples by which the strides are happening:
9160 ///
9161 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9162 ///
9163 /// Note that the outermost dimension remains of UnknownSize because there are
9164 /// no strides that would help identifying the size of the last dimension: when
9165 /// the array has been statically allocated, one could compute the size of that
9166 /// dimension by dividing the overall size of the array by the size of the known
9167 /// dimensions: %m * %o * 8.
9168 ///
9169 /// Finally delinearize provides the access functions for the array reference
9170 /// that does correspond to A[i][j][k] of the above C testcase:
9171 ///
9172 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9173 ///
9174 /// The testcases are checking the output of a function pass:
9175 /// DelinearizationPass that walks through all loads and stores of a function
9176 /// asking for the SCEV of the memory access with respect to all enclosing
9177 /// loops, calling SCEV->delinearize on that and printing the results.
9178 
9179 void ScalarEvolution::delinearize(const SCEV *Expr,
9180                                  SmallVectorImpl<const SCEV *> &Subscripts,
9181                                  SmallVectorImpl<const SCEV *> &Sizes,
9182                                  const SCEV *ElementSize) {
9183   // First step: collect parametric terms.
9184   SmallVector<const SCEV *, 4> Terms;
9185   collectParametricTerms(Expr, Terms);
9186 
9187   if (Terms.empty())
9188     return;
9189 
9190   // Second step: find subscript sizes.
9191   findArrayDimensions(Terms, Sizes, ElementSize);
9192 
9193   if (Sizes.empty())
9194     return;
9195 
9196   // Third step: compute the access functions for each subscript.
9197   computeAccessFunctions(Expr, Subscripts, Sizes);
9198 
9199   if (Subscripts.empty())
9200     return;
9201 
9202   DEBUG({
9203       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9204       dbgs() << "ArrayDecl[UnknownSize]";
9205       for (const SCEV *S : Sizes)
9206         dbgs() << "[" << *S << "]";
9207 
9208       dbgs() << "\nArrayRef";
9209       for (const SCEV *S : Subscripts)
9210         dbgs() << "[" << *S << "]";
9211       dbgs() << "\n";
9212     });
9213 }
9214 
9215 //===----------------------------------------------------------------------===//
9216 //                   SCEVCallbackVH Class Implementation
9217 //===----------------------------------------------------------------------===//
9218 
9219 void ScalarEvolution::SCEVCallbackVH::deleted() {
9220   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9221   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9222     SE->ConstantEvolutionLoopExitValue.erase(PN);
9223   SE->eraseValueFromMap(getValPtr());
9224   // this now dangles!
9225 }
9226 
9227 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9228   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9229 
9230   // Forget all the expressions associated with users of the old value,
9231   // so that future queries will recompute the expressions using the new
9232   // value.
9233   Value *Old = getValPtr();
9234   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9235   SmallPtrSet<User *, 8> Visited;
9236   while (!Worklist.empty()) {
9237     User *U = Worklist.pop_back_val();
9238     // Deleting the Old value will cause this to dangle. Postpone
9239     // that until everything else is done.
9240     if (U == Old)
9241       continue;
9242     if (!Visited.insert(U).second)
9243       continue;
9244     if (PHINode *PN = dyn_cast<PHINode>(U))
9245       SE->ConstantEvolutionLoopExitValue.erase(PN);
9246     SE->eraseValueFromMap(U);
9247     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9248   }
9249   // Delete the Old value.
9250   if (PHINode *PN = dyn_cast<PHINode>(Old))
9251     SE->ConstantEvolutionLoopExitValue.erase(PN);
9252   SE->eraseValueFromMap(Old);
9253   // this now dangles!
9254 }
9255 
9256 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9257   : CallbackVH(V), SE(se) {}
9258 
9259 //===----------------------------------------------------------------------===//
9260 //                   ScalarEvolution Class Implementation
9261 //===----------------------------------------------------------------------===//
9262 
9263 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9264                                  AssumptionCache &AC, DominatorTree &DT,
9265                                  LoopInfo &LI)
9266     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9267       CouldNotCompute(new SCEVCouldNotCompute()),
9268       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9269       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9270       FirstUnknown(nullptr) {}
9271 
9272 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9273     : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
9274       CouldNotCompute(std::move(Arg.CouldNotCompute)),
9275       ValueExprMap(std::move(Arg.ValueExprMap)),
9276       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9277       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9278       ConstantEvolutionLoopExitValue(
9279           std::move(Arg.ConstantEvolutionLoopExitValue)),
9280       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9281       LoopDispositions(std::move(Arg.LoopDispositions)),
9282       BlockDispositions(std::move(Arg.BlockDispositions)),
9283       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9284       SignedRanges(std::move(Arg.SignedRanges)),
9285       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9286       UniquePreds(std::move(Arg.UniquePreds)),
9287       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9288       FirstUnknown(Arg.FirstUnknown) {
9289   Arg.FirstUnknown = nullptr;
9290 }
9291 
9292 ScalarEvolution::~ScalarEvolution() {
9293   // Iterate through all the SCEVUnknown instances and call their
9294   // destructors, so that they release their references to their values.
9295   for (SCEVUnknown *U = FirstUnknown; U;) {
9296     SCEVUnknown *Tmp = U;
9297     U = U->Next;
9298     Tmp->~SCEVUnknown();
9299   }
9300   FirstUnknown = nullptr;
9301 
9302   ExprValueMap.clear();
9303   ValueExprMap.clear();
9304   HasRecMap.clear();
9305 
9306   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9307   // that a loop had multiple computable exits.
9308   for (auto &BTCI : BackedgeTakenCounts)
9309     BTCI.second.clear();
9310 
9311   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9312   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9313   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9314 }
9315 
9316 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9317   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9318 }
9319 
9320 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9321                           const Loop *L) {
9322   // Print all inner loops first
9323   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
9324     PrintLoopInfo(OS, SE, *I);
9325 
9326   OS << "Loop ";
9327   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9328   OS << ": ";
9329 
9330   SmallVector<BasicBlock *, 8> ExitBlocks;
9331   L->getExitBlocks(ExitBlocks);
9332   if (ExitBlocks.size() != 1)
9333     OS << "<multiple exits> ";
9334 
9335   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9336     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9337   } else {
9338     OS << "Unpredictable backedge-taken count. ";
9339   }
9340 
9341   OS << "\n"
9342         "Loop ";
9343   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9344   OS << ": ";
9345 
9346   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9347     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9348   } else {
9349     OS << "Unpredictable max backedge-taken count. ";
9350   }
9351 
9352   OS << "\n";
9353 }
9354 
9355 void ScalarEvolution::print(raw_ostream &OS) const {
9356   // ScalarEvolution's implementation of the print method is to print
9357   // out SCEV values of all instructions that are interesting. Doing
9358   // this potentially causes it to create new SCEV objects though,
9359   // which technically conflicts with the const qualifier. This isn't
9360   // observable from outside the class though, so casting away the
9361   // const isn't dangerous.
9362   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9363 
9364   OS << "Classifying expressions for: ";
9365   F.printAsOperand(OS, /*PrintType=*/false);
9366   OS << "\n";
9367   for (Instruction &I : instructions(F))
9368     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9369       OS << I << '\n';
9370       OS << "  -->  ";
9371       const SCEV *SV = SE.getSCEV(&I);
9372       SV->print(OS);
9373       if (!isa<SCEVCouldNotCompute>(SV)) {
9374         OS << " U: ";
9375         SE.getUnsignedRange(SV).print(OS);
9376         OS << " S: ";
9377         SE.getSignedRange(SV).print(OS);
9378       }
9379 
9380       const Loop *L = LI.getLoopFor(I.getParent());
9381 
9382       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9383       if (AtUse != SV) {
9384         OS << "  -->  ";
9385         AtUse->print(OS);
9386         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9387           OS << " U: ";
9388           SE.getUnsignedRange(AtUse).print(OS);
9389           OS << " S: ";
9390           SE.getSignedRange(AtUse).print(OS);
9391         }
9392       }
9393 
9394       if (L) {
9395         OS << "\t\t" "Exits: ";
9396         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9397         if (!SE.isLoopInvariant(ExitValue, L)) {
9398           OS << "<<Unknown>>";
9399         } else {
9400           OS << *ExitValue;
9401         }
9402       }
9403 
9404       OS << "\n";
9405     }
9406 
9407   OS << "Determining loop execution counts for: ";
9408   F.printAsOperand(OS, /*PrintType=*/false);
9409   OS << "\n";
9410   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
9411     PrintLoopInfo(OS, &SE, *I);
9412 }
9413 
9414 ScalarEvolution::LoopDisposition
9415 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9416   auto &Values = LoopDispositions[S];
9417   for (auto &V : Values) {
9418     if (V.getPointer() == L)
9419       return V.getInt();
9420   }
9421   Values.emplace_back(L, LoopVariant);
9422   LoopDisposition D = computeLoopDisposition(S, L);
9423   auto &Values2 = LoopDispositions[S];
9424   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9425     if (V.getPointer() == L) {
9426       V.setInt(D);
9427       break;
9428     }
9429   }
9430   return D;
9431 }
9432 
9433 ScalarEvolution::LoopDisposition
9434 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9435   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9436   case scConstant:
9437     return LoopInvariant;
9438   case scTruncate:
9439   case scZeroExtend:
9440   case scSignExtend:
9441     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9442   case scAddRecExpr: {
9443     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9444 
9445     // If L is the addrec's loop, it's computable.
9446     if (AR->getLoop() == L)
9447       return LoopComputable;
9448 
9449     // Add recurrences are never invariant in the function-body (null loop).
9450     if (!L)
9451       return LoopVariant;
9452 
9453     // This recurrence is variant w.r.t. L if L contains AR's loop.
9454     if (L->contains(AR->getLoop()))
9455       return LoopVariant;
9456 
9457     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9458     if (AR->getLoop()->contains(L))
9459       return LoopInvariant;
9460 
9461     // This recurrence is variant w.r.t. L if any of its operands
9462     // are variant.
9463     for (auto *Op : AR->operands())
9464       if (!isLoopInvariant(Op, L))
9465         return LoopVariant;
9466 
9467     // Otherwise it's loop-invariant.
9468     return LoopInvariant;
9469   }
9470   case scAddExpr:
9471   case scMulExpr:
9472   case scUMaxExpr:
9473   case scSMaxExpr: {
9474     bool HasVarying = false;
9475     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9476       LoopDisposition D = getLoopDisposition(Op, L);
9477       if (D == LoopVariant)
9478         return LoopVariant;
9479       if (D == LoopComputable)
9480         HasVarying = true;
9481     }
9482     return HasVarying ? LoopComputable : LoopInvariant;
9483   }
9484   case scUDivExpr: {
9485     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9486     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9487     if (LD == LoopVariant)
9488       return LoopVariant;
9489     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9490     if (RD == LoopVariant)
9491       return LoopVariant;
9492     return (LD == LoopInvariant && RD == LoopInvariant) ?
9493            LoopInvariant : LoopComputable;
9494   }
9495   case scUnknown:
9496     // All non-instruction values are loop invariant.  All instructions are loop
9497     // invariant if they are not contained in the specified loop.
9498     // Instructions are never considered invariant in the function body
9499     // (null loop) because they are defined within the "loop".
9500     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9501       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9502     return LoopInvariant;
9503   case scCouldNotCompute:
9504     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9505   }
9506   llvm_unreachable("Unknown SCEV kind!");
9507 }
9508 
9509 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9510   return getLoopDisposition(S, L) == LoopInvariant;
9511 }
9512 
9513 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9514   return getLoopDisposition(S, L) == LoopComputable;
9515 }
9516 
9517 ScalarEvolution::BlockDisposition
9518 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9519   auto &Values = BlockDispositions[S];
9520   for (auto &V : Values) {
9521     if (V.getPointer() == BB)
9522       return V.getInt();
9523   }
9524   Values.emplace_back(BB, DoesNotDominateBlock);
9525   BlockDisposition D = computeBlockDisposition(S, BB);
9526   auto &Values2 = BlockDispositions[S];
9527   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9528     if (V.getPointer() == BB) {
9529       V.setInt(D);
9530       break;
9531     }
9532   }
9533   return D;
9534 }
9535 
9536 ScalarEvolution::BlockDisposition
9537 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9538   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9539   case scConstant:
9540     return ProperlyDominatesBlock;
9541   case scTruncate:
9542   case scZeroExtend:
9543   case scSignExtend:
9544     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9545   case scAddRecExpr: {
9546     // This uses a "dominates" query instead of "properly dominates" query
9547     // to test for proper dominance too, because the instruction which
9548     // produces the addrec's value is a PHI, and a PHI effectively properly
9549     // dominates its entire containing block.
9550     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9551     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9552       return DoesNotDominateBlock;
9553   }
9554   // FALL THROUGH into SCEVNAryExpr handling.
9555   case scAddExpr:
9556   case scMulExpr:
9557   case scUMaxExpr:
9558   case scSMaxExpr: {
9559     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9560     bool Proper = true;
9561     for (const SCEV *NAryOp : NAry->operands()) {
9562       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9563       if (D == DoesNotDominateBlock)
9564         return DoesNotDominateBlock;
9565       if (D == DominatesBlock)
9566         Proper = false;
9567     }
9568     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9569   }
9570   case scUDivExpr: {
9571     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9572     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9573     BlockDisposition LD = getBlockDisposition(LHS, BB);
9574     if (LD == DoesNotDominateBlock)
9575       return DoesNotDominateBlock;
9576     BlockDisposition RD = getBlockDisposition(RHS, BB);
9577     if (RD == DoesNotDominateBlock)
9578       return DoesNotDominateBlock;
9579     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9580       ProperlyDominatesBlock : DominatesBlock;
9581   }
9582   case scUnknown:
9583     if (Instruction *I =
9584           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9585       if (I->getParent() == BB)
9586         return DominatesBlock;
9587       if (DT.properlyDominates(I->getParent(), BB))
9588         return ProperlyDominatesBlock;
9589       return DoesNotDominateBlock;
9590     }
9591     return ProperlyDominatesBlock;
9592   case scCouldNotCompute:
9593     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9594   }
9595   llvm_unreachable("Unknown SCEV kind!");
9596 }
9597 
9598 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9599   return getBlockDisposition(S, BB) >= DominatesBlock;
9600 }
9601 
9602 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9603   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9604 }
9605 
9606 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9607   // Search for a SCEV expression node within an expression tree.
9608   // Implements SCEVTraversal::Visitor.
9609   struct SCEVSearch {
9610     const SCEV *Node;
9611     bool IsFound;
9612 
9613     SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9614 
9615     bool follow(const SCEV *S) {
9616       IsFound |= (S == Node);
9617       return !IsFound;
9618     }
9619     bool isDone() const { return IsFound; }
9620   };
9621 
9622   SCEVSearch Search(Op);
9623   visitAll(S, Search);
9624   return Search.IsFound;
9625 }
9626 
9627 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9628   ValuesAtScopes.erase(S);
9629   LoopDispositions.erase(S);
9630   BlockDispositions.erase(S);
9631   UnsignedRanges.erase(S);
9632   SignedRanges.erase(S);
9633   ExprValueMap.erase(S);
9634   HasRecMap.erase(S);
9635 
9636   for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
9637          BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
9638     BackedgeTakenInfo &BEInfo = I->second;
9639     if (BEInfo.hasOperand(S, this)) {
9640       BEInfo.clear();
9641       BackedgeTakenCounts.erase(I++);
9642     }
9643     else
9644       ++I;
9645   }
9646 }
9647 
9648 typedef DenseMap<const Loop *, std::string> VerifyMap;
9649 
9650 /// replaceSubString - Replaces all occurrences of From in Str with To.
9651 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9652   size_t Pos = 0;
9653   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9654     Str.replace(Pos, From.size(), To.data(), To.size());
9655     Pos += To.size();
9656   }
9657 }
9658 
9659 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9660 static void
9661 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9662   std::string &S = Map[L];
9663   if (S.empty()) {
9664     raw_string_ostream OS(S);
9665     SE.getBackedgeTakenCount(L)->print(OS);
9666 
9667     // false and 0 are semantically equivalent. This can happen in dead loops.
9668     replaceSubString(OS.str(), "false", "0");
9669     // Remove wrap flags, their use in SCEV is highly fragile.
9670     // FIXME: Remove this when SCEV gets smarter about them.
9671     replaceSubString(OS.str(), "<nw>", "");
9672     replaceSubString(OS.str(), "<nsw>", "");
9673     replaceSubString(OS.str(), "<nuw>", "");
9674   }
9675 
9676   for (auto *R : reverse(*L))
9677     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
9678 }
9679 
9680 void ScalarEvolution::verify() const {
9681   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9682 
9683   // Gather stringified backedge taken counts for all loops using SCEV's caches.
9684   // FIXME: It would be much better to store actual values instead of strings,
9685   //        but SCEV pointers will change if we drop the caches.
9686   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
9687   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9688     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9689 
9690   // Gather stringified backedge taken counts for all loops using a fresh
9691   // ScalarEvolution object.
9692   ScalarEvolution SE2(F, TLI, AC, DT, LI);
9693   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9694     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
9695 
9696   // Now compare whether they're the same with and without caches. This allows
9697   // verifying that no pass changed the cache.
9698   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9699          "New loops suddenly appeared!");
9700 
9701   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9702                            OldE = BackedgeDumpsOld.end(),
9703                            NewI = BackedgeDumpsNew.begin();
9704        OldI != OldE; ++OldI, ++NewI) {
9705     assert(OldI->first == NewI->first && "Loop order changed!");
9706 
9707     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9708     // changes.
9709     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
9710     // means that a pass is buggy or SCEV has to learn a new pattern but is
9711     // usually not harmful.
9712     if (OldI->second != NewI->second &&
9713         OldI->second.find("undef") == std::string::npos &&
9714         NewI->second.find("undef") == std::string::npos &&
9715         OldI->second != "***COULDNOTCOMPUTE***" &&
9716         NewI->second != "***COULDNOTCOMPUTE***") {
9717       dbgs() << "SCEVValidator: SCEV for loop '"
9718              << OldI->first->getHeader()->getName()
9719              << "' changed from '" << OldI->second
9720              << "' to '" << NewI->second << "'!\n";
9721       std::abort();
9722     }
9723   }
9724 
9725   // TODO: Verify more things.
9726 }
9727 
9728 template class llvm::AnalysisBase<ScalarEvolutionAnalysis>;
9729 
9730 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
9731                                              AnalysisManager<Function> *AM) {
9732   return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F),
9733                          AM->getResult<AssumptionAnalysis>(F),
9734                          AM->getResult<DominatorTreeAnalysis>(F),
9735                          AM->getResult<LoopAnalysis>(F));
9736 }
9737 
9738 PreservedAnalyses
9739 ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) {
9740   AM->getResult<ScalarEvolutionAnalysis>(F).print(OS);
9741   return PreservedAnalyses::all();
9742 }
9743 
9744 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
9745                       "Scalar Evolution Analysis", false, true)
9746 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9747 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
9748 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9749 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
9750 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
9751                     "Scalar Evolution Analysis", false, true)
9752 char ScalarEvolutionWrapperPass::ID = 0;
9753 
9754 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
9755   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
9756 }
9757 
9758 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
9759   SE.reset(new ScalarEvolution(
9760       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
9761       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
9762       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
9763       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
9764   return false;
9765 }
9766 
9767 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
9768 
9769 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
9770   SE->print(OS);
9771 }
9772 
9773 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
9774   if (!VerifySCEV)
9775     return;
9776 
9777   SE->verify();
9778 }
9779 
9780 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
9781   AU.setPreservesAll();
9782   AU.addRequiredTransitive<AssumptionCacheTracker>();
9783   AU.addRequiredTransitive<LoopInfoWrapperPass>();
9784   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
9785   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
9786 }
9787 
9788 const SCEVPredicate *
9789 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
9790                                    const SCEVConstant *RHS) {
9791   FoldingSetNodeID ID;
9792   // Unique this node based on the arguments
9793   ID.AddInteger(SCEVPredicate::P_Equal);
9794   ID.AddPointer(LHS);
9795   ID.AddPointer(RHS);
9796   void *IP = nullptr;
9797   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
9798     return S;
9799   SCEVEqualPredicate *Eq = new (SCEVAllocator)
9800       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
9801   UniquePreds.InsertNode(Eq, IP);
9802   return Eq;
9803 }
9804 
9805 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
9806     const SCEVAddRecExpr *AR,
9807     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
9808   FoldingSetNodeID ID;
9809   // Unique this node based on the arguments
9810   ID.AddInteger(SCEVPredicate::P_Wrap);
9811   ID.AddPointer(AR);
9812   ID.AddInteger(AddedFlags);
9813   void *IP = nullptr;
9814   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
9815     return S;
9816   auto *OF = new (SCEVAllocator)
9817       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
9818   UniquePreds.InsertNode(OF, IP);
9819   return OF;
9820 }
9821 
9822 namespace {
9823 
9824 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
9825 public:
9826   // Rewrites \p S in the context of a loop L and the predicate A.
9827   // If Assume is true, rewrite is free to add further predicates to A
9828   // such that the result will be an AddRecExpr.
9829   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
9830                              SCEVUnionPredicate &A, bool Assume) {
9831     SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
9832     return Rewriter.visit(S);
9833   }
9834 
9835   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
9836                         SCEVUnionPredicate &P, bool Assume)
9837       : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
9838 
9839   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
9840     auto ExprPreds = P.getPredicatesForExpr(Expr);
9841     for (auto *Pred : ExprPreds)
9842       if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred))
9843         if (IPred->getLHS() == Expr)
9844           return IPred->getRHS();
9845 
9846     return Expr;
9847   }
9848 
9849   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
9850     const SCEV *Operand = visit(Expr->getOperand());
9851     const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
9852     if (AR && AR->getLoop() == L && AR->isAffine()) {
9853       // This couldn't be folded because the operand didn't have the nuw
9854       // flag. Add the nusw flag as an assumption that we could make.
9855       const SCEV *Step = AR->getStepRecurrence(SE);
9856       Type *Ty = Expr->getType();
9857       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
9858         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
9859                                 SE.getSignExtendExpr(Step, Ty), L,
9860                                 AR->getNoWrapFlags());
9861     }
9862     return SE.getZeroExtendExpr(Operand, Expr->getType());
9863   }
9864 
9865   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
9866     const SCEV *Operand = visit(Expr->getOperand());
9867     const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
9868     if (AR && AR->getLoop() == L && AR->isAffine()) {
9869       // This couldn't be folded because the operand didn't have the nsw
9870       // flag. Add the nssw flag as an assumption that we could make.
9871       const SCEV *Step = AR->getStepRecurrence(SE);
9872       Type *Ty = Expr->getType();
9873       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
9874         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
9875                                 SE.getSignExtendExpr(Step, Ty), L,
9876                                 AR->getNoWrapFlags());
9877     }
9878     return SE.getSignExtendExpr(Operand, Expr->getType());
9879   }
9880 
9881 private:
9882   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
9883                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
9884     auto *A = SE.getWrapPredicate(AR, AddedFlags);
9885     if (!Assume) {
9886       // Check if we've already made this assumption.
9887       if (P.implies(A))
9888         return true;
9889       return false;
9890     }
9891     P.add(A);
9892     return true;
9893   }
9894 
9895   SCEVUnionPredicate &P;
9896   const Loop *L;
9897   bool Assume;
9898 };
9899 } // end anonymous namespace
9900 
9901 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
9902                                                    SCEVUnionPredicate &Preds) {
9903   return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
9904 }
9905 
9906 const SCEV *
9907 ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
9908                                                    SCEVUnionPredicate &Preds) {
9909   return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, true);
9910 }
9911 
9912 /// SCEV predicates
9913 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
9914                              SCEVPredicateKind Kind)
9915     : FastID(ID), Kind(Kind) {}
9916 
9917 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
9918                                        const SCEVUnknown *LHS,
9919                                        const SCEVConstant *RHS)
9920     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
9921 
9922 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
9923   const auto *Op = dyn_cast<const SCEVEqualPredicate>(N);
9924 
9925   if (!Op)
9926     return false;
9927 
9928   return Op->LHS == LHS && Op->RHS == RHS;
9929 }
9930 
9931 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
9932 
9933 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
9934 
9935 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
9936   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
9937 }
9938 
9939 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
9940                                      const SCEVAddRecExpr *AR,
9941                                      IncrementWrapFlags Flags)
9942     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
9943 
9944 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
9945 
9946 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
9947   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
9948 
9949   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
9950 }
9951 
9952 bool SCEVWrapPredicate::isAlwaysTrue() const {
9953   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
9954   IncrementWrapFlags IFlags = Flags;
9955 
9956   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
9957     IFlags = clearFlags(IFlags, IncrementNSSW);
9958 
9959   return IFlags == IncrementAnyWrap;
9960 }
9961 
9962 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
9963   OS.indent(Depth) << *getExpr() << " Added Flags: ";
9964   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
9965     OS << "<nusw>";
9966   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
9967     OS << "<nssw>";
9968   OS << "\n";
9969 }
9970 
9971 SCEVWrapPredicate::IncrementWrapFlags
9972 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
9973                                    ScalarEvolution &SE) {
9974   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
9975   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
9976 
9977   // We can safely transfer the NSW flag as NSSW.
9978   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
9979     ImpliedFlags = IncrementNSSW;
9980 
9981   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
9982     // If the increment is positive, the SCEV NUW flag will also imply the
9983     // WrapPredicate NUSW flag.
9984     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
9985       if (Step->getValue()->getValue().isNonNegative())
9986         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
9987   }
9988 
9989   return ImpliedFlags;
9990 }
9991 
9992 /// Union predicates don't get cached so create a dummy set ID for it.
9993 SCEVUnionPredicate::SCEVUnionPredicate()
9994     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
9995 
9996 bool SCEVUnionPredicate::isAlwaysTrue() const {
9997   return all_of(Preds,
9998                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
9999 }
10000 
10001 ArrayRef<const SCEVPredicate *>
10002 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10003   auto I = SCEVToPreds.find(Expr);
10004   if (I == SCEVToPreds.end())
10005     return ArrayRef<const SCEVPredicate *>();
10006   return I->second;
10007 }
10008 
10009 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10010   if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N))
10011     return all_of(Set->Preds,
10012                   [this](const SCEVPredicate *I) { return this->implies(I); });
10013 
10014   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10015   if (ScevPredsIt == SCEVToPreds.end())
10016     return false;
10017   auto &SCEVPreds = ScevPredsIt->second;
10018 
10019   return any_of(SCEVPreds,
10020                 [N](const SCEVPredicate *I) { return I->implies(N); });
10021 }
10022 
10023 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10024 
10025 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10026   for (auto Pred : Preds)
10027     Pred->print(OS, Depth);
10028 }
10029 
10030 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10031   if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) {
10032     for (auto Pred : Set->Preds)
10033       add(Pred);
10034     return;
10035   }
10036 
10037   if (implies(N))
10038     return;
10039 
10040   const SCEV *Key = N->getExpr();
10041   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10042                 " associated expression!");
10043 
10044   SCEVToPreds[Key].push_back(N);
10045   Preds.push_back(N);
10046 }
10047 
10048 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10049                                                      Loop &L)
10050     : SE(SE), L(L), Generation(0) {}
10051 
10052 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10053   const SCEV *Expr = SE.getSCEV(V);
10054   RewriteEntry &Entry = RewriteMap[Expr];
10055 
10056   // If we already have an entry and the version matches, return it.
10057   if (Entry.second && Generation == Entry.first)
10058     return Entry.second;
10059 
10060   // We found an entry but it's stale. Rewrite the stale entry
10061   // acording to the current predicate.
10062   if (Entry.second)
10063     Expr = Entry.second;
10064 
10065   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10066   Entry = {Generation, NewSCEV};
10067 
10068   return NewSCEV;
10069 }
10070 
10071 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10072   if (Preds.implies(&Pred))
10073     return;
10074   Preds.add(&Pred);
10075   updateGeneration();
10076 }
10077 
10078 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10079   return Preds;
10080 }
10081 
10082 void PredicatedScalarEvolution::updateGeneration() {
10083   // If the generation number wrapped recompute everything.
10084   if (++Generation == 0) {
10085     for (auto &II : RewriteMap) {
10086       const SCEV *Rewritten = II.second.second;
10087       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10088     }
10089   }
10090 }
10091 
10092 void PredicatedScalarEvolution::setNoOverflow(
10093     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10094   const SCEV *Expr = getSCEV(V);
10095   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10096 
10097   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10098 
10099   // Clear the statically implied flags.
10100   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10101   addPredicate(*SE.getWrapPredicate(AR, Flags));
10102 
10103   auto II = FlagsMap.insert({V, Flags});
10104   if (!II.second)
10105     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10106 }
10107 
10108 bool PredicatedScalarEvolution::hasNoOverflow(
10109     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10110   const SCEV *Expr = getSCEV(V);
10111   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10112 
10113   Flags = SCEVWrapPredicate::clearFlags(
10114       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10115 
10116   auto II = FlagsMap.find(V);
10117 
10118   if (II != FlagsMap.end())
10119     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10120 
10121   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10122 }
10123 
10124 const SCEV *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10125   const SCEV *Expr = this->getSCEV(V);
10126   const SCEV *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
10127   updateGeneration();
10128   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10129   return New;
10130 }
10131 
10132 PredicatedScalarEvolution::
10133 PredicatedScalarEvolution(const PredicatedScalarEvolution &Init) :
10134   RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10135   Generation(Init.Generation) {
10136   for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I)
10137     FlagsMap.insert(*I);
10138 }
10139