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