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