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