Add one more case we compute a max trip count.
[oota-llvm.git] / lib / Analysis / ScalarEvolution.cpp
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
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 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/InstructionSimplify.h"
73 #include "llvm/Analysis/LoopInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/Assembly/Writer.h"
76 #include "llvm/Target/TargetData.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/ConstantRange.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/GetElementPtrTypeIterator.h"
82 #include "llvm/Support/InstIterator.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/ADT/Statistic.h"
86 #include "llvm/ADT/STLExtras.h"
87 #include "llvm/ADT/SmallPtrSet.h"
88 #include <algorithm>
89 using namespace llvm;
90
91 STATISTIC(NumArrayLenItCounts,
92           "Number of trip counts computed with array length");
93 STATISTIC(NumTripCountsComputed,
94           "Number of loops with predictable loop counts");
95 STATISTIC(NumTripCountsNotComputed,
96           "Number of loops without predictable loop counts");
97 STATISTIC(NumBruteForceTripCountsComputed,
98           "Number of loops with trip counts computed by force");
99
100 static cl::opt<unsigned>
101 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
102                         cl::desc("Maximum number of iterations SCEV will "
103                                  "symbolically execute a constant "
104                                  "derived loop"),
105                         cl::init(100));
106
107 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
108                 "Scalar Evolution Analysis", false, true)
109 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
110 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
111 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
112                 "Scalar Evolution Analysis", false, true)
113 char ScalarEvolution::ID = 0;
114
115 //===----------------------------------------------------------------------===//
116 //                           SCEV class definitions
117 //===----------------------------------------------------------------------===//
118
119 //===----------------------------------------------------------------------===//
120 // Implementation of the SCEV class.
121 //
122
123 void SCEV::dump() const {
124   print(dbgs());
125   dbgs() << '\n';
126 }
127
128 void SCEV::print(raw_ostream &OS) const {
129   switch (getSCEVType()) {
130   case scConstant:
131     WriteAsOperand(OS, cast<SCEVConstant>(this)->getValue(), false);
132     return;
133   case scTruncate: {
134     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
135     const SCEV *Op = Trunc->getOperand();
136     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
137        << *Trunc->getType() << ")";
138     return;
139   }
140   case scZeroExtend: {
141     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
142     const SCEV *Op = ZExt->getOperand();
143     OS << "(zext " << *Op->getType() << " " << *Op << " to "
144        << *ZExt->getType() << ")";
145     return;
146   }
147   case scSignExtend: {
148     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
149     const SCEV *Op = SExt->getOperand();
150     OS << "(sext " << *Op->getType() << " " << *Op << " to "
151        << *SExt->getType() << ")";
152     return;
153   }
154   case scAddRecExpr: {
155     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
156     OS << "{" << *AR->getOperand(0);
157     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
158       OS << ",+," << *AR->getOperand(i);
159     OS << "}<";
160     if (AR->getNoWrapFlags(FlagNUW))
161       OS << "nuw><";
162     if (AR->getNoWrapFlags(FlagNSW))
163       OS << "nsw><";
164     if (AR->getNoWrapFlags(FlagNW) &&
165         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
166       OS << "nw><";
167     WriteAsOperand(OS, AR->getLoop()->getHeader(), /*PrintType=*/false);
168     OS << ">";
169     return;
170   }
171   case scAddExpr:
172   case scMulExpr:
173   case scUMaxExpr:
174   case scSMaxExpr: {
175     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
176     const char *OpStr = 0;
177     switch (NAry->getSCEVType()) {
178     case scAddExpr: OpStr = " + "; break;
179     case scMulExpr: OpStr = " * "; break;
180     case scUMaxExpr: OpStr = " umax "; break;
181     case scSMaxExpr: OpStr = " smax "; break;
182     }
183     OS << "(";
184     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
185          I != E; ++I) {
186       OS << **I;
187       if (llvm::next(I) != E)
188         OS << OpStr;
189     }
190     OS << ")";
191     return;
192   }
193   case scUDivExpr: {
194     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
195     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
196     return;
197   }
198   case scUnknown: {
199     const SCEVUnknown *U = cast<SCEVUnknown>(this);
200     Type *AllocTy;
201     if (U->isSizeOf(AllocTy)) {
202       OS << "sizeof(" << *AllocTy << ")";
203       return;
204     }
205     if (U->isAlignOf(AllocTy)) {
206       OS << "alignof(" << *AllocTy << ")";
207       return;
208     }
209
210     Type *CTy;
211     Constant *FieldNo;
212     if (U->isOffsetOf(CTy, FieldNo)) {
213       OS << "offsetof(" << *CTy << ", ";
214       WriteAsOperand(OS, FieldNo, false);
215       OS << ")";
216       return;
217     }
218
219     // Otherwise just print it normally.
220     WriteAsOperand(OS, U->getValue(), false);
221     return;
222   }
223   case scCouldNotCompute:
224     OS << "***COULDNOTCOMPUTE***";
225     return;
226   default: break;
227   }
228   llvm_unreachable("Unknown SCEV kind!");
229 }
230
231 Type *SCEV::getType() const {
232   switch (getSCEVType()) {
233   case scConstant:
234     return cast<SCEVConstant>(this)->getType();
235   case scTruncate:
236   case scZeroExtend:
237   case scSignExtend:
238     return cast<SCEVCastExpr>(this)->getType();
239   case scAddRecExpr:
240   case scMulExpr:
241   case scUMaxExpr:
242   case scSMaxExpr:
243     return cast<SCEVNAryExpr>(this)->getType();
244   case scAddExpr:
245     return cast<SCEVAddExpr>(this)->getType();
246   case scUDivExpr:
247     return cast<SCEVUDivExpr>(this)->getType();
248   case scUnknown:
249     return cast<SCEVUnknown>(this)->getType();
250   case scCouldNotCompute:
251     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
252     return 0;
253   default: break;
254   }
255   llvm_unreachable("Unknown SCEV kind!");
256   return 0;
257 }
258
259 bool SCEV::isZero() const {
260   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
261     return SC->getValue()->isZero();
262   return false;
263 }
264
265 bool SCEV::isOne() const {
266   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
267     return SC->getValue()->isOne();
268   return false;
269 }
270
271 bool SCEV::isAllOnesValue() const {
272   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
273     return SC->getValue()->isAllOnesValue();
274   return false;
275 }
276
277 SCEVCouldNotCompute::SCEVCouldNotCompute() :
278   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
279
280 bool SCEVCouldNotCompute::classof(const SCEV *S) {
281   return S->getSCEVType() == scCouldNotCompute;
282 }
283
284 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
285   FoldingSetNodeID ID;
286   ID.AddInteger(scConstant);
287   ID.AddPointer(V);
288   void *IP = 0;
289   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
290   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
291   UniqueSCEVs.InsertNode(S, IP);
292   return S;
293 }
294
295 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
296   return getConstant(ConstantInt::get(getContext(), Val));
297 }
298
299 const SCEV *
300 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
301   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
302   return getConstant(ConstantInt::get(ITy, V, isSigned));
303 }
304
305 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
306                            unsigned SCEVTy, const SCEV *op, Type *ty)
307   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
308
309 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
310                                    const SCEV *op, Type *ty)
311   : SCEVCastExpr(ID, scTruncate, op, ty) {
312   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
313          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
314          "Cannot truncate non-integer value!");
315 }
316
317 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
318                                        const SCEV *op, Type *ty)
319   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
320   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
321          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
322          "Cannot zero extend non-integer value!");
323 }
324
325 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
326                                        const SCEV *op, Type *ty)
327   : SCEVCastExpr(ID, scSignExtend, op, ty) {
328   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
329          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
330          "Cannot sign extend non-integer value!");
331 }
332
333 void SCEVUnknown::deleted() {
334   // Clear this SCEVUnknown from various maps.
335   SE->forgetMemoizedResults(this);
336
337   // Remove this SCEVUnknown from the uniquing map.
338   SE->UniqueSCEVs.RemoveNode(this);
339
340   // Release the value.
341   setValPtr(0);
342 }
343
344 void SCEVUnknown::allUsesReplacedWith(Value *New) {
345   // Clear this SCEVUnknown from various maps.
346   SE->forgetMemoizedResults(this);
347
348   // Remove this SCEVUnknown from the uniquing map.
349   SE->UniqueSCEVs.RemoveNode(this);
350
351   // Update this SCEVUnknown to point to the new value. This is needed
352   // because there may still be outstanding SCEVs which still point to
353   // this SCEVUnknown.
354   setValPtr(New);
355 }
356
357 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
358   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
359     if (VCE->getOpcode() == Instruction::PtrToInt)
360       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
361         if (CE->getOpcode() == Instruction::GetElementPtr &&
362             CE->getOperand(0)->isNullValue() &&
363             CE->getNumOperands() == 2)
364           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
365             if (CI->isOne()) {
366               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
367                                  ->getElementType();
368               return true;
369             }
370
371   return false;
372 }
373
374 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
375   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
376     if (VCE->getOpcode() == Instruction::PtrToInt)
377       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
378         if (CE->getOpcode() == Instruction::GetElementPtr &&
379             CE->getOperand(0)->isNullValue()) {
380           Type *Ty =
381             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
382           if (StructType *STy = dyn_cast<StructType>(Ty))
383             if (!STy->isPacked() &&
384                 CE->getNumOperands() == 3 &&
385                 CE->getOperand(1)->isNullValue()) {
386               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
387                 if (CI->isOne() &&
388                     STy->getNumElements() == 2 &&
389                     STy->getElementType(0)->isIntegerTy(1)) {
390                   AllocTy = STy->getElementType(1);
391                   return true;
392                 }
393             }
394         }
395
396   return false;
397 }
398
399 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
400   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
401     if (VCE->getOpcode() == Instruction::PtrToInt)
402       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
403         if (CE->getOpcode() == Instruction::GetElementPtr &&
404             CE->getNumOperands() == 3 &&
405             CE->getOperand(0)->isNullValue() &&
406             CE->getOperand(1)->isNullValue()) {
407           Type *Ty =
408             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
409           // Ignore vector types here so that ScalarEvolutionExpander doesn't
410           // emit getelementptrs that index into vectors.
411           if (Ty->isStructTy() || Ty->isArrayTy()) {
412             CTy = Ty;
413             FieldNo = CE->getOperand(2);
414             return true;
415           }
416         }
417
418   return false;
419 }
420
421 //===----------------------------------------------------------------------===//
422 //                               SCEV Utilities
423 //===----------------------------------------------------------------------===//
424
425 namespace {
426   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427   /// than the complexity of the RHS.  This comparator is used to canonicalize
428   /// expressions.
429   class SCEVComplexityCompare {
430     const LoopInfo *const LI;
431   public:
432     explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
433
434     // Return true or false if LHS is less than, or at least RHS, respectively.
435     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
436       return compare(LHS, RHS) < 0;
437     }
438
439     // Return negative, zero, or positive, if LHS is less than, equal to, or
440     // greater than RHS, respectively. A three-way result allows recursive
441     // comparisons to be more efficient.
442     int compare(const SCEV *LHS, const SCEV *RHS) const {
443       // Fast-path: SCEVs are uniqued so we can do a quick equality check.
444       if (LHS == RHS)
445         return 0;
446
447       // Primarily, sort the SCEVs by their getSCEVType().
448       unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
449       if (LType != RType)
450         return (int)LType - (int)RType;
451
452       // Aside from the getSCEVType() ordering, the particular ordering
453       // isn't very important except that it's beneficial to be consistent,
454       // so that (a + b) and (b + a) don't end up as different expressions.
455       switch (LType) {
456       case scUnknown: {
457         const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
458         const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
459
460         // Sort SCEVUnknown values with some loose heuristics. TODO: This is
461         // not as complete as it could be.
462         const Value *LV = LU->getValue(), *RV = RU->getValue();
463
464         // Order pointer values after integer values. This helps SCEVExpander
465         // form GEPs.
466         bool LIsPointer = LV->getType()->isPointerTy(),
467              RIsPointer = RV->getType()->isPointerTy();
468         if (LIsPointer != RIsPointer)
469           return (int)LIsPointer - (int)RIsPointer;
470
471         // Compare getValueID values.
472         unsigned LID = LV->getValueID(),
473                  RID = RV->getValueID();
474         if (LID != RID)
475           return (int)LID - (int)RID;
476
477         // Sort arguments by their position.
478         if (const Argument *LA = dyn_cast<Argument>(LV)) {
479           const Argument *RA = cast<Argument>(RV);
480           unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
481           return (int)LArgNo - (int)RArgNo;
482         }
483
484         // For instructions, compare their loop depth, and their operand
485         // count.  This is pretty loose.
486         if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
487           const Instruction *RInst = cast<Instruction>(RV);
488
489           // Compare loop depths.
490           const BasicBlock *LParent = LInst->getParent(),
491                            *RParent = RInst->getParent();
492           if (LParent != RParent) {
493             unsigned LDepth = LI->getLoopDepth(LParent),
494                      RDepth = LI->getLoopDepth(RParent);
495             if (LDepth != RDepth)
496               return (int)LDepth - (int)RDepth;
497           }
498
499           // Compare the number of operands.
500           unsigned LNumOps = LInst->getNumOperands(),
501                    RNumOps = RInst->getNumOperands();
502           return (int)LNumOps - (int)RNumOps;
503         }
504
505         return 0;
506       }
507
508       case scConstant: {
509         const SCEVConstant *LC = cast<SCEVConstant>(LHS);
510         const SCEVConstant *RC = cast<SCEVConstant>(RHS);
511
512         // Compare constant values.
513         const APInt &LA = LC->getValue()->getValue();
514         const APInt &RA = RC->getValue()->getValue();
515         unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
516         if (LBitWidth != RBitWidth)
517           return (int)LBitWidth - (int)RBitWidth;
518         return LA.ult(RA) ? -1 : 1;
519       }
520
521       case scAddRecExpr: {
522         const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
523         const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
524
525         // Compare addrec loop depths.
526         const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
527         if (LLoop != RLoop) {
528           unsigned LDepth = LLoop->getLoopDepth(),
529                    RDepth = RLoop->getLoopDepth();
530           if (LDepth != RDepth)
531             return (int)LDepth - (int)RDepth;
532         }
533
534         // Addrec complexity grows with operand count.
535         unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
536         if (LNumOps != RNumOps)
537           return (int)LNumOps - (int)RNumOps;
538
539         // Lexicographically compare.
540         for (unsigned i = 0; i != LNumOps; ++i) {
541           long X = compare(LA->getOperand(i), RA->getOperand(i));
542           if (X != 0)
543             return X;
544         }
545
546         return 0;
547       }
548
549       case scAddExpr:
550       case scMulExpr:
551       case scSMaxExpr:
552       case scUMaxExpr: {
553         const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
554         const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
555
556         // Lexicographically compare n-ary expressions.
557         unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
558         for (unsigned i = 0; i != LNumOps; ++i) {
559           if (i >= RNumOps)
560             return 1;
561           long X = compare(LC->getOperand(i), RC->getOperand(i));
562           if (X != 0)
563             return X;
564         }
565         return (int)LNumOps - (int)RNumOps;
566       }
567
568       case scUDivExpr: {
569         const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
570         const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
571
572         // Lexicographically compare udiv expressions.
573         long X = compare(LC->getLHS(), RC->getLHS());
574         if (X != 0)
575           return X;
576         return compare(LC->getRHS(), RC->getRHS());
577       }
578
579       case scTruncate:
580       case scZeroExtend:
581       case scSignExtend: {
582         const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
583         const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
584
585         // Compare cast expressions by operand.
586         return compare(LC->getOperand(), RC->getOperand());
587       }
588
589       default:
590         break;
591       }
592
593       llvm_unreachable("Unknown SCEV kind!");
594       return 0;
595     }
596   };
597 }
598
599 /// GroupByComplexity - Given a list of SCEV objects, order them by their
600 /// complexity, and group objects of the same complexity together by value.
601 /// When this routine is finished, we know that any duplicates in the vector are
602 /// consecutive and that complexity is monotonically increasing.
603 ///
604 /// Note that we go take special precautions to ensure that we get deterministic
605 /// results from this routine.  In other words, we don't want the results of
606 /// this to depend on where the addresses of various SCEV objects happened to
607 /// land in memory.
608 ///
609 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
610                               LoopInfo *LI) {
611   if (Ops.size() < 2) return;  // Noop
612   if (Ops.size() == 2) {
613     // This is the common case, which also happens to be trivially simple.
614     // Special case it.
615     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
616     if (SCEVComplexityCompare(LI)(RHS, LHS))
617       std::swap(LHS, RHS);
618     return;
619   }
620
621   // Do the rough sort by complexity.
622   std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
623
624   // Now that we are sorted by complexity, group elements of the same
625   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
626   // be extremely short in practice.  Note that we take this approach because we
627   // do not want to depend on the addresses of the objects we are grouping.
628   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
629     const SCEV *S = Ops[i];
630     unsigned Complexity = S->getSCEVType();
631
632     // If there are any objects of the same complexity and same value as this
633     // one, group them.
634     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
635       if (Ops[j] == S) { // Found a duplicate.
636         // Move it to immediately after i'th element.
637         std::swap(Ops[i+1], Ops[j]);
638         ++i;   // no need to rescan it.
639         if (i == e-2) return;  // Done!
640       }
641     }
642   }
643 }
644
645
646
647 //===----------------------------------------------------------------------===//
648 //                      Simple SCEV method implementations
649 //===----------------------------------------------------------------------===//
650
651 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
652 /// Assume, K > 0.
653 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
654                                        ScalarEvolution &SE,
655                                        Type *ResultTy) {
656   // Handle the simplest case efficiently.
657   if (K == 1)
658     return SE.getTruncateOrZeroExtend(It, ResultTy);
659
660   // We are using the following formula for BC(It, K):
661   //
662   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
663   //
664   // Suppose, W is the bitwidth of the return value.  We must be prepared for
665   // overflow.  Hence, we must assure that the result of our computation is
666   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
667   // safe in modular arithmetic.
668   //
669   // However, this code doesn't use exactly that formula; the formula it uses
670   // is something like the following, where T is the number of factors of 2 in
671   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
672   // exponentiation:
673   //
674   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
675   //
676   // This formula is trivially equivalent to the previous formula.  However,
677   // this formula can be implemented much more efficiently.  The trick is that
678   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
679   // arithmetic.  To do exact division in modular arithmetic, all we have
680   // to do is multiply by the inverse.  Therefore, this step can be done at
681   // width W.
682   //
683   // The next issue is how to safely do the division by 2^T.  The way this
684   // is done is by doing the multiplication step at a width of at least W + T
685   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
686   // when we perform the division by 2^T (which is equivalent to a right shift
687   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
688   // truncated out after the division by 2^T.
689   //
690   // In comparison to just directly using the first formula, this technique
691   // is much more efficient; using the first formula requires W * K bits,
692   // but this formula less than W + K bits. Also, the first formula requires
693   // a division step, whereas this formula only requires multiplies and shifts.
694   //
695   // It doesn't matter whether the subtraction step is done in the calculation
696   // width or the input iteration count's width; if the subtraction overflows,
697   // the result must be zero anyway.  We prefer here to do it in the width of
698   // the induction variable because it helps a lot for certain cases; CodeGen
699   // isn't smart enough to ignore the overflow, which leads to much less
700   // efficient code if the width of the subtraction is wider than the native
701   // register width.
702   //
703   // (It's possible to not widen at all by pulling out factors of 2 before
704   // the multiplication; for example, K=2 can be calculated as
705   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
706   // extra arithmetic, so it's not an obvious win, and it gets
707   // much more complicated for K > 3.)
708
709   // Protection from insane SCEVs; this bound is conservative,
710   // but it probably doesn't matter.
711   if (K > 1000)
712     return SE.getCouldNotCompute();
713
714   unsigned W = SE.getTypeSizeInBits(ResultTy);
715
716   // Calculate K! / 2^T and T; we divide out the factors of two before
717   // multiplying for calculating K! / 2^T to avoid overflow.
718   // Other overflow doesn't matter because we only care about the bottom
719   // W bits of the result.
720   APInt OddFactorial(W, 1);
721   unsigned T = 1;
722   for (unsigned i = 3; i <= K; ++i) {
723     APInt Mult(W, i);
724     unsigned TwoFactors = Mult.countTrailingZeros();
725     T += TwoFactors;
726     Mult = Mult.lshr(TwoFactors);
727     OddFactorial *= Mult;
728   }
729
730   // We need at least W + T bits for the multiplication step
731   unsigned CalculationBits = W + T;
732
733   // Calculate 2^T, at width T+W.
734   APInt DivFactor = APInt(CalculationBits, 1).shl(T);
735
736   // Calculate the multiplicative inverse of K! / 2^T;
737   // this multiplication factor will perform the exact division by
738   // K! / 2^T.
739   APInt Mod = APInt::getSignedMinValue(W+1);
740   APInt MultiplyFactor = OddFactorial.zext(W+1);
741   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
742   MultiplyFactor = MultiplyFactor.trunc(W);
743
744   // Calculate the product, at width T+W
745   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
746                                                       CalculationBits);
747   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
748   for (unsigned i = 1; i != K; ++i) {
749     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
750     Dividend = SE.getMulExpr(Dividend,
751                              SE.getTruncateOrZeroExtend(S, CalculationTy));
752   }
753
754   // Divide by 2^T
755   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
756
757   // Truncate the result, and divide by K! / 2^T.
758
759   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
760                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
761 }
762
763 /// evaluateAtIteration - Return the value of this chain of recurrences at
764 /// the specified iteration number.  We can evaluate this recurrence by
765 /// multiplying each element in the chain by the binomial coefficient
766 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
767 ///
768 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
769 ///
770 /// where BC(It, k) stands for binomial coefficient.
771 ///
772 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
773                                                 ScalarEvolution &SE) const {
774   const SCEV *Result = getStart();
775   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
776     // The computation is correct in the face of overflow provided that the
777     // multiplication is performed _after_ the evaluation of the binomial
778     // coefficient.
779     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
780     if (isa<SCEVCouldNotCompute>(Coeff))
781       return Coeff;
782
783     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
784   }
785   return Result;
786 }
787
788 //===----------------------------------------------------------------------===//
789 //                    SCEV Expression folder implementations
790 //===----------------------------------------------------------------------===//
791
792 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
793                                              Type *Ty) {
794   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
795          "This is not a truncating conversion!");
796   assert(isSCEVable(Ty) &&
797          "This is not a conversion to a SCEVable type!");
798   Ty = getEffectiveSCEVType(Ty);
799
800   FoldingSetNodeID ID;
801   ID.AddInteger(scTruncate);
802   ID.AddPointer(Op);
803   ID.AddPointer(Ty);
804   void *IP = 0;
805   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
806
807   // Fold if the operand is constant.
808   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
809     return getConstant(
810       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
811                                                getEffectiveSCEVType(Ty))));
812
813   // trunc(trunc(x)) --> trunc(x)
814   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
815     return getTruncateExpr(ST->getOperand(), Ty);
816
817   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
818   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
819     return getTruncateOrSignExtend(SS->getOperand(), Ty);
820
821   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
822   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
823     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
824
825   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
826   // eliminate all the truncates.
827   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
828     SmallVector<const SCEV *, 4> Operands;
829     bool hasTrunc = false;
830     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
831       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
832       hasTrunc = isa<SCEVTruncateExpr>(S);
833       Operands.push_back(S);
834     }
835     if (!hasTrunc)
836       return getAddExpr(Operands);
837     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
838   }
839
840   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
841   // eliminate all the truncates.
842   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
843     SmallVector<const SCEV *, 4> Operands;
844     bool hasTrunc = false;
845     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
846       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
847       hasTrunc = isa<SCEVTruncateExpr>(S);
848       Operands.push_back(S);
849     }
850     if (!hasTrunc)
851       return getMulExpr(Operands);
852     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
853   }
854
855   // If the input value is a chrec scev, truncate the chrec's operands.
856   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
857     SmallVector<const SCEV *, 4> Operands;
858     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
859       Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
860     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
861   }
862
863   // As a special case, fold trunc(undef) to undef. We don't want to
864   // know too much about SCEVUnknowns, but this special case is handy
865   // and harmless.
866   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
867     if (isa<UndefValue>(U->getValue()))
868       return getSCEV(UndefValue::get(Ty));
869
870   // The cast wasn't folded; create an explicit cast node. We can reuse
871   // the existing insert position since if we get here, we won't have
872   // made any changes which would invalidate it.
873   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
874                                                  Op, Ty);
875   UniqueSCEVs.InsertNode(S, IP);
876   return S;
877 }
878
879 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
880                                                Type *Ty) {
881   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
882          "This is not an extending conversion!");
883   assert(isSCEVable(Ty) &&
884          "This is not a conversion to a SCEVable type!");
885   Ty = getEffectiveSCEVType(Ty);
886
887   // Fold if the operand is constant.
888   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
889     return getConstant(
890       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
891                                               getEffectiveSCEVType(Ty))));
892
893   // zext(zext(x)) --> zext(x)
894   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
895     return getZeroExtendExpr(SZ->getOperand(), Ty);
896
897   // Before doing any expensive analysis, check to see if we've already
898   // computed a SCEV for this Op and Ty.
899   FoldingSetNodeID ID;
900   ID.AddInteger(scZeroExtend);
901   ID.AddPointer(Op);
902   ID.AddPointer(Ty);
903   void *IP = 0;
904   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
905
906   // zext(trunc(x)) --> zext(x) or x or trunc(x)
907   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
908     // It's possible the bits taken off by the truncate were all zero bits. If
909     // so, we should be able to simplify this further.
910     const SCEV *X = ST->getOperand();
911     ConstantRange CR = getUnsignedRange(X);
912     unsigned TruncBits = getTypeSizeInBits(ST->getType());
913     unsigned NewBits = getTypeSizeInBits(Ty);
914     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
915             CR.zextOrTrunc(NewBits)))
916       return getTruncateOrZeroExtend(X, Ty);
917   }
918
919   // If the input value is a chrec scev, and we can prove that the value
920   // did not overflow the old, smaller, value, we can zero extend all of the
921   // operands (often constants).  This allows analysis of something like
922   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
923   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
924     if (AR->isAffine()) {
925       const SCEV *Start = AR->getStart();
926       const SCEV *Step = AR->getStepRecurrence(*this);
927       unsigned BitWidth = getTypeSizeInBits(AR->getType());
928       const Loop *L = AR->getLoop();
929
930       // If we have special knowledge that this addrec won't overflow,
931       // we don't need to do any further analysis.
932       if (AR->getNoWrapFlags(SCEV::FlagNUW))
933         return getAddRecExpr(getZeroExtendExpr(Start, Ty),
934                              getZeroExtendExpr(Step, Ty),
935                              L, AR->getNoWrapFlags());
936
937       // Check whether the backedge-taken count is SCEVCouldNotCompute.
938       // Note that this serves two purposes: It filters out loops that are
939       // simply not analyzable, and it covers the case where this code is
940       // being called from within backedge-taken count analysis, such that
941       // attempting to ask for the backedge-taken count would likely result
942       // in infinite recursion. In the later case, the analysis code will
943       // cope with a conservative value, and it will take care to purge
944       // that value once it has finished.
945       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
946       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
947         // Manually compute the final value for AR, checking for
948         // overflow.
949
950         // Check whether the backedge-taken count can be losslessly casted to
951         // the addrec's type. The count is always unsigned.
952         const SCEV *CastedMaxBECount =
953           getTruncateOrZeroExtend(MaxBECount, Start->getType());
954         const SCEV *RecastedMaxBECount =
955           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
956         if (MaxBECount == RecastedMaxBECount) {
957           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
958           // Check whether Start+Step*MaxBECount has no unsigned overflow.
959           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
960           const SCEV *Add = getAddExpr(Start, ZMul);
961           const SCEV *OperandExtendedAdd =
962             getAddExpr(getZeroExtendExpr(Start, WideTy),
963                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
964                                   getZeroExtendExpr(Step, WideTy)));
965           if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
966             // Cache knowledge of AR NUW, which is propagated to this AddRec.
967             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
968             // Return the expression with the addrec on the outside.
969             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
970                                  getZeroExtendExpr(Step, Ty),
971                                  L, AR->getNoWrapFlags());
972           }
973           // Similar to above, only this time treat the step value as signed.
974           // This covers loops that count down.
975           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
976           Add = getAddExpr(Start, SMul);
977           OperandExtendedAdd =
978             getAddExpr(getZeroExtendExpr(Start, WideTy),
979                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
980                                   getSignExtendExpr(Step, WideTy)));
981           if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) {
982             // Cache knowledge of AR NW, which is propagated to this AddRec.
983             // Negative step causes unsigned wrap, but it still can't self-wrap.
984             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
985             // Return the expression with the addrec on the outside.
986             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
987                                  getSignExtendExpr(Step, Ty),
988                                  L, AR->getNoWrapFlags());
989           }
990         }
991
992         // If the backedge is guarded by a comparison with the pre-inc value
993         // the addrec is safe. Also, if the entry is guarded by a comparison
994         // with the start value and the backedge is guarded by a comparison
995         // with the post-inc value, the addrec is safe.
996         if (isKnownPositive(Step)) {
997           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
998                                       getUnsignedRange(Step).getUnsignedMax());
999           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1000               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1001                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1002                                            AR->getPostIncExpr(*this), N))) {
1003             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1004             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1005             // Return the expression with the addrec on the outside.
1006             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1007                                  getZeroExtendExpr(Step, Ty),
1008                                  L, AR->getNoWrapFlags());
1009           }
1010         } else if (isKnownNegative(Step)) {
1011           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1012                                       getSignedRange(Step).getSignedMin());
1013           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1014               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1015                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1016                                            AR->getPostIncExpr(*this), N))) {
1017             // Cache knowledge of AR NW, which is propagated to this AddRec.
1018             // Negative step causes unsigned wrap, but it still can't self-wrap.
1019             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1020             // Return the expression with the addrec on the outside.
1021             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1022                                  getSignExtendExpr(Step, Ty),
1023                                  L, AR->getNoWrapFlags());
1024           }
1025         }
1026       }
1027     }
1028
1029   // The cast wasn't folded; create an explicit cast node.
1030   // Recompute the insert position, as it may have been invalidated.
1031   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1032   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1033                                                    Op, Ty);
1034   UniqueSCEVs.InsertNode(S, IP);
1035   return S;
1036 }
1037
1038 // Get the limit of a recurrence such that incrementing by Step cannot cause
1039 // signed overflow as long as the value of the recurrence within the loop does
1040 // not exceed this limit before incrementing.
1041 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1042                                            ICmpInst::Predicate *Pred,
1043                                            ScalarEvolution *SE) {
1044   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1045   if (SE->isKnownPositive(Step)) {
1046     *Pred = ICmpInst::ICMP_SLT;
1047     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1048                            SE->getSignedRange(Step).getSignedMax());
1049   }
1050   if (SE->isKnownNegative(Step)) {
1051     *Pred = ICmpInst::ICMP_SGT;
1052     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1053                        SE->getSignedRange(Step).getSignedMin());
1054   }
1055   return 0;
1056 }
1057
1058 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
1059 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
1060 // or postincrement sibling. This allows normalizing a sign extended AddRec as
1061 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1062 // result, the expression "Step + sext(PreIncAR)" is congruent with
1063 // "sext(PostIncAR)"
1064 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
1065                                             Type *Ty,
1066                                             ScalarEvolution *SE) {
1067   const Loop *L = AR->getLoop();
1068   const SCEV *Start = AR->getStart();
1069   const SCEV *Step = AR->getStepRecurrence(*SE);
1070
1071   // Check for a simple looking step prior to loop entry.
1072   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1073   if (!SA)
1074     return 0;
1075
1076   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1077   // subtraction is expensive. For this purpose, perform a quick and dirty
1078   // difference, by checking for Step in the operand list.
1079   SmallVector<const SCEV *, 4> DiffOps;
1080   for (SCEVAddExpr::op_iterator I = SA->op_begin(), E = SA->op_end();
1081        I != E; ++I) {
1082     if (*I != Step)
1083       DiffOps.push_back(*I);
1084   }
1085   if (DiffOps.size() == SA->getNumOperands())
1086     return 0;
1087
1088   // This is a postinc AR. Check for overflow on the preinc recurrence using the
1089   // same three conditions that getSignExtendedExpr checks.
1090
1091   // 1. NSW flags on the step increment.
1092   const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
1093   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1094     SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1095
1096   if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
1097     return PreStart;
1098
1099   // 2. Direct overflow check on the step operation's expression.
1100   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1101   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1102   const SCEV *OperandExtendedStart =
1103     SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1104                    SE->getSignExtendExpr(Step, WideTy));
1105   if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1106     // Cache knowledge of PreAR NSW.
1107     if (PreAR)
1108       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1109     // FIXME: this optimization needs a unit test
1110     DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1111     return PreStart;
1112   }
1113
1114   // 3. Loop precondition.
1115   ICmpInst::Predicate Pred;
1116   const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1117
1118   if (OverflowLimit &&
1119       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
1120     return PreStart;
1121   }
1122   return 0;
1123 }
1124
1125 // Get the normalized sign-extended expression for this AddRec's Start.
1126 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
1127                                             Type *Ty,
1128                                             ScalarEvolution *SE) {
1129   const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1130   if (!PreStart)
1131     return SE->getSignExtendExpr(AR->getStart(), Ty);
1132
1133   return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1134                         SE->getSignExtendExpr(PreStart, Ty));
1135 }
1136
1137 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1138                                                Type *Ty) {
1139   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1140          "This is not an extending conversion!");
1141   assert(isSCEVable(Ty) &&
1142          "This is not a conversion to a SCEVable type!");
1143   Ty = getEffectiveSCEVType(Ty);
1144
1145   // Fold if the operand is constant.
1146   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1147     return getConstant(
1148       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1149                                               getEffectiveSCEVType(Ty))));
1150
1151   // sext(sext(x)) --> sext(x)
1152   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1153     return getSignExtendExpr(SS->getOperand(), Ty);
1154
1155   // sext(zext(x)) --> zext(x)
1156   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1157     return getZeroExtendExpr(SZ->getOperand(), Ty);
1158
1159   // Before doing any expensive analysis, check to see if we've already
1160   // computed a SCEV for this Op and Ty.
1161   FoldingSetNodeID ID;
1162   ID.AddInteger(scSignExtend);
1163   ID.AddPointer(Op);
1164   ID.AddPointer(Ty);
1165   void *IP = 0;
1166   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1167
1168   // If the input value is provably positive, build a zext instead.
1169   if (isKnownNonNegative(Op))
1170     return getZeroExtendExpr(Op, Ty);
1171
1172   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1173   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1174     // It's possible the bits taken off by the truncate were all sign bits. If
1175     // so, we should be able to simplify this further.
1176     const SCEV *X = ST->getOperand();
1177     ConstantRange CR = getSignedRange(X);
1178     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1179     unsigned NewBits = getTypeSizeInBits(Ty);
1180     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1181             CR.sextOrTrunc(NewBits)))
1182       return getTruncateOrSignExtend(X, Ty);
1183   }
1184
1185   // If the input value is a chrec scev, and we can prove that the value
1186   // did not overflow the old, smaller, value, we can sign extend all of the
1187   // operands (often constants).  This allows analysis of something like
1188   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1189   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1190     if (AR->isAffine()) {
1191       const SCEV *Start = AR->getStart();
1192       const SCEV *Step = AR->getStepRecurrence(*this);
1193       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1194       const Loop *L = AR->getLoop();
1195
1196       // If we have special knowledge that this addrec won't overflow,
1197       // we don't need to do any further analysis.
1198       if (AR->getNoWrapFlags(SCEV::FlagNSW))
1199         return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1200                              getSignExtendExpr(Step, Ty),
1201                              L, SCEV::FlagNSW);
1202
1203       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1204       // Note that this serves two purposes: It filters out loops that are
1205       // simply not analyzable, and it covers the case where this code is
1206       // being called from within backedge-taken count analysis, such that
1207       // attempting to ask for the backedge-taken count would likely result
1208       // in infinite recursion. In the later case, the analysis code will
1209       // cope with a conservative value, and it will take care to purge
1210       // that value once it has finished.
1211       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1212       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1213         // Manually compute the final value for AR, checking for
1214         // overflow.
1215
1216         // Check whether the backedge-taken count can be losslessly casted to
1217         // the addrec's type. The count is always unsigned.
1218         const SCEV *CastedMaxBECount =
1219           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1220         const SCEV *RecastedMaxBECount =
1221           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1222         if (MaxBECount == RecastedMaxBECount) {
1223           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1224           // Check whether Start+Step*MaxBECount has no signed overflow.
1225           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1226           const SCEV *Add = getAddExpr(Start, SMul);
1227           const SCEV *OperandExtendedAdd =
1228             getAddExpr(getSignExtendExpr(Start, WideTy),
1229                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1230                                   getSignExtendExpr(Step, WideTy)));
1231           if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1232             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1233             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1234             // Return the expression with the addrec on the outside.
1235             return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1236                                  getSignExtendExpr(Step, Ty),
1237                                  L, AR->getNoWrapFlags());
1238           }
1239           // Similar to above, only this time treat the step value as unsigned.
1240           // This covers loops that count up with an unsigned step.
1241           const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1242           Add = getAddExpr(Start, UMul);
1243           OperandExtendedAdd =
1244             getAddExpr(getSignExtendExpr(Start, WideTy),
1245                        getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1246                                   getZeroExtendExpr(Step, WideTy)));
1247           if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) {
1248             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1249             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1250             // Return the expression with the addrec on the outside.
1251             return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1252                                  getZeroExtendExpr(Step, Ty),
1253                                  L, AR->getNoWrapFlags());
1254           }
1255         }
1256
1257         // If the backedge is guarded by a comparison with the pre-inc value
1258         // the addrec is safe. Also, if the entry is guarded by a comparison
1259         // with the start value and the backedge is guarded by a comparison
1260         // with the post-inc value, the addrec is safe.
1261         ICmpInst::Predicate Pred;
1262         const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1263         if (OverflowLimit &&
1264             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1265              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1266               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1267                                           OverflowLimit)))) {
1268           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1269           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1270           return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1271                                getSignExtendExpr(Step, Ty),
1272                                L, AR->getNoWrapFlags());
1273         }
1274       }
1275     }
1276
1277   // The cast wasn't folded; create an explicit cast node.
1278   // Recompute the insert position, as it may have been invalidated.
1279   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1280   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1281                                                    Op, Ty);
1282   UniqueSCEVs.InsertNode(S, IP);
1283   return S;
1284 }
1285
1286 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1287 /// unspecified bits out to the given type.
1288 ///
1289 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1290                                               Type *Ty) {
1291   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1292          "This is not an extending conversion!");
1293   assert(isSCEVable(Ty) &&
1294          "This is not a conversion to a SCEVable type!");
1295   Ty = getEffectiveSCEVType(Ty);
1296
1297   // Sign-extend negative constants.
1298   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1299     if (SC->getValue()->getValue().isNegative())
1300       return getSignExtendExpr(Op, Ty);
1301
1302   // Peel off a truncate cast.
1303   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1304     const SCEV *NewOp = T->getOperand();
1305     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1306       return getAnyExtendExpr(NewOp, Ty);
1307     return getTruncateOrNoop(NewOp, Ty);
1308   }
1309
1310   // Next try a zext cast. If the cast is folded, use it.
1311   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1312   if (!isa<SCEVZeroExtendExpr>(ZExt))
1313     return ZExt;
1314
1315   // Next try a sext cast. If the cast is folded, use it.
1316   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1317   if (!isa<SCEVSignExtendExpr>(SExt))
1318     return SExt;
1319
1320   // Force the cast to be folded into the operands of an addrec.
1321   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1322     SmallVector<const SCEV *, 4> Ops;
1323     for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1324          I != E; ++I)
1325       Ops.push_back(getAnyExtendExpr(*I, Ty));
1326     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1327   }
1328
1329   // As a special case, fold anyext(undef) to undef. We don't want to
1330   // know too much about SCEVUnknowns, but this special case is handy
1331   // and harmless.
1332   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1333     if (isa<UndefValue>(U->getValue()))
1334       return getSCEV(UndefValue::get(Ty));
1335
1336   // If the expression is obviously signed, use the sext cast value.
1337   if (isa<SCEVSMaxExpr>(Op))
1338     return SExt;
1339
1340   // Absent any other information, use the zext cast value.
1341   return ZExt;
1342 }
1343
1344 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1345 /// a list of operands to be added under the given scale, update the given
1346 /// map. This is a helper function for getAddRecExpr. As an example of
1347 /// what it does, given a sequence of operands that would form an add
1348 /// expression like this:
1349 ///
1350 ///    m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1351 ///
1352 /// where A and B are constants, update the map with these values:
1353 ///
1354 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1355 ///
1356 /// and add 13 + A*B*29 to AccumulatedConstant.
1357 /// This will allow getAddRecExpr to produce this:
1358 ///
1359 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1360 ///
1361 /// This form often exposes folding opportunities that are hidden in
1362 /// the original operand list.
1363 ///
1364 /// Return true iff it appears that any interesting folding opportunities
1365 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1366 /// the common case where no interesting opportunities are present, and
1367 /// is also used as a check to avoid infinite recursion.
1368 ///
1369 static bool
1370 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1371                              SmallVector<const SCEV *, 8> &NewOps,
1372                              APInt &AccumulatedConstant,
1373                              const SCEV *const *Ops, size_t NumOperands,
1374                              const APInt &Scale,
1375                              ScalarEvolution &SE) {
1376   bool Interesting = false;
1377
1378   // Iterate over the add operands. They are sorted, with constants first.
1379   unsigned i = 0;
1380   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1381     ++i;
1382     // Pull a buried constant out to the outside.
1383     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1384       Interesting = true;
1385     AccumulatedConstant += Scale * C->getValue()->getValue();
1386   }
1387
1388   // Next comes everything else. We're especially interested in multiplies
1389   // here, but they're in the middle, so just visit the rest with one loop.
1390   for (; i != NumOperands; ++i) {
1391     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1392     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1393       APInt NewScale =
1394         Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1395       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1396         // A multiplication of a constant with another add; recurse.
1397         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1398         Interesting |=
1399           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1400                                        Add->op_begin(), Add->getNumOperands(),
1401                                        NewScale, SE);
1402       } else {
1403         // A multiplication of a constant with some other value. Update
1404         // the map.
1405         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1406         const SCEV *Key = SE.getMulExpr(MulOps);
1407         std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1408           M.insert(std::make_pair(Key, NewScale));
1409         if (Pair.second) {
1410           NewOps.push_back(Pair.first->first);
1411         } else {
1412           Pair.first->second += NewScale;
1413           // The map already had an entry for this value, which may indicate
1414           // a folding opportunity.
1415           Interesting = true;
1416         }
1417       }
1418     } else {
1419       // An ordinary operand. Update the map.
1420       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1421         M.insert(std::make_pair(Ops[i], Scale));
1422       if (Pair.second) {
1423         NewOps.push_back(Pair.first->first);
1424       } else {
1425         Pair.first->second += Scale;
1426         // The map already had an entry for this value, which may indicate
1427         // a folding opportunity.
1428         Interesting = true;
1429       }
1430     }
1431   }
1432
1433   return Interesting;
1434 }
1435
1436 namespace {
1437   struct APIntCompare {
1438     bool operator()(const APInt &LHS, const APInt &RHS) const {
1439       return LHS.ult(RHS);
1440     }
1441   };
1442 }
1443
1444 /// getAddExpr - Get a canonical add expression, or something simpler if
1445 /// possible.
1446 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1447                                         SCEV::NoWrapFlags Flags) {
1448   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1449          "only nuw or nsw allowed");
1450   assert(!Ops.empty() && "Cannot get empty add!");
1451   if (Ops.size() == 1) return Ops[0];
1452 #ifndef NDEBUG
1453   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1454   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1455     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1456            "SCEVAddExpr operand types don't match!");
1457 #endif
1458
1459   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1460   // And vice-versa.
1461   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1462   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1463   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1464     bool All = true;
1465     for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1466          E = Ops.end(); I != E; ++I)
1467       if (!isKnownNonNegative(*I)) {
1468         All = false;
1469         break;
1470       }
1471     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1472   }
1473
1474   // Sort by complexity, this groups all similar expression types together.
1475   GroupByComplexity(Ops, LI);
1476
1477   // If there are any constants, fold them together.
1478   unsigned Idx = 0;
1479   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1480     ++Idx;
1481     assert(Idx < Ops.size());
1482     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1483       // We found two constants, fold them together!
1484       Ops[0] = getConstant(LHSC->getValue()->getValue() +
1485                            RHSC->getValue()->getValue());
1486       if (Ops.size() == 2) return Ops[0];
1487       Ops.erase(Ops.begin()+1);  // Erase the folded element
1488       LHSC = cast<SCEVConstant>(Ops[0]);
1489     }
1490
1491     // If we are left with a constant zero being added, strip it off.
1492     if (LHSC->getValue()->isZero()) {
1493       Ops.erase(Ops.begin());
1494       --Idx;
1495     }
1496
1497     if (Ops.size() == 1) return Ops[0];
1498   }
1499
1500   // Okay, check to see if the same value occurs in the operand list more than
1501   // once.  If so, merge them together into an multiply expression.  Since we
1502   // sorted the list, these values are required to be adjacent.
1503   Type *Ty = Ops[0]->getType();
1504   bool FoundMatch = false;
1505   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
1506     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
1507       // Scan ahead to count how many equal operands there are.
1508       unsigned Count = 2;
1509       while (i+Count != e && Ops[i+Count] == Ops[i])
1510         ++Count;
1511       // Merge the values into a multiply.
1512       const SCEV *Scale = getConstant(Ty, Count);
1513       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1514       if (Ops.size() == Count)
1515         return Mul;
1516       Ops[i] = Mul;
1517       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
1518       --i; e -= Count - 1;
1519       FoundMatch = true;
1520     }
1521   if (FoundMatch)
1522     return getAddExpr(Ops, Flags);
1523
1524   // Check for truncates. If all the operands are truncated from the same
1525   // type, see if factoring out the truncate would permit the result to be
1526   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1527   // if the contents of the resulting outer trunc fold to something simple.
1528   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1529     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1530     Type *DstType = Trunc->getType();
1531     Type *SrcType = Trunc->getOperand()->getType();
1532     SmallVector<const SCEV *, 8> LargeOps;
1533     bool Ok = true;
1534     // Check all the operands to see if they can be represented in the
1535     // source type of the truncate.
1536     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1537       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1538         if (T->getOperand()->getType() != SrcType) {
1539           Ok = false;
1540           break;
1541         }
1542         LargeOps.push_back(T->getOperand());
1543       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1544         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1545       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1546         SmallVector<const SCEV *, 8> LargeMulOps;
1547         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1548           if (const SCEVTruncateExpr *T =
1549                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1550             if (T->getOperand()->getType() != SrcType) {
1551               Ok = false;
1552               break;
1553             }
1554             LargeMulOps.push_back(T->getOperand());
1555           } else if (const SCEVConstant *C =
1556                        dyn_cast<SCEVConstant>(M->getOperand(j))) {
1557             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1558           } else {
1559             Ok = false;
1560             break;
1561           }
1562         }
1563         if (Ok)
1564           LargeOps.push_back(getMulExpr(LargeMulOps));
1565       } else {
1566         Ok = false;
1567         break;
1568       }
1569     }
1570     if (Ok) {
1571       // Evaluate the expression in the larger type.
1572       const SCEV *Fold = getAddExpr(LargeOps, Flags);
1573       // If it folds to something simple, use it. Otherwise, don't.
1574       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1575         return getTruncateExpr(Fold, DstType);
1576     }
1577   }
1578
1579   // Skip past any other cast SCEVs.
1580   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1581     ++Idx;
1582
1583   // If there are add operands they would be next.
1584   if (Idx < Ops.size()) {
1585     bool DeletedAdd = false;
1586     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1587       // If we have an add, expand the add operands onto the end of the operands
1588       // list.
1589       Ops.erase(Ops.begin()+Idx);
1590       Ops.append(Add->op_begin(), Add->op_end());
1591       DeletedAdd = true;
1592     }
1593
1594     // If we deleted at least one add, we added operands to the end of the list,
1595     // and they are not necessarily sorted.  Recurse to resort and resimplify
1596     // any operands we just acquired.
1597     if (DeletedAdd)
1598       return getAddExpr(Ops);
1599   }
1600
1601   // Skip over the add expression until we get to a multiply.
1602   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1603     ++Idx;
1604
1605   // Check to see if there are any folding opportunities present with
1606   // operands multiplied by constant values.
1607   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1608     uint64_t BitWidth = getTypeSizeInBits(Ty);
1609     DenseMap<const SCEV *, APInt> M;
1610     SmallVector<const SCEV *, 8> NewOps;
1611     APInt AccumulatedConstant(BitWidth, 0);
1612     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1613                                      Ops.data(), Ops.size(),
1614                                      APInt(BitWidth, 1), *this)) {
1615       // Some interesting folding opportunity is present, so its worthwhile to
1616       // re-generate the operands list. Group the operands by constant scale,
1617       // to avoid multiplying by the same constant scale multiple times.
1618       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1619       for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
1620            E = NewOps.end(); I != E; ++I)
1621         MulOpLists[M.find(*I)->second].push_back(*I);
1622       // Re-generate the operands list.
1623       Ops.clear();
1624       if (AccumulatedConstant != 0)
1625         Ops.push_back(getConstant(AccumulatedConstant));
1626       for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1627            I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1628         if (I->first != 0)
1629           Ops.push_back(getMulExpr(getConstant(I->first),
1630                                    getAddExpr(I->second)));
1631       if (Ops.empty())
1632         return getConstant(Ty, 0);
1633       if (Ops.size() == 1)
1634         return Ops[0];
1635       return getAddExpr(Ops);
1636     }
1637   }
1638
1639   // If we are adding something to a multiply expression, make sure the
1640   // something is not already an operand of the multiply.  If so, merge it into
1641   // the multiply.
1642   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1643     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1644     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1645       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1646       if (isa<SCEVConstant>(MulOpSCEV))
1647         continue;
1648       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1649         if (MulOpSCEV == Ops[AddOp]) {
1650           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
1651           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1652           if (Mul->getNumOperands() != 2) {
1653             // If the multiply has more than two operands, we must get the
1654             // Y*Z term.
1655             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1656                                                 Mul->op_begin()+MulOp);
1657             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1658             InnerMul = getMulExpr(MulOps);
1659           }
1660           const SCEV *One = getConstant(Ty, 1);
1661           const SCEV *AddOne = getAddExpr(One, InnerMul);
1662           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
1663           if (Ops.size() == 2) return OuterMul;
1664           if (AddOp < Idx) {
1665             Ops.erase(Ops.begin()+AddOp);
1666             Ops.erase(Ops.begin()+Idx-1);
1667           } else {
1668             Ops.erase(Ops.begin()+Idx);
1669             Ops.erase(Ops.begin()+AddOp-1);
1670           }
1671           Ops.push_back(OuterMul);
1672           return getAddExpr(Ops);
1673         }
1674
1675       // Check this multiply against other multiplies being added together.
1676       for (unsigned OtherMulIdx = Idx+1;
1677            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1678            ++OtherMulIdx) {
1679         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1680         // If MulOp occurs in OtherMul, we can fold the two multiplies
1681         // together.
1682         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1683              OMulOp != e; ++OMulOp)
1684           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1685             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1686             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1687             if (Mul->getNumOperands() != 2) {
1688               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1689                                                   Mul->op_begin()+MulOp);
1690               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
1691               InnerMul1 = getMulExpr(MulOps);
1692             }
1693             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1694             if (OtherMul->getNumOperands() != 2) {
1695               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1696                                                   OtherMul->op_begin()+OMulOp);
1697               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
1698               InnerMul2 = getMulExpr(MulOps);
1699             }
1700             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1701             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1702             if (Ops.size() == 2) return OuterMul;
1703             Ops.erase(Ops.begin()+Idx);
1704             Ops.erase(Ops.begin()+OtherMulIdx-1);
1705             Ops.push_back(OuterMul);
1706             return getAddExpr(Ops);
1707           }
1708       }
1709     }
1710   }
1711
1712   // If there are any add recurrences in the operands list, see if any other
1713   // added values are loop invariant.  If so, we can fold them into the
1714   // recurrence.
1715   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1716     ++Idx;
1717
1718   // Scan over all recurrences, trying to fold loop invariants into them.
1719   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1720     // Scan all of the other operands to this add and add them to the vector if
1721     // they are loop invariant w.r.t. the recurrence.
1722     SmallVector<const SCEV *, 8> LIOps;
1723     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1724     const Loop *AddRecLoop = AddRec->getLoop();
1725     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1726       if (isLoopInvariant(Ops[i], AddRecLoop)) {
1727         LIOps.push_back(Ops[i]);
1728         Ops.erase(Ops.begin()+i);
1729         --i; --e;
1730       }
1731
1732     // If we found some loop invariants, fold them into the recurrence.
1733     if (!LIOps.empty()) {
1734       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
1735       LIOps.push_back(AddRec->getStart());
1736
1737       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1738                                              AddRec->op_end());
1739       AddRecOps[0] = getAddExpr(LIOps);
1740
1741       // Build the new addrec. Propagate the NUW and NSW flags if both the
1742       // outer add and the inner addrec are guaranteed to have no overflow.
1743       // Always propagate NW.
1744       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
1745       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
1746
1747       // If all of the other operands were loop invariant, we are done.
1748       if (Ops.size() == 1) return NewRec;
1749
1750       // Otherwise, add the folded AddRec by the non-invariant parts.
1751       for (unsigned i = 0;; ++i)
1752         if (Ops[i] == AddRec) {
1753           Ops[i] = NewRec;
1754           break;
1755         }
1756       return getAddExpr(Ops);
1757     }
1758
1759     // Okay, if there weren't any loop invariants to be folded, check to see if
1760     // there are multiple AddRec's with the same loop induction variable being
1761     // added together.  If so, we can fold them.
1762     for (unsigned OtherIdx = Idx+1;
1763          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1764          ++OtherIdx)
1765       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1766         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
1767         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1768                                                AddRec->op_end());
1769         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1770              ++OtherIdx)
1771           if (const SCEVAddRecExpr *OtherAddRec =
1772                 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1773             if (OtherAddRec->getLoop() == AddRecLoop) {
1774               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1775                    i != e; ++i) {
1776                 if (i >= AddRecOps.size()) {
1777                   AddRecOps.append(OtherAddRec->op_begin()+i,
1778                                    OtherAddRec->op_end());
1779                   break;
1780                 }
1781                 AddRecOps[i] = getAddExpr(AddRecOps[i],
1782                                           OtherAddRec->getOperand(i));
1783               }
1784               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1785             }
1786         // Step size has changed, so we cannot guarantee no self-wraparound.
1787         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
1788         return getAddExpr(Ops);
1789       }
1790
1791     // Otherwise couldn't fold anything into this recurrence.  Move onto the
1792     // next one.
1793   }
1794
1795   // Okay, it looks like we really DO need an add expr.  Check to see if we
1796   // already have one, otherwise create a new one.
1797   FoldingSetNodeID ID;
1798   ID.AddInteger(scAddExpr);
1799   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1800     ID.AddPointer(Ops[i]);
1801   void *IP = 0;
1802   SCEVAddExpr *S =
1803     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1804   if (!S) {
1805     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1806     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1807     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1808                                         O, Ops.size());
1809     UniqueSCEVs.InsertNode(S, IP);
1810   }
1811   S->setNoWrapFlags(Flags);
1812   return S;
1813 }
1814
1815 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1816 /// possible.
1817 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1818                                         SCEV::NoWrapFlags Flags) {
1819   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
1820          "only nuw or nsw allowed");
1821   assert(!Ops.empty() && "Cannot get empty mul!");
1822   if (Ops.size() == 1) return Ops[0];
1823 #ifndef NDEBUG
1824   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1825   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1826     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1827            "SCEVMulExpr operand types don't match!");
1828 #endif
1829
1830   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
1831   // And vice-versa.
1832   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1833   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1834   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
1835     bool All = true;
1836     for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1837          E = Ops.end(); I != E; ++I)
1838       if (!isKnownNonNegative(*I)) {
1839         All = false;
1840         break;
1841       }
1842     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
1843   }
1844
1845   // Sort by complexity, this groups all similar expression types together.
1846   GroupByComplexity(Ops, LI);
1847
1848   // If there are any constants, fold them together.
1849   unsigned Idx = 0;
1850   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1851
1852     // C1*(C2+V) -> C1*C2 + C1*V
1853     if (Ops.size() == 2)
1854       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1855         if (Add->getNumOperands() == 2 &&
1856             isa<SCEVConstant>(Add->getOperand(0)))
1857           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1858                             getMulExpr(LHSC, Add->getOperand(1)));
1859
1860     ++Idx;
1861     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1862       // We found two constants, fold them together!
1863       ConstantInt *Fold = ConstantInt::get(getContext(),
1864                                            LHSC->getValue()->getValue() *
1865                                            RHSC->getValue()->getValue());
1866       Ops[0] = getConstant(Fold);
1867       Ops.erase(Ops.begin()+1);  // Erase the folded element
1868       if (Ops.size() == 1) return Ops[0];
1869       LHSC = cast<SCEVConstant>(Ops[0]);
1870     }
1871
1872     // If we are left with a constant one being multiplied, strip it off.
1873     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1874       Ops.erase(Ops.begin());
1875       --Idx;
1876     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1877       // If we have a multiply of zero, it will always be zero.
1878       return Ops[0];
1879     } else if (Ops[0]->isAllOnesValue()) {
1880       // If we have a mul by -1 of an add, try distributing the -1 among the
1881       // add operands.
1882       if (Ops.size() == 2) {
1883         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1884           SmallVector<const SCEV *, 4> NewOps;
1885           bool AnyFolded = false;
1886           for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
1887                  E = Add->op_end(); I != E; ++I) {
1888             const SCEV *Mul = getMulExpr(Ops[0], *I);
1889             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1890             NewOps.push_back(Mul);
1891           }
1892           if (AnyFolded)
1893             return getAddExpr(NewOps);
1894         }
1895         else if (const SCEVAddRecExpr *
1896                  AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
1897           // Negation preserves a recurrence's no self-wrap property.
1898           SmallVector<const SCEV *, 4> Operands;
1899           for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
1900                  E = AddRec->op_end(); I != E; ++I) {
1901             Operands.push_back(getMulExpr(Ops[0], *I));
1902           }
1903           return getAddRecExpr(Operands, AddRec->getLoop(),
1904                                AddRec->getNoWrapFlags(SCEV::FlagNW));
1905         }
1906       }
1907     }
1908
1909     if (Ops.size() == 1)
1910       return Ops[0];
1911   }
1912
1913   // Skip over the add expression until we get to a multiply.
1914   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1915     ++Idx;
1916
1917   // If there are mul operands inline them all into this expression.
1918   if (Idx < Ops.size()) {
1919     bool DeletedMul = false;
1920     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1921       // If we have an mul, expand the mul operands onto the end of the operands
1922       // list.
1923       Ops.erase(Ops.begin()+Idx);
1924       Ops.append(Mul->op_begin(), Mul->op_end());
1925       DeletedMul = true;
1926     }
1927
1928     // If we deleted at least one mul, we added operands to the end of the list,
1929     // and they are not necessarily sorted.  Recurse to resort and resimplify
1930     // any operands we just acquired.
1931     if (DeletedMul)
1932       return getMulExpr(Ops);
1933   }
1934
1935   // If there are any add recurrences in the operands list, see if any other
1936   // added values are loop invariant.  If so, we can fold them into the
1937   // recurrence.
1938   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1939     ++Idx;
1940
1941   // Scan over all recurrences, trying to fold loop invariants into them.
1942   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1943     // Scan all of the other operands to this mul and add them to the vector if
1944     // they are loop invariant w.r.t. the recurrence.
1945     SmallVector<const SCEV *, 8> LIOps;
1946     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1947     const Loop *AddRecLoop = AddRec->getLoop();
1948     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1949       if (isLoopInvariant(Ops[i], AddRecLoop)) {
1950         LIOps.push_back(Ops[i]);
1951         Ops.erase(Ops.begin()+i);
1952         --i; --e;
1953       }
1954
1955     // If we found some loop invariants, fold them into the recurrence.
1956     if (!LIOps.empty()) {
1957       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
1958       SmallVector<const SCEV *, 4> NewOps;
1959       NewOps.reserve(AddRec->getNumOperands());
1960       const SCEV *Scale = getMulExpr(LIOps);
1961       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1962         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1963
1964       // Build the new addrec. Propagate the NUW and NSW flags if both the
1965       // outer mul and the inner addrec are guaranteed to have no overflow.
1966       //
1967       // No self-wrap cannot be guaranteed after changing the step size, but
1968       // will be inferred if either NUW or NSW is true.
1969       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
1970       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
1971
1972       // If all of the other operands were loop invariant, we are done.
1973       if (Ops.size() == 1) return NewRec;
1974
1975       // Otherwise, multiply the folded AddRec by the non-invariant parts.
1976       for (unsigned i = 0;; ++i)
1977         if (Ops[i] == AddRec) {
1978           Ops[i] = NewRec;
1979           break;
1980         }
1981       return getMulExpr(Ops);
1982     }
1983
1984     // Okay, if there weren't any loop invariants to be folded, check to see if
1985     // there are multiple AddRec's with the same loop induction variable being
1986     // multiplied together.  If so, we can fold them.
1987     for (unsigned OtherIdx = Idx+1;
1988          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1989          ++OtherIdx) {
1990       bool Retry = false;
1991       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1992         // {A,+,B}<L> * {C,+,D}<L>  -->  {A*C,+,A*D + B*C + B*D,+,2*B*D}<L>
1993         //
1994         // {A,+,B} * {C,+,D} = A+It*B * C+It*D = A*C + (A*D + B*C)*It + B*D*It^2
1995         // Given an equation of the form x + y*It + z*It^2 (above), we want to
1996         // express it in terms of {X,+,Y,+,Z}.
1997         // {X,+,Y,+,Z} = X + Y*It + Z*(It^2 - It)/2.
1998         // Rearranging, X = x, Y = y+z, Z = 2z.
1999         //
2000         // x = A*C, y = (A*D + B*C), z = B*D.
2001         // Therefore X = A*C, Y = A*D + B*C + B*D and Z = 2*B*D.
2002         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2003              ++OtherIdx)
2004           if (const SCEVAddRecExpr *OtherAddRec =
2005                 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2006             if (OtherAddRec->getLoop() == AddRecLoop) {
2007               const SCEV *A = AddRec->getStart();
2008               const SCEV *B = AddRec->getStepRecurrence(*this);
2009               const SCEV *C = OtherAddRec->getStart();
2010               const SCEV *D = OtherAddRec->getStepRecurrence(*this);
2011               const SCEV *NewStart = getMulExpr(A, C);
2012               const SCEV *BD = getMulExpr(B, D);
2013               const SCEV *NewStep = getAddExpr(getMulExpr(A, D),
2014                                                getMulExpr(B, C), BD);
2015               const SCEV *NewSecondOrderStep =
2016                   getMulExpr(BD, getConstant(BD->getType(), 2));
2017
2018               // This can happen when AddRec or OtherAddRec have >3 operands.
2019               // TODO: support these add-recs.
2020               if (isLoopInvariant(NewStart, AddRecLoop) &&
2021                   isLoopInvariant(NewStep, AddRecLoop) &&
2022                   isLoopInvariant(NewSecondOrderStep, AddRecLoop)) {
2023                 SmallVector<const SCEV *, 3> AddRecOps;
2024                 AddRecOps.push_back(NewStart);
2025                 AddRecOps.push_back(NewStep);
2026                 AddRecOps.push_back(NewSecondOrderStep);
2027                 const SCEV *NewAddRec = getAddRecExpr(AddRecOps,
2028                                                       AddRec->getLoop(),
2029                                                       SCEV::FlagAnyWrap);
2030                 if (Ops.size() == 2) return NewAddRec;
2031                 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
2032                 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2033                 Retry = true;
2034               }
2035             }
2036         if (Retry)
2037           return getMulExpr(Ops);
2038       }
2039     }
2040
2041     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2042     // next one.
2043   }
2044
2045   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2046   // already have one, otherwise create a new one.
2047   FoldingSetNodeID ID;
2048   ID.AddInteger(scMulExpr);
2049   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2050     ID.AddPointer(Ops[i]);
2051   void *IP = 0;
2052   SCEVMulExpr *S =
2053     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2054   if (!S) {
2055     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2056     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2057     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2058                                         O, Ops.size());
2059     UniqueSCEVs.InsertNode(S, IP);
2060   }
2061   S->setNoWrapFlags(Flags);
2062   return S;
2063 }
2064
2065 /// getUDivExpr - Get a canonical unsigned division expression, or something
2066 /// simpler if possible.
2067 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2068                                          const SCEV *RHS) {
2069   assert(getEffectiveSCEVType(LHS->getType()) ==
2070          getEffectiveSCEVType(RHS->getType()) &&
2071          "SCEVUDivExpr operand types don't match!");
2072
2073   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2074     if (RHSC->getValue()->equalsInt(1))
2075       return LHS;                               // X udiv 1 --> x
2076     // If the denominator is zero, the result of the udiv is undefined. Don't
2077     // try to analyze it, because the resolution chosen here may differ from
2078     // the resolution chosen in other parts of the compiler.
2079     if (!RHSC->getValue()->isZero()) {
2080       // Determine if the division can be folded into the operands of
2081       // its operands.
2082       // TODO: Generalize this to non-constants by using known-bits information.
2083       Type *Ty = LHS->getType();
2084       unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
2085       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2086       // For non-power-of-two values, effectively round the value up to the
2087       // nearest power of two.
2088       if (!RHSC->getValue()->getValue().isPowerOf2())
2089         ++MaxShiftAmt;
2090       IntegerType *ExtTy =
2091         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2092       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2093         if (const SCEVConstant *Step =
2094             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2095           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2096           const APInt &StepInt = Step->getValue()->getValue();
2097           const APInt &DivInt = RHSC->getValue()->getValue();
2098           if (!StepInt.urem(DivInt) &&
2099               getZeroExtendExpr(AR, ExtTy) ==
2100               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2101                             getZeroExtendExpr(Step, ExtTy),
2102                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2103             SmallVector<const SCEV *, 4> Operands;
2104             for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2105               Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
2106             return getAddRecExpr(Operands, AR->getLoop(),
2107                                  SCEV::FlagNW);
2108           }
2109           /// Get a canonical UDivExpr for a recurrence.
2110           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2111           // We can currently only fold X%N if X is constant.
2112           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2113           if (StartC && !DivInt.urem(StepInt) &&
2114               getZeroExtendExpr(AR, ExtTy) ==
2115               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2116                             getZeroExtendExpr(Step, ExtTy),
2117                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2118             const APInt &StartInt = StartC->getValue()->getValue();
2119             const APInt &StartRem = StartInt.urem(StepInt);
2120             if (StartRem != 0)
2121               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2122                                   AR->getLoop(), SCEV::FlagNW);
2123           }
2124         }
2125       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2126       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2127         SmallVector<const SCEV *, 4> Operands;
2128         for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2129           Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2130         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2131           // Find an operand that's safely divisible.
2132           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2133             const SCEV *Op = M->getOperand(i);
2134             const SCEV *Div = getUDivExpr(Op, RHSC);
2135             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2136               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2137                                                       M->op_end());
2138               Operands[i] = Div;
2139               return getMulExpr(Operands);
2140             }
2141           }
2142       }
2143       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2144       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2145         SmallVector<const SCEV *, 4> Operands;
2146         for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2147           Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2148         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2149           Operands.clear();
2150           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2151             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2152             if (isa<SCEVUDivExpr>(Op) ||
2153                 getMulExpr(Op, RHS) != A->getOperand(i))
2154               break;
2155             Operands.push_back(Op);
2156           }
2157           if (Operands.size() == A->getNumOperands())
2158             return getAddExpr(Operands);
2159         }
2160       }
2161
2162       // Fold if both operands are constant.
2163       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2164         Constant *LHSCV = LHSC->getValue();
2165         Constant *RHSCV = RHSC->getValue();
2166         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2167                                                                    RHSCV)));
2168       }
2169     }
2170   }
2171
2172   FoldingSetNodeID ID;
2173   ID.AddInteger(scUDivExpr);
2174   ID.AddPointer(LHS);
2175   ID.AddPointer(RHS);
2176   void *IP = 0;
2177   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2178   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2179                                              LHS, RHS);
2180   UniqueSCEVs.InsertNode(S, IP);
2181   return S;
2182 }
2183
2184
2185 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2186 /// Simplify the expression as much as possible.
2187 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2188                                            const Loop *L,
2189                                            SCEV::NoWrapFlags Flags) {
2190   SmallVector<const SCEV *, 4> Operands;
2191   Operands.push_back(Start);
2192   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2193     if (StepChrec->getLoop() == L) {
2194       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2195       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2196     }
2197
2198   Operands.push_back(Step);
2199   return getAddRecExpr(Operands, L, Flags);
2200 }
2201
2202 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2203 /// Simplify the expression as much as possible.
2204 const SCEV *
2205 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2206                                const Loop *L, SCEV::NoWrapFlags Flags) {
2207   if (Operands.size() == 1) return Operands[0];
2208 #ifndef NDEBUG
2209   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2210   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2211     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2212            "SCEVAddRecExpr operand types don't match!");
2213   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2214     assert(isLoopInvariant(Operands[i], L) &&
2215            "SCEVAddRecExpr operand is not loop-invariant!");
2216 #endif
2217
2218   if (Operands.back()->isZero()) {
2219     Operands.pop_back();
2220     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2221   }
2222
2223   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2224   // use that information to infer NUW and NSW flags. However, computing a
2225   // BE count requires calling getAddRecExpr, so we may not yet have a
2226   // meaningful BE count at this point (and if we don't, we'd be stuck
2227   // with a SCEVCouldNotCompute as the cached BE count).
2228
2229   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2230   // And vice-versa.
2231   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2232   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2233   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
2234     bool All = true;
2235     for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2236          E = Operands.end(); I != E; ++I)
2237       if (!isKnownNonNegative(*I)) {
2238         All = false;
2239         break;
2240       }
2241     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2242   }
2243
2244   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2245   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2246     const Loop *NestedLoop = NestedAR->getLoop();
2247     if (L->contains(NestedLoop) ?
2248         (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2249         (!NestedLoop->contains(L) &&
2250          DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2251       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2252                                                   NestedAR->op_end());
2253       Operands[0] = NestedAR->getStart();
2254       // AddRecs require their operands be loop-invariant with respect to their
2255       // loops. Don't perform this transformation if it would break this
2256       // requirement.
2257       bool AllInvariant = true;
2258       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2259         if (!isLoopInvariant(Operands[i], L)) {
2260           AllInvariant = false;
2261           break;
2262         }
2263       if (AllInvariant) {
2264         // Create a recurrence for the outer loop with the same step size.
2265         //
2266         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2267         // inner recurrence has the same property.
2268         SCEV::NoWrapFlags OuterFlags =
2269           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
2270
2271         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
2272         AllInvariant = true;
2273         for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2274           if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
2275             AllInvariant = false;
2276             break;
2277           }
2278         if (AllInvariant) {
2279           // Ok, both add recurrences are valid after the transformation.
2280           //
2281           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2282           // the outer recurrence has the same property.
2283           SCEV::NoWrapFlags InnerFlags =
2284             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
2285           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2286         }
2287       }
2288       // Reset Operands to its original state.
2289       Operands[0] = NestedAR;
2290     }
2291   }
2292
2293   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
2294   // already have one, otherwise create a new one.
2295   FoldingSetNodeID ID;
2296   ID.AddInteger(scAddRecExpr);
2297   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2298     ID.AddPointer(Operands[i]);
2299   ID.AddPointer(L);
2300   void *IP = 0;
2301   SCEVAddRecExpr *S =
2302     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2303   if (!S) {
2304     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2305     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2306     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2307                                            O, Operands.size(), L);
2308     UniqueSCEVs.InsertNode(S, IP);
2309   }
2310   S->setNoWrapFlags(Flags);
2311   return S;
2312 }
2313
2314 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2315                                          const SCEV *RHS) {
2316   SmallVector<const SCEV *, 2> Ops;
2317   Ops.push_back(LHS);
2318   Ops.push_back(RHS);
2319   return getSMaxExpr(Ops);
2320 }
2321
2322 const SCEV *
2323 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2324   assert(!Ops.empty() && "Cannot get empty smax!");
2325   if (Ops.size() == 1) return Ops[0];
2326 #ifndef NDEBUG
2327   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2328   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2329     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2330            "SCEVSMaxExpr operand types don't match!");
2331 #endif
2332
2333   // Sort by complexity, this groups all similar expression types together.
2334   GroupByComplexity(Ops, LI);
2335
2336   // If there are any constants, fold them together.
2337   unsigned Idx = 0;
2338   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2339     ++Idx;
2340     assert(Idx < Ops.size());
2341     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2342       // We found two constants, fold them together!
2343       ConstantInt *Fold = ConstantInt::get(getContext(),
2344                               APIntOps::smax(LHSC->getValue()->getValue(),
2345                                              RHSC->getValue()->getValue()));
2346       Ops[0] = getConstant(Fold);
2347       Ops.erase(Ops.begin()+1);  // Erase the folded element
2348       if (Ops.size() == 1) return Ops[0];
2349       LHSC = cast<SCEVConstant>(Ops[0]);
2350     }
2351
2352     // If we are left with a constant minimum-int, strip it off.
2353     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2354       Ops.erase(Ops.begin());
2355       --Idx;
2356     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2357       // If we have an smax with a constant maximum-int, it will always be
2358       // maximum-int.
2359       return Ops[0];
2360     }
2361
2362     if (Ops.size() == 1) return Ops[0];
2363   }
2364
2365   // Find the first SMax
2366   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2367     ++Idx;
2368
2369   // Check to see if one of the operands is an SMax. If so, expand its operands
2370   // onto our operand list, and recurse to simplify.
2371   if (Idx < Ops.size()) {
2372     bool DeletedSMax = false;
2373     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2374       Ops.erase(Ops.begin()+Idx);
2375       Ops.append(SMax->op_begin(), SMax->op_end());
2376       DeletedSMax = true;
2377     }
2378
2379     if (DeletedSMax)
2380       return getSMaxExpr(Ops);
2381   }
2382
2383   // Okay, check to see if the same value occurs in the operand list twice.  If
2384   // so, delete one.  Since we sorted the list, these values are required to
2385   // be adjacent.
2386   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2387     //  X smax Y smax Y  -->  X smax Y
2388     //  X smax Y         -->  X, if X is always greater than Y
2389     if (Ops[i] == Ops[i+1] ||
2390         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2391       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2392       --i; --e;
2393     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2394       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2395       --i; --e;
2396     }
2397
2398   if (Ops.size() == 1) return Ops[0];
2399
2400   assert(!Ops.empty() && "Reduced smax down to nothing!");
2401
2402   // Okay, it looks like we really DO need an smax expr.  Check to see if we
2403   // already have one, otherwise create a new one.
2404   FoldingSetNodeID ID;
2405   ID.AddInteger(scSMaxExpr);
2406   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2407     ID.AddPointer(Ops[i]);
2408   void *IP = 0;
2409   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2410   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2411   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2412   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2413                                              O, Ops.size());
2414   UniqueSCEVs.InsertNode(S, IP);
2415   return S;
2416 }
2417
2418 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2419                                          const SCEV *RHS) {
2420   SmallVector<const SCEV *, 2> Ops;
2421   Ops.push_back(LHS);
2422   Ops.push_back(RHS);
2423   return getUMaxExpr(Ops);
2424 }
2425
2426 const SCEV *
2427 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2428   assert(!Ops.empty() && "Cannot get empty umax!");
2429   if (Ops.size() == 1) return Ops[0];
2430 #ifndef NDEBUG
2431   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2432   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2433     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2434            "SCEVUMaxExpr operand types don't match!");
2435 #endif
2436
2437   // Sort by complexity, this groups all similar expression types together.
2438   GroupByComplexity(Ops, LI);
2439
2440   // If there are any constants, fold them together.
2441   unsigned Idx = 0;
2442   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2443     ++Idx;
2444     assert(Idx < Ops.size());
2445     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2446       // We found two constants, fold them together!
2447       ConstantInt *Fold = ConstantInt::get(getContext(),
2448                               APIntOps::umax(LHSC->getValue()->getValue(),
2449                                              RHSC->getValue()->getValue()));
2450       Ops[0] = getConstant(Fold);
2451       Ops.erase(Ops.begin()+1);  // Erase the folded element
2452       if (Ops.size() == 1) return Ops[0];
2453       LHSC = cast<SCEVConstant>(Ops[0]);
2454     }
2455
2456     // If we are left with a constant minimum-int, strip it off.
2457     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2458       Ops.erase(Ops.begin());
2459       --Idx;
2460     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2461       // If we have an umax with a constant maximum-int, it will always be
2462       // maximum-int.
2463       return Ops[0];
2464     }
2465
2466     if (Ops.size() == 1) return Ops[0];
2467   }
2468
2469   // Find the first UMax
2470   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2471     ++Idx;
2472
2473   // Check to see if one of the operands is a UMax. If so, expand its operands
2474   // onto our operand list, and recurse to simplify.
2475   if (Idx < Ops.size()) {
2476     bool DeletedUMax = false;
2477     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2478       Ops.erase(Ops.begin()+Idx);
2479       Ops.append(UMax->op_begin(), UMax->op_end());
2480       DeletedUMax = true;
2481     }
2482
2483     if (DeletedUMax)
2484       return getUMaxExpr(Ops);
2485   }
2486
2487   // Okay, check to see if the same value occurs in the operand list twice.  If
2488   // so, delete one.  Since we sorted the list, these values are required to
2489   // be adjacent.
2490   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2491     //  X umax Y umax Y  -->  X umax Y
2492     //  X umax Y         -->  X, if X is always greater than Y
2493     if (Ops[i] == Ops[i+1] ||
2494         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2495       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2496       --i; --e;
2497     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2498       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2499       --i; --e;
2500     }
2501
2502   if (Ops.size() == 1) return Ops[0];
2503
2504   assert(!Ops.empty() && "Reduced umax down to nothing!");
2505
2506   // Okay, it looks like we really DO need a umax expr.  Check to see if we
2507   // already have one, otherwise create a new one.
2508   FoldingSetNodeID ID;
2509   ID.AddInteger(scUMaxExpr);
2510   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2511     ID.AddPointer(Ops[i]);
2512   void *IP = 0;
2513   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2514   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2515   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2516   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2517                                              O, Ops.size());
2518   UniqueSCEVs.InsertNode(S, IP);
2519   return S;
2520 }
2521
2522 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2523                                          const SCEV *RHS) {
2524   // ~smax(~x, ~y) == smin(x, y).
2525   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2526 }
2527
2528 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2529                                          const SCEV *RHS) {
2530   // ~umax(~x, ~y) == umin(x, y)
2531   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2532 }
2533
2534 const SCEV *ScalarEvolution::getSizeOfExpr(Type *AllocTy) {
2535   // If we have TargetData, we can bypass creating a target-independent
2536   // constant expression and then folding it back into a ConstantInt.
2537   // This is just a compile-time optimization.
2538   if (TD)
2539     return getConstant(TD->getIntPtrType(getContext()),
2540                        TD->getTypeAllocSize(AllocTy));
2541
2542   Constant *C = ConstantExpr::getSizeOf(AllocTy);
2543   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2544     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2545       C = Folded;
2546   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2547   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2548 }
2549
2550 const SCEV *ScalarEvolution::getAlignOfExpr(Type *AllocTy) {
2551   Constant *C = ConstantExpr::getAlignOf(AllocTy);
2552   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2553     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2554       C = Folded;
2555   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2556   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2557 }
2558
2559 const SCEV *ScalarEvolution::getOffsetOfExpr(StructType *STy,
2560                                              unsigned FieldNo) {
2561   // If we have TargetData, we can bypass creating a target-independent
2562   // constant expression and then folding it back into a ConstantInt.
2563   // This is just a compile-time optimization.
2564   if (TD)
2565     return getConstant(TD->getIntPtrType(getContext()),
2566                        TD->getStructLayout(STy)->getElementOffset(FieldNo));
2567
2568   Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2569   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2570     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2571       C = Folded;
2572   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2573   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2574 }
2575
2576 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *CTy,
2577                                              Constant *FieldNo) {
2578   Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2579   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2580     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2581       C = Folded;
2582   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2583   return getTruncateOrZeroExtend(getSCEV(C), Ty);
2584 }
2585
2586 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2587   // Don't attempt to do anything other than create a SCEVUnknown object
2588   // here.  createSCEV only calls getUnknown after checking for all other
2589   // interesting possibilities, and any other code that calls getUnknown
2590   // is doing so in order to hide a value from SCEV canonicalization.
2591
2592   FoldingSetNodeID ID;
2593   ID.AddInteger(scUnknown);
2594   ID.AddPointer(V);
2595   void *IP = 0;
2596   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2597     assert(cast<SCEVUnknown>(S)->getValue() == V &&
2598            "Stale SCEVUnknown in uniquing map!");
2599     return S;
2600   }
2601   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2602                                             FirstUnknown);
2603   FirstUnknown = cast<SCEVUnknown>(S);
2604   UniqueSCEVs.InsertNode(S, IP);
2605   return S;
2606 }
2607
2608 //===----------------------------------------------------------------------===//
2609 //            Basic SCEV Analysis and PHI Idiom Recognition Code
2610 //
2611
2612 /// isSCEVable - Test if values of the given type are analyzable within
2613 /// the SCEV framework. This primarily includes integer types, and it
2614 /// can optionally include pointer types if the ScalarEvolution class
2615 /// has access to target-specific information.
2616 bool ScalarEvolution::isSCEVable(Type *Ty) const {
2617   // Integers and pointers are always SCEVable.
2618   return Ty->isIntegerTy() || Ty->isPointerTy();
2619 }
2620
2621 /// getTypeSizeInBits - Return the size in bits of the specified type,
2622 /// for which isSCEVable must return true.
2623 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
2624   assert(isSCEVable(Ty) && "Type is not SCEVable!");
2625
2626   // If we have a TargetData, use it!
2627   if (TD)
2628     return TD->getTypeSizeInBits(Ty);
2629
2630   // Integer types have fixed sizes.
2631   if (Ty->isIntegerTy())
2632     return Ty->getPrimitiveSizeInBits();
2633
2634   // The only other support type is pointer. Without TargetData, conservatively
2635   // assume pointers are 64-bit.
2636   assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2637   return 64;
2638 }
2639
2640 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2641 /// the given type and which represents how SCEV will treat the given
2642 /// type, for which isSCEVable must return true. For pointer types,
2643 /// this is the pointer-sized integer type.
2644 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
2645   assert(isSCEVable(Ty) && "Type is not SCEVable!");
2646
2647   if (Ty->isIntegerTy())
2648     return Ty;
2649
2650   // The only other support type is pointer.
2651   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2652   if (TD) return TD->getIntPtrType(getContext());
2653
2654   // Without TargetData, conservatively assume pointers are 64-bit.
2655   return Type::getInt64Ty(getContext());
2656 }
2657
2658 const SCEV *ScalarEvolution::getCouldNotCompute() {
2659   return &CouldNotCompute;
2660 }
2661
2662 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2663 /// expression and create a new one.
2664 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2665   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2666
2667   ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2668   if (I != ValueExprMap.end()) return I->second;
2669   const SCEV *S = createSCEV(V);
2670
2671   // The process of creating a SCEV for V may have caused other SCEVs
2672   // to have been created, so it's necessary to insert the new entry
2673   // from scratch, rather than trying to remember the insert position
2674   // above.
2675   ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2676   return S;
2677 }
2678
2679 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2680 ///
2681 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2682   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2683     return getConstant(
2684                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2685
2686   Type *Ty = V->getType();
2687   Ty = getEffectiveSCEVType(Ty);
2688   return getMulExpr(V,
2689                   getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2690 }
2691
2692 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2693 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2694   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2695     return getConstant(
2696                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2697
2698   Type *Ty = V->getType();
2699   Ty = getEffectiveSCEVType(Ty);
2700   const SCEV *AllOnes =
2701                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2702   return getMinusSCEV(AllOnes, V);
2703 }
2704
2705 /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
2706 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
2707                                           SCEV::NoWrapFlags Flags) {
2708   assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
2709
2710   // Fast path: X - X --> 0.
2711   if (LHS == RHS)
2712     return getConstant(LHS->getType(), 0);
2713
2714   // X - Y --> X + -Y
2715   return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
2716 }
2717
2718 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2719 /// input value to the specified type.  If the type must be extended, it is zero
2720 /// extended.
2721 const SCEV *
2722 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
2723   Type *SrcTy = V->getType();
2724   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2725          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2726          "Cannot truncate or zero extend with non-integer arguments!");
2727   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2728     return V;  // No conversion
2729   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2730     return getTruncateExpr(V, Ty);
2731   return getZeroExtendExpr(V, Ty);
2732 }
2733
2734 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2735 /// input value to the specified type.  If the type must be extended, it is sign
2736 /// extended.
2737 const SCEV *
2738 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2739                                          Type *Ty) {
2740   Type *SrcTy = V->getType();
2741   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2742          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2743          "Cannot truncate or zero extend with non-integer arguments!");
2744   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2745     return V;  // No conversion
2746   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2747     return getTruncateExpr(V, Ty);
2748   return getSignExtendExpr(V, Ty);
2749 }
2750
2751 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2752 /// input value to the specified type.  If the type must be extended, it is zero
2753 /// extended.  The conversion must not be narrowing.
2754 const SCEV *
2755 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
2756   Type *SrcTy = V->getType();
2757   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2758          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2759          "Cannot noop or zero extend with non-integer arguments!");
2760   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2761          "getNoopOrZeroExtend cannot truncate!");
2762   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2763     return V;  // No conversion
2764   return getZeroExtendExpr(V, Ty);
2765 }
2766
2767 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2768 /// input value to the specified type.  If the type must be extended, it is sign
2769 /// extended.  The conversion must not be narrowing.
2770 const SCEV *
2771 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
2772   Type *SrcTy = V->getType();
2773   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2774          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2775          "Cannot noop or sign extend with non-integer arguments!");
2776   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2777          "getNoopOrSignExtend cannot truncate!");
2778   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2779     return V;  // No conversion
2780   return getSignExtendExpr(V, Ty);
2781 }
2782
2783 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2784 /// the input value to the specified type. If the type must be extended,
2785 /// it is extended with unspecified bits. The conversion must not be
2786 /// narrowing.
2787 const SCEV *
2788 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
2789   Type *SrcTy = V->getType();
2790   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2791          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2792          "Cannot noop or any extend with non-integer arguments!");
2793   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2794          "getNoopOrAnyExtend cannot truncate!");
2795   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2796     return V;  // No conversion
2797   return getAnyExtendExpr(V, Ty);
2798 }
2799
2800 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2801 /// input value to the specified type.  The conversion must not be widening.
2802 const SCEV *
2803 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
2804   Type *SrcTy = V->getType();
2805   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2806          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2807          "Cannot truncate or noop with non-integer arguments!");
2808   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2809          "getTruncateOrNoop cannot extend!");
2810   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2811     return V;  // No conversion
2812   return getTruncateExpr(V, Ty);
2813 }
2814
2815 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2816 /// the types using zero-extension, and then perform a umax operation
2817 /// with them.
2818 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2819                                                         const SCEV *RHS) {
2820   const SCEV *PromotedLHS = LHS;
2821   const SCEV *PromotedRHS = RHS;
2822
2823   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2824     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2825   else
2826     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2827
2828   return getUMaxExpr(PromotedLHS, PromotedRHS);
2829 }
2830
2831 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2832 /// the types using zero-extension, and then perform a umin operation
2833 /// with them.
2834 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2835                                                         const SCEV *RHS) {
2836   const SCEV *PromotedLHS = LHS;
2837   const SCEV *PromotedRHS = RHS;
2838
2839   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2840     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2841   else
2842     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2843
2844   return getUMinExpr(PromotedLHS, PromotedRHS);
2845 }
2846
2847 /// getPointerBase - Transitively follow the chain of pointer-type operands
2848 /// until reaching a SCEV that does not have a single pointer operand. This
2849 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
2850 /// but corner cases do exist.
2851 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
2852   // A pointer operand may evaluate to a nonpointer expression, such as null.
2853   if (!V->getType()->isPointerTy())
2854     return V;
2855
2856   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
2857     return getPointerBase(Cast->getOperand());
2858   }
2859   else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
2860     const SCEV *PtrOp = 0;
2861     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
2862          I != E; ++I) {
2863       if ((*I)->getType()->isPointerTy()) {
2864         // Cannot find the base of an expression with multiple pointer operands.
2865         if (PtrOp)
2866           return V;
2867         PtrOp = *I;
2868       }
2869     }
2870     if (!PtrOp)
2871       return V;
2872     return getPointerBase(PtrOp);
2873   }
2874   return V;
2875 }
2876
2877 /// PushDefUseChildren - Push users of the given Instruction
2878 /// onto the given Worklist.
2879 static void
2880 PushDefUseChildren(Instruction *I,
2881                    SmallVectorImpl<Instruction *> &Worklist) {
2882   // Push the def-use children onto the Worklist stack.
2883   for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2884        UI != UE; ++UI)
2885     Worklist.push_back(cast<Instruction>(*UI));
2886 }
2887
2888 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2889 /// instructions that depend on the given instruction and removes them from
2890 /// the ValueExprMapType map if they reference SymName. This is used during PHI
2891 /// resolution.
2892 void
2893 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2894   SmallVector<Instruction *, 16> Worklist;
2895   PushDefUseChildren(PN, Worklist);
2896
2897   SmallPtrSet<Instruction *, 8> Visited;
2898   Visited.insert(PN);
2899   while (!Worklist.empty()) {
2900     Instruction *I = Worklist.pop_back_val();
2901     if (!Visited.insert(I)) continue;
2902
2903     ValueExprMapType::iterator It =
2904       ValueExprMap.find(static_cast<Value *>(I));
2905     if (It != ValueExprMap.end()) {
2906       const SCEV *Old = It->second;
2907
2908       // Short-circuit the def-use traversal if the symbolic name
2909       // ceases to appear in expressions.
2910       if (Old != SymName && !hasOperand(Old, SymName))
2911         continue;
2912
2913       // SCEVUnknown for a PHI either means that it has an unrecognized
2914       // structure, it's a PHI that's in the progress of being computed
2915       // by createNodeForPHI, or it's a single-value PHI. In the first case,
2916       // additional loop trip count information isn't going to change anything.
2917       // In the second case, createNodeForPHI will perform the necessary
2918       // updates on its own when it gets to that point. In the third, we do
2919       // want to forget the SCEVUnknown.
2920       if (!isa<PHINode>(I) ||
2921           !isa<SCEVUnknown>(Old) ||
2922           (I != PN && Old == SymName)) {
2923         forgetMemoizedResults(Old);
2924         ValueExprMap.erase(It);
2925       }
2926     }
2927
2928     PushDefUseChildren(I, Worklist);
2929   }
2930 }
2931
2932 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
2933 /// a loop header, making it a potential recurrence, or it doesn't.
2934 ///
2935 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2936   if (const Loop *L = LI->getLoopFor(PN->getParent()))
2937     if (L->getHeader() == PN->getParent()) {
2938       // The loop may have multiple entrances or multiple exits; we can analyze
2939       // this phi as an addrec if it has a unique entry value and a unique
2940       // backedge value.
2941       Value *BEValueV = 0, *StartValueV = 0;
2942       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2943         Value *V = PN->getIncomingValue(i);
2944         if (L->contains(PN->getIncomingBlock(i))) {
2945           if (!BEValueV) {
2946             BEValueV = V;
2947           } else if (BEValueV != V) {
2948             BEValueV = 0;
2949             break;
2950           }
2951         } else if (!StartValueV) {
2952           StartValueV = V;
2953         } else if (StartValueV != V) {
2954           StartValueV = 0;
2955           break;
2956         }
2957       }
2958       if (BEValueV && StartValueV) {
2959         // While we are analyzing this PHI node, handle its value symbolically.
2960         const SCEV *SymbolicName = getUnknown(PN);
2961         assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
2962                "PHI node already processed?");
2963         ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2964
2965         // Using this symbolic name for the PHI, analyze the value coming around
2966         // the back-edge.
2967         const SCEV *BEValue = getSCEV(BEValueV);
2968
2969         // NOTE: If BEValue is loop invariant, we know that the PHI node just
2970         // has a special value for the first iteration of the loop.
2971
2972         // If the value coming around the backedge is an add with the symbolic
2973         // value we just inserted, then we found a simple induction variable!
2974         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2975           // If there is a single occurrence of the symbolic value, replace it
2976           // with a recurrence.
2977           unsigned FoundIndex = Add->getNumOperands();
2978           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2979             if (Add->getOperand(i) == SymbolicName)
2980               if (FoundIndex == e) {
2981                 FoundIndex = i;
2982                 break;
2983               }
2984
2985           if (FoundIndex != Add->getNumOperands()) {
2986             // Create an add with everything but the specified operand.
2987             SmallVector<const SCEV *, 8> Ops;
2988             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2989               if (i != FoundIndex)
2990                 Ops.push_back(Add->getOperand(i));
2991             const SCEV *Accum = getAddExpr(Ops);
2992
2993             // This is not a valid addrec if the step amount is varying each
2994             // loop iteration, but is not itself an addrec in this loop.
2995             if (isLoopInvariant(Accum, L) ||
2996                 (isa<SCEVAddRecExpr>(Accum) &&
2997                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2998               SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
2999
3000               // If the increment doesn't overflow, then neither the addrec nor
3001               // the post-increment will overflow.
3002               if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3003                 if (OBO->hasNoUnsignedWrap())
3004                   Flags = setFlags(Flags, SCEV::FlagNUW);
3005                 if (OBO->hasNoSignedWrap())
3006                   Flags = setFlags(Flags, SCEV::FlagNSW);
3007               } else if (const GEPOperator *GEP =
3008                          dyn_cast<GEPOperator>(BEValueV)) {
3009                 // If the increment is an inbounds GEP, then we know the address
3010                 // space cannot be wrapped around. We cannot make any guarantee
3011                 // about signed or unsigned overflow because pointers are
3012                 // unsigned but we may have a negative index from the base
3013                 // pointer.
3014                 if (GEP->isInBounds())
3015                   Flags = setFlags(Flags, SCEV::FlagNW);
3016               }
3017
3018               const SCEV *StartVal = getSCEV(StartValueV);
3019               const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
3020
3021               // Since the no-wrap flags are on the increment, they apply to the
3022               // post-incremented value as well.
3023               if (isLoopInvariant(Accum, L))
3024                 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
3025                                     Accum, L, Flags);
3026
3027               // Okay, for the entire analysis of this edge we assumed the PHI
3028               // to be symbolic.  We now need to go back and purge all of the
3029               // entries for the scalars that use the symbolic expression.
3030               ForgetSymbolicName(PN, SymbolicName);
3031               ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3032               return PHISCEV;
3033             }
3034           }
3035         } else if (const SCEVAddRecExpr *AddRec =
3036                      dyn_cast<SCEVAddRecExpr>(BEValue)) {
3037           // Otherwise, this could be a loop like this:
3038           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
3039           // In this case, j = {1,+,1}  and BEValue is j.
3040           // Because the other in-value of i (0) fits the evolution of BEValue
3041           // i really is an addrec evolution.
3042           if (AddRec->getLoop() == L && AddRec->isAffine()) {
3043             const SCEV *StartVal = getSCEV(StartValueV);
3044
3045             // If StartVal = j.start - j.stride, we can use StartVal as the
3046             // initial step of the addrec evolution.
3047             if (StartVal == getMinusSCEV(AddRec->getOperand(0),
3048                                          AddRec->getOperand(1))) {
3049               // FIXME: For constant StartVal, we should be able to infer
3050               // no-wrap flags.
3051               const SCEV *PHISCEV =
3052                 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3053                               SCEV::FlagAnyWrap);
3054
3055               // Okay, for the entire analysis of this edge we assumed the PHI
3056               // to be symbolic.  We now need to go back and purge all of the
3057               // entries for the scalars that use the symbolic expression.
3058               ForgetSymbolicName(PN, SymbolicName);
3059               ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
3060               return PHISCEV;
3061             }
3062           }
3063         }
3064       }
3065     }
3066
3067   // If the PHI has a single incoming value, follow that value, unless the
3068   // PHI's incoming blocks are in a different loop, in which case doing so
3069   // risks breaking LCSSA form. Instcombine would normally zap these, but
3070   // it doesn't have DominatorTree information, so it may miss cases.
3071   if (Value *V = SimplifyInstruction(PN, TD, DT))
3072     if (LI->replacementPreservesLCSSAForm(PN, V))
3073       return getSCEV(V);
3074
3075   // If it's not a loop phi, we can't handle it yet.
3076   return getUnknown(PN);
3077 }
3078
3079 /// createNodeForGEP - Expand GEP instructions into add and multiply
3080 /// operations. This allows them to be analyzed by regular SCEV code.
3081 ///
3082 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
3083
3084   // Don't blindly transfer the inbounds flag from the GEP instruction to the
3085   // Add expression, because the Instruction may be guarded by control flow
3086   // and the no-overflow bits may not be valid for the expression in any
3087   // context.
3088   bool isInBounds = GEP->isInBounds();
3089
3090   Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
3091   Value *Base = GEP->getOperand(0);
3092   // Don't attempt to analyze GEPs over unsized objects.
3093   if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
3094     return getUnknown(GEP);
3095   const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
3096   gep_type_iterator GTI = gep_type_begin(GEP);
3097   for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
3098                                       E = GEP->op_end();
3099        I != E; ++I) {
3100     Value *Index = *I;
3101     // Compute the (potentially symbolic) offset in bytes for this index.
3102     if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
3103       // For a struct, add the member offset.
3104       unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
3105       const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
3106
3107       // Add the field offset to the running total offset.
3108       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3109     } else {
3110       // For an array, add the element offset, explicitly scaled.
3111       const SCEV *ElementSize = getSizeOfExpr(*GTI);
3112       const SCEV *IndexS = getSCEV(Index);
3113       // Getelementptr indices are signed.
3114       IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3115
3116       // Multiply the index by the element size to compute the element offset.
3117       const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize,
3118                                            isInBounds ? SCEV::FlagNSW :
3119                                            SCEV::FlagAnyWrap);
3120
3121       // Add the element offset to the running total offset.
3122       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3123     }
3124   }
3125
3126   // Get the SCEV for the GEP base.
3127   const SCEV *BaseS = getSCEV(Base);
3128
3129   // Add the total offset from all the GEP indices to the base.
3130   return getAddExpr(BaseS, TotalOffset,
3131                     isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
3132 }
3133
3134 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3135 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
3136 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
3137 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
3138 uint32_t
3139 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
3140   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3141     return C->getValue()->getValue().countTrailingZeros();
3142
3143   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
3144     return std::min(GetMinTrailingZeros(T->getOperand()),
3145                     (uint32_t)getTypeSizeInBits(T->getType()));
3146
3147   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
3148     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3149     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3150              getTypeSizeInBits(E->getType()) : OpRes;
3151   }
3152
3153   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
3154     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3155     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3156              getTypeSizeInBits(E->getType()) : OpRes;
3157   }
3158
3159   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
3160     // The result is the min of all operands results.
3161     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3162     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3163       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3164     return MinOpRes;
3165   }
3166
3167   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
3168     // The result is the sum of all operands results.
3169     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3170     uint32_t BitWidth = getTypeSizeInBits(M->getType());
3171     for (unsigned i = 1, e = M->getNumOperands();
3172          SumOpRes != BitWidth && i != e; ++i)
3173       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
3174                           BitWidth);
3175     return SumOpRes;
3176   }
3177
3178   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
3179     // The result is the min of all operands results.
3180     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
3181     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
3182       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
3183     return MinOpRes;
3184   }
3185
3186   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
3187     // The result is the min of all operands results.
3188     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3189     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3190       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3191     return MinOpRes;
3192   }
3193
3194   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
3195     // The result is the min of all operands results.
3196     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
3197     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
3198       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
3199     return MinOpRes;
3200   }
3201
3202   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3203     // For a SCEVUnknown, ask ValueTracking.
3204     unsigned BitWidth = getTypeSizeInBits(U->getType());
3205     APInt Mask = APInt::getAllOnesValue(BitWidth);
3206     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3207     ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
3208     return Zeros.countTrailingOnes();
3209   }
3210
3211   // SCEVUDivExpr
3212   return 0;
3213 }
3214
3215 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3216 ///
3217 ConstantRange
3218 ScalarEvolution::getUnsignedRange(const SCEV *S) {
3219   // See if we've computed this range already.
3220   DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3221   if (I != UnsignedRanges.end())
3222     return I->second;
3223
3224   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3225     return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
3226
3227   unsigned BitWidth = getTypeSizeInBits(S->getType());
3228   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3229
3230   // If the value has known zeros, the maximum unsigned value will have those
3231   // known zeros as well.
3232   uint32_t TZ = GetMinTrailingZeros(S);
3233   if (TZ != 0)
3234     ConservativeResult =
3235       ConstantRange(APInt::getMinValue(BitWidth),
3236                     APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3237
3238   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3239     ConstantRange X = getUnsignedRange(Add->getOperand(0));
3240     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3241       X = X.add(getUnsignedRange(Add->getOperand(i)));
3242     return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
3243   }
3244
3245   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3246     ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3247     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3248       X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
3249     return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
3250   }
3251
3252   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3253     ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3254     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3255       X = X.smax(getUnsignedRange(SMax->getOperand(i)));
3256     return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
3257   }
3258
3259   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3260     ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3261     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3262       X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3263     return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
3264   }
3265
3266   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3267     ConstantRange X = getUnsignedRange(UDiv->getLHS());
3268     ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3269     return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3270   }
3271
3272   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3273     ConstantRange X = getUnsignedRange(ZExt->getOperand());
3274     return setUnsignedRange(ZExt,
3275       ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3276   }
3277
3278   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3279     ConstantRange X = getUnsignedRange(SExt->getOperand());
3280     return setUnsignedRange(SExt,
3281       ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3282   }
3283
3284   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3285     ConstantRange X = getUnsignedRange(Trunc->getOperand());
3286     return setUnsignedRange(Trunc,
3287       ConservativeResult.intersectWith(X.truncate(BitWidth)));
3288   }
3289
3290   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3291     // If there's no unsigned wrap, the value will never be less than its
3292     // initial value.
3293     if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
3294       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3295         if (!C->getValue()->isZero())
3296           ConservativeResult =
3297             ConservativeResult.intersectWith(
3298               ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3299
3300     // TODO: non-affine addrec
3301     if (AddRec->isAffine()) {
3302       Type *Ty = AddRec->getType();
3303       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3304       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3305           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3306         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3307
3308         const SCEV *Start = AddRec->getStart();
3309         const SCEV *Step = AddRec->getStepRecurrence(*this);
3310
3311         ConstantRange StartRange = getUnsignedRange(Start);
3312         ConstantRange StepRange = getSignedRange(Step);
3313         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3314         ConstantRange EndRange =
3315           StartRange.add(MaxBECountRange.multiply(StepRange));
3316
3317         // Check for overflow. This must be done with ConstantRange arithmetic
3318         // because we could be called from within the ScalarEvolution overflow
3319         // checking code.
3320         ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3321         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3322         ConstantRange ExtMaxBECountRange =
3323           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3324         ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3325         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3326             ExtEndRange)
3327           return setUnsignedRange(AddRec, ConservativeResult);
3328
3329         APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3330                                    EndRange.getUnsignedMin());
3331         APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3332                                    EndRange.getUnsignedMax());
3333         if (Min.isMinValue() && Max.isMaxValue())
3334           return setUnsignedRange(AddRec, ConservativeResult);
3335         return setUnsignedRange(AddRec,
3336           ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3337       }
3338     }
3339
3340     return setUnsignedRange(AddRec, ConservativeResult);
3341   }
3342
3343   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3344     // For a SCEVUnknown, ask ValueTracking.
3345     APInt Mask = APInt::getAllOnesValue(BitWidth);
3346     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3347     ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3348     if (Ones == ~Zeros + 1)
3349       return setUnsignedRange(U, ConservativeResult);
3350     return setUnsignedRange(U,
3351       ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
3352   }
3353
3354   return setUnsignedRange(S, ConservativeResult);
3355 }
3356
3357 /// getSignedRange - Determine the signed range for a particular SCEV.
3358 ///
3359 ConstantRange
3360 ScalarEvolution::getSignedRange(const SCEV *S) {
3361   // See if we've computed this range already.
3362   DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3363   if (I != SignedRanges.end())
3364     return I->second;
3365
3366   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3367     return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
3368
3369   unsigned BitWidth = getTypeSizeInBits(S->getType());
3370   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3371
3372   // If the value has known zeros, the maximum signed value will have those
3373   // known zeros as well.
3374   uint32_t TZ = GetMinTrailingZeros(S);
3375   if (TZ != 0)
3376     ConservativeResult =
3377       ConstantRange(APInt::getSignedMinValue(BitWidth),
3378                     APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3379
3380   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3381     ConstantRange X = getSignedRange(Add->getOperand(0));
3382     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3383       X = X.add(getSignedRange(Add->getOperand(i)));
3384     return setSignedRange(Add, ConservativeResult.intersectWith(X));
3385   }
3386
3387   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3388     ConstantRange X = getSignedRange(Mul->getOperand(0));
3389     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3390       X = X.multiply(getSignedRange(Mul->getOperand(i)));
3391     return setSignedRange(Mul, ConservativeResult.intersectWith(X));
3392   }
3393
3394   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3395     ConstantRange X = getSignedRange(SMax->getOperand(0));
3396     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3397       X = X.smax(getSignedRange(SMax->getOperand(i)));
3398     return setSignedRange(SMax, ConservativeResult.intersectWith(X));
3399   }
3400
3401   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3402     ConstantRange X = getSignedRange(UMax->getOperand(0));
3403     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3404       X = X.umax(getSignedRange(UMax->getOperand(i)));
3405     return setSignedRange(UMax, ConservativeResult.intersectWith(X));
3406   }
3407
3408   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3409     ConstantRange X = getSignedRange(UDiv->getLHS());
3410     ConstantRange Y = getSignedRange(UDiv->getRHS());
3411     return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
3412   }
3413
3414   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3415     ConstantRange X = getSignedRange(ZExt->getOperand());
3416     return setSignedRange(ZExt,
3417       ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
3418   }
3419
3420   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3421     ConstantRange X = getSignedRange(SExt->getOperand());
3422     return setSignedRange(SExt,
3423       ConservativeResult.intersectWith(X.signExtend(BitWidth)));
3424   }
3425
3426   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3427     ConstantRange X = getSignedRange(Trunc->getOperand());
3428     return setSignedRange(Trunc,
3429       ConservativeResult.intersectWith(X.truncate(BitWidth)));
3430   }
3431
3432   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3433     // If there's no signed wrap, and all the operands have the same sign or
3434     // zero, the value won't ever change sign.
3435     if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
3436       bool AllNonNeg = true;
3437       bool AllNonPos = true;
3438       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3439         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3440         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3441       }
3442       if (AllNonNeg)
3443         ConservativeResult = ConservativeResult.intersectWith(
3444           ConstantRange(APInt(BitWidth, 0),
3445                         APInt::getSignedMinValue(BitWidth)));
3446       else if (AllNonPos)
3447         ConservativeResult = ConservativeResult.intersectWith(
3448           ConstantRange(APInt::getSignedMinValue(BitWidth),
3449                         APInt(BitWidth, 1)));
3450     }
3451
3452     // TODO: non-affine addrec
3453     if (AddRec->isAffine()) {
3454       Type *Ty = AddRec->getType();
3455       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3456       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3457           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3458         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3459
3460         const SCEV *Start = AddRec->getStart();
3461         const SCEV *Step = AddRec->getStepRecurrence(*this);
3462
3463         ConstantRange StartRange = getSignedRange(Start);
3464         ConstantRange StepRange = getSignedRange(Step);
3465         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3466         ConstantRange EndRange =
3467           StartRange.add(MaxBECountRange.multiply(StepRange));
3468
3469         // Check for overflow. This must be done with ConstantRange arithmetic
3470         // because we could be called from within the ScalarEvolution overflow
3471         // checking code.
3472         ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3473         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3474         ConstantRange ExtMaxBECountRange =
3475           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3476         ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3477         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3478             ExtEndRange)
3479           return setSignedRange(AddRec, ConservativeResult);
3480
3481         APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3482                                    EndRange.getSignedMin());
3483         APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3484                                    EndRange.getSignedMax());
3485         if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3486           return setSignedRange(AddRec, ConservativeResult);
3487         return setSignedRange(AddRec,
3488           ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
3489       }
3490     }
3491
3492     return setSignedRange(AddRec, ConservativeResult);
3493   }
3494
3495   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3496     // For a SCEVUnknown, ask ValueTracking.
3497     if (!U->getValue()->getType()->isIntegerTy() && !TD)
3498       return setSignedRange(U, ConservativeResult);
3499     unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3500     if (NS == 1)
3501       return setSignedRange(U, ConservativeResult);
3502     return setSignedRange(U, ConservativeResult.intersectWith(
3503       ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3504                     APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
3505   }
3506
3507   return setSignedRange(S, ConservativeResult);
3508 }
3509
3510 /// createSCEV - We know that there is no SCEV for the specified value.
3511 /// Analyze the expression.
3512 ///
3513 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3514   if (!isSCEVable(V->getType()))
3515     return getUnknown(V);
3516
3517   unsigned Opcode = Instruction::UserOp1;
3518   if (Instruction *I = dyn_cast<Instruction>(V)) {
3519     Opcode = I->getOpcode();
3520
3521     // Don't attempt to analyze instructions in blocks that aren't
3522     // reachable. Such instructions don't matter, and they aren't required
3523     // to obey basic rules for definitions dominating uses which this
3524     // analysis depends on.
3525     if (!DT->isReachableFromEntry(I->getParent()))
3526       return getUnknown(V);
3527   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3528     Opcode = CE->getOpcode();
3529   else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3530     return getConstant(CI);
3531   else if (isa<ConstantPointerNull>(V))
3532     return getConstant(V->getType(), 0);
3533   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3534     return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3535   else
3536     return getUnknown(V);
3537
3538   Operator *U = cast<Operator>(V);
3539   switch (Opcode) {
3540   case Instruction::Add: {
3541     // The simple thing to do would be to just call getSCEV on both operands
3542     // and call getAddExpr with the result. However if we're looking at a
3543     // bunch of things all added together, this can be quite inefficient,
3544     // because it leads to N-1 getAddExpr calls for N ultimate operands.
3545     // Instead, gather up all the operands and make a single getAddExpr call.
3546     // LLVM IR canonical form means we need only traverse the left operands.
3547     SmallVector<const SCEV *, 4> AddOps;
3548     AddOps.push_back(getSCEV(U->getOperand(1)));
3549     for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3550       unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3551       if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3552         break;
3553       U = cast<Operator>(Op);
3554       const SCEV *Op1 = getSCEV(U->getOperand(1));
3555       if (Opcode == Instruction::Sub)
3556         AddOps.push_back(getNegativeSCEV(Op1));
3557       else
3558         AddOps.push_back(Op1);
3559     }
3560     AddOps.push_back(getSCEV(U->getOperand(0)));
3561     SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3562     OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(V);
3563     if (OBO->hasNoSignedWrap())
3564       setFlags(Flags, SCEV::FlagNSW);
3565     if (OBO->hasNoUnsignedWrap())
3566       setFlags(Flags, SCEV::FlagNUW);
3567     return getAddExpr(AddOps, Flags);
3568   }
3569   case Instruction::Mul: {
3570     // See the Add code above.
3571     SmallVector<const SCEV *, 4> MulOps;
3572     MulOps.push_back(getSCEV(U->getOperand(1)));
3573     for (Value *Op = U->getOperand(0);
3574          Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3575          Op = U->getOperand(0)) {
3576       U = cast<Operator>(Op);
3577       MulOps.push_back(getSCEV(U->getOperand(1)));
3578     }
3579     MulOps.push_back(getSCEV(U->getOperand(0)));
3580     return getMulExpr(MulOps);
3581   }
3582   case Instruction::UDiv:
3583     return getUDivExpr(getSCEV(U->getOperand(0)),
3584                        getSCEV(U->getOperand(1)));
3585   case Instruction::Sub:
3586     return getMinusSCEV(getSCEV(U->getOperand(0)),
3587                         getSCEV(U->getOperand(1)));
3588   case Instruction::And:
3589     // For an expression like x&255 that merely masks off the high bits,
3590     // use zext(trunc(x)) as the SCEV expression.
3591     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3592       if (CI->isNullValue())
3593         return getSCEV(U->getOperand(1));
3594       if (CI->isAllOnesValue())
3595         return getSCEV(U->getOperand(0));
3596       const APInt &A = CI->getValue();
3597
3598       // Instcombine's ShrinkDemandedConstant may strip bits out of
3599       // constants, obscuring what would otherwise be a low-bits mask.
3600       // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3601       // knew about to reconstruct a low-bits mask value.
3602       unsigned LZ = A.countLeadingZeros();
3603       unsigned BitWidth = A.getBitWidth();
3604       APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3605       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3606       ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3607
3608       APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3609
3610       if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3611         return
3612           getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3613                                 IntegerType::get(getContext(), BitWidth - LZ)),
3614                             U->getType());
3615     }
3616     break;
3617
3618   case Instruction::Or:
3619     // If the RHS of the Or is a constant, we may have something like:
3620     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
3621     // optimizations will transparently handle this case.
3622     //
3623     // In order for this transformation to be safe, the LHS must be of the
3624     // form X*(2^n) and the Or constant must be less than 2^n.
3625     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3626       const SCEV *LHS = getSCEV(U->getOperand(0));
3627       const APInt &CIVal = CI->getValue();
3628       if (GetMinTrailingZeros(LHS) >=
3629           (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3630         // Build a plain add SCEV.
3631         const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3632         // If the LHS of the add was an addrec and it has no-wrap flags,
3633         // transfer the no-wrap flags, since an or won't introduce a wrap.
3634         if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3635           const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3636           const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
3637             OldAR->getNoWrapFlags());
3638         }
3639         return S;
3640       }
3641     }
3642     break;
3643   case Instruction::Xor:
3644     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3645       // If the RHS of the xor is a signbit, then this is just an add.
3646       // Instcombine turns add of signbit into xor as a strength reduction step.
3647       if (CI->getValue().isSignBit())
3648         return getAddExpr(getSCEV(U->getOperand(0)),
3649                           getSCEV(U->getOperand(1)));
3650
3651       // If the RHS of xor is -1, then this is a not operation.
3652       if (CI->isAllOnesValue())
3653         return getNotSCEV(getSCEV(U->getOperand(0)));
3654
3655       // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3656       // This is a variant of the check for xor with -1, and it handles
3657       // the case where instcombine has trimmed non-demanded bits out
3658       // of an xor with -1.
3659       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3660         if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3661           if (BO->getOpcode() == Instruction::And &&
3662               LCI->getValue() == CI->getValue())
3663             if (const SCEVZeroExtendExpr *Z =
3664                   dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3665               Type *UTy = U->getType();
3666               const SCEV *Z0 = Z->getOperand();
3667               Type *Z0Ty = Z0->getType();
3668               unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3669
3670               // If C is a low-bits mask, the zero extend is serving to
3671               // mask off the high bits. Complement the operand and
3672               // re-apply the zext.
3673               if (APIntOps::isMask(Z0TySize, CI->getValue()))
3674                 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3675
3676               // If C is a single bit, it may be in the sign-bit position
3677               // before the zero-extend. In this case, represent the xor
3678               // using an add, which is equivalent, and re-apply the zext.
3679               APInt Trunc = CI->getValue().trunc(Z0TySize);
3680               if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3681                   Trunc.isSignBit())
3682                 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3683                                          UTy);
3684             }
3685     }
3686     break;
3687
3688   case Instruction::Shl:
3689     // Turn shift left of a constant amount into a multiply.
3690     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3691       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3692
3693       // If the shift count is not less than the bitwidth, the result of
3694       // the shift is undefined. Don't try to analyze it, because the
3695       // resolution chosen here may differ from the resolution chosen in
3696       // other parts of the compiler.
3697       if (SA->getValue().uge(BitWidth))
3698         break;
3699
3700       Constant *X = ConstantInt::get(getContext(),
3701         APInt(BitWidth, 1).shl(SA->getZExtValue()));
3702       return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3703     }
3704     break;
3705
3706   case Instruction::LShr:
3707     // Turn logical shift right of a constant into a unsigned divide.
3708     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3709       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3710
3711       // If the shift count is not less than the bitwidth, the result of
3712       // the shift is undefined. Don't try to analyze it, because the
3713       // resolution chosen here may differ from the resolution chosen in
3714       // other parts of the compiler.
3715       if (SA->getValue().uge(BitWidth))
3716         break;
3717
3718       Constant *X = ConstantInt::get(getContext(),
3719         APInt(BitWidth, 1).shl(SA->getZExtValue()));
3720       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3721     }
3722     break;
3723
3724   case Instruction::AShr:
3725     // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3726     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3727       if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3728         if (L->getOpcode() == Instruction::Shl &&
3729             L->getOperand(1) == U->getOperand(1)) {
3730           uint64_t BitWidth = getTypeSizeInBits(U->getType());
3731
3732           // If the shift count is not less than the bitwidth, the result of
3733           // the shift is undefined. Don't try to analyze it, because the
3734           // resolution chosen here may differ from the resolution chosen in
3735           // other parts of the compiler.
3736           if (CI->getValue().uge(BitWidth))
3737             break;
3738
3739           uint64_t Amt = BitWidth - CI->getZExtValue();
3740           if (Amt == BitWidth)
3741             return getSCEV(L->getOperand(0));       // shift by zero --> noop
3742           return
3743             getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3744                                               IntegerType::get(getContext(),
3745                                                                Amt)),
3746                               U->getType());
3747         }
3748     break;
3749
3750   case Instruction::Trunc:
3751     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3752
3753   case Instruction::ZExt:
3754     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3755
3756   case Instruction::SExt:
3757     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3758
3759   case Instruction::BitCast:
3760     // BitCasts are no-op casts so we just eliminate the cast.
3761     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3762       return getSCEV(U->getOperand(0));
3763     break;
3764
3765   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3766   // lead to pointer expressions which cannot safely be expanded to GEPs,
3767   // because ScalarEvolution doesn't respect the GEP aliasing rules when
3768   // simplifying integer expressions.
3769
3770   case Instruction::GetElementPtr:
3771     return createNodeForGEP(cast<GEPOperator>(U));
3772
3773   case Instruction::PHI:
3774     return createNodeForPHI(cast<PHINode>(U));
3775
3776   case Instruction::Select:
3777     // This could be a smax or umax that was lowered earlier.
3778     // Try to recover it.
3779     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3780       Value *LHS = ICI->getOperand(0);
3781       Value *RHS = ICI->getOperand(1);
3782       switch (ICI->getPredicate()) {
3783       case ICmpInst::ICMP_SLT:
3784       case ICmpInst::ICMP_SLE:
3785         std::swap(LHS, RHS);
3786         // fall through
3787       case ICmpInst::ICMP_SGT:
3788       case ICmpInst::ICMP_SGE:
3789         // a >s b ? a+x : b+x  ->  smax(a, b)+x
3790         // a >s b ? b+x : a+x  ->  smin(a, b)+x
3791         if (LHS->getType() == U->getType()) {
3792           const SCEV *LS = getSCEV(LHS);
3793           const SCEV *RS = getSCEV(RHS);
3794           const SCEV *LA = getSCEV(U->getOperand(1));
3795           const SCEV *RA = getSCEV(U->getOperand(2));
3796           const SCEV *LDiff = getMinusSCEV(LA, LS);
3797           const SCEV *RDiff = getMinusSCEV(RA, RS);
3798           if (LDiff == RDiff)
3799             return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3800           LDiff = getMinusSCEV(LA, RS);
3801           RDiff = getMinusSCEV(RA, LS);
3802           if (LDiff == RDiff)
3803             return getAddExpr(getSMinExpr(LS, RS), LDiff);
3804         }
3805         break;
3806       case ICmpInst::ICMP_ULT:
3807       case ICmpInst::ICMP_ULE:
3808         std::swap(LHS, RHS);
3809         // fall through
3810       case ICmpInst::ICMP_UGT:
3811       case ICmpInst::ICMP_UGE:
3812         // a >u b ? a+x : b+x  ->  umax(a, b)+x
3813         // a >u b ? b+x : a+x  ->  umin(a, b)+x
3814         if (LHS->getType() == U->getType()) {
3815           const SCEV *LS = getSCEV(LHS);
3816           const SCEV *RS = getSCEV(RHS);
3817           const SCEV *LA = getSCEV(U->getOperand(1));
3818           const SCEV *RA = getSCEV(U->getOperand(2));
3819           const SCEV *LDiff = getMinusSCEV(LA, LS);
3820           const SCEV *RDiff = getMinusSCEV(RA, RS);
3821           if (LDiff == RDiff)
3822             return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3823           LDiff = getMinusSCEV(LA, RS);
3824           RDiff = getMinusSCEV(RA, LS);
3825           if (LDiff == RDiff)
3826             return getAddExpr(getUMinExpr(LS, RS), LDiff);
3827         }
3828         break;
3829       case ICmpInst::ICMP_NE:
3830         // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
3831         if (LHS->getType() == U->getType() &&
3832             isa<ConstantInt>(RHS) &&
3833             cast<ConstantInt>(RHS)->isZero()) {
3834           const SCEV *One = getConstant(LHS->getType(), 1);
3835           const SCEV *LS = getSCEV(LHS);
3836           const SCEV *LA = getSCEV(U->getOperand(1));
3837           const SCEV *RA = getSCEV(U->getOperand(2));
3838           const SCEV *LDiff = getMinusSCEV(LA, LS);
3839           const SCEV *RDiff = getMinusSCEV(RA, One);
3840           if (LDiff == RDiff)
3841             return getAddExpr(getUMaxExpr(One, LS), LDiff);
3842         }
3843         break;
3844       case ICmpInst::ICMP_EQ:
3845         // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
3846         if (LHS->getType() == U->getType() &&
3847             isa<ConstantInt>(RHS) &&
3848             cast<ConstantInt>(RHS)->isZero()) {
3849           const SCEV *One = getConstant(LHS->getType(), 1);
3850           const SCEV *LS = getSCEV(LHS);
3851           const SCEV *LA = getSCEV(U->getOperand(1));
3852           const SCEV *RA = getSCEV(U->getOperand(2));
3853           const SCEV *LDiff = getMinusSCEV(LA, One);
3854           const SCEV *RDiff = getMinusSCEV(RA, LS);
3855           if (LDiff == RDiff)
3856             return getAddExpr(getUMaxExpr(One, LS), LDiff);
3857         }
3858         break;
3859       default:
3860         break;
3861       }
3862     }
3863
3864   default: // We cannot analyze this expression.
3865     break;
3866   }
3867
3868   return getUnknown(V);
3869 }
3870
3871
3872
3873 //===----------------------------------------------------------------------===//
3874 //                   Iteration Count Computation Code
3875 //
3876
3877 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
3878 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
3879 /// or not constant. Will also return 0 if the maximum trip count is very large
3880 /// (>= 2^32)
3881 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
3882                                                     BasicBlock *ExitBlock) {
3883   const SCEVConstant *ExitCount =
3884     dyn_cast<SCEVConstant>(getExitCount(L, ExitBlock));
3885   if (!ExitCount)
3886     return 0;
3887
3888   ConstantInt *ExitConst = ExitCount->getValue();
3889
3890   // Guard against huge trip counts.
3891   if (ExitConst->getValue().getActiveBits() > 32)
3892     return 0;
3893
3894   // In case of integer overflow, this returns 0, which is correct.
3895   return ((unsigned)ExitConst->getZExtValue()) + 1;
3896 }
3897
3898 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
3899 /// trip count of this loop as a normal unsigned value, if possible. This
3900 /// means that the actual trip count is always a multiple of the returned
3901 /// value (don't forget the trip count could very well be zero as well!).
3902 ///
3903 /// Returns 1 if the trip count is unknown or not guaranteed to be the
3904 /// multiple of a constant (which is also the case if the trip count is simply
3905 /// constant, use getSmallConstantTripCount for that case), Will also return 1
3906 /// if the trip count is very large (>= 2^32).
3907 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
3908                                                        BasicBlock *ExitBlock) {
3909   const SCEV *ExitCount = getExitCount(L, ExitBlock);
3910   if (ExitCount == getCouldNotCompute())
3911     return 1;
3912
3913   // Get the trip count from the BE count by adding 1.
3914   const SCEV *TCMul = getAddExpr(ExitCount,
3915                                  getConstant(ExitCount->getType(), 1));
3916   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
3917   // to factor simple cases.
3918   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
3919     TCMul = Mul->getOperand(0);
3920
3921   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
3922   if (!MulC)
3923     return 1;
3924
3925   ConstantInt *Result = MulC->getValue();
3926
3927   // Guard against huge trip counts.
3928   if (!Result || Result->getValue().getActiveBits() > 32)
3929     return 1;
3930
3931   return (unsigned)Result->getZExtValue();
3932 }
3933
3934 // getExitCount - Get the expression for the number of loop iterations for which
3935 // this loop is guaranteed not to exit via ExitintBlock. Otherwise return
3936 // SCEVCouldNotCompute.
3937 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
3938   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
3939 }
3940
3941 /// getBackedgeTakenCount - If the specified loop has a predictable
3942 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3943 /// object. The backedge-taken count is the number of times the loop header
3944 /// will be branched to from within the loop. This is one less than the
3945 /// trip count of the loop, since it doesn't count the first iteration,
3946 /// when the header is branched to from outside the loop.
3947 ///
3948 /// Note that it is not valid to call this method on a loop without a
3949 /// loop-invariant backedge-taken count (see
3950 /// hasLoopInvariantBackedgeTakenCount).
3951 ///
3952 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3953   return getBackedgeTakenInfo(L).getExact(this);
3954 }
3955
3956 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3957 /// return the least SCEV value that is known never to be less than the
3958 /// actual backedge taken count.
3959 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3960   return getBackedgeTakenInfo(L).getMax(this);
3961 }
3962
3963 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3964 /// onto the given Worklist.
3965 static void
3966 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3967   BasicBlock *Header = L->getHeader();
3968
3969   // Push all Loop-header PHIs onto the Worklist stack.
3970   for (BasicBlock::iterator I = Header->begin();
3971        PHINode *PN = dyn_cast<PHINode>(I); ++I)
3972     Worklist.push_back(PN);
3973 }
3974
3975 const ScalarEvolution::BackedgeTakenInfo &
3976 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3977   // Initially insert an invalid entry for this loop. If the insertion
3978   // succeeds, proceed to actually compute a backedge-taken count and
3979   // update the value. The temporary CouldNotCompute value tells SCEV
3980   // code elsewhere that it shouldn't attempt to request a new
3981   // backedge-taken count, which could result in infinite recursion.
3982   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3983     BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
3984   if (!Pair.second)
3985     return Pair.first->second;
3986
3987   // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
3988   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
3989   // must be cleared in this scope.
3990   BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
3991
3992   if (Result.getExact(this) != getCouldNotCompute()) {
3993     assert(isLoopInvariant(Result.getExact(this), L) &&
3994            isLoopInvariant(Result.getMax(this), L) &&
3995            "Computed backedge-taken count isn't loop invariant for loop!");
3996     ++NumTripCountsComputed;
3997   }
3998   else if (Result.getMax(this) == getCouldNotCompute() &&
3999            isa<PHINode>(L->getHeader()->begin())) {
4000     // Only count loops that have phi nodes as not being computable.
4001     ++NumTripCountsNotComputed;
4002   }
4003
4004   // Now that we know more about the trip count for this loop, forget any
4005   // existing SCEV values for PHI nodes in this loop since they are only
4006   // conservative estimates made without the benefit of trip count
4007   // information. This is similar to the code in forgetLoop, except that
4008   // it handles SCEVUnknown PHI nodes specially.
4009   if (Result.hasAnyInfo()) {
4010     SmallVector<Instruction *, 16> Worklist;
4011     PushLoopPHIs(L, Worklist);
4012
4013     SmallPtrSet<Instruction *, 8> Visited;
4014     while (!Worklist.empty()) {
4015       Instruction *I = Worklist.pop_back_val();
4016       if (!Visited.insert(I)) continue;
4017
4018       ValueExprMapType::iterator It =
4019         ValueExprMap.find(static_cast<Value *>(I));
4020       if (It != ValueExprMap.end()) {
4021         const SCEV *Old = It->second;
4022
4023         // SCEVUnknown for a PHI either means that it has an unrecognized
4024         // structure, or it's a PHI that's in the progress of being computed
4025         // by createNodeForPHI.  In the former case, additional loop trip
4026         // count information isn't going to change anything. In the later
4027         // case, createNodeForPHI will perform the necessary updates on its
4028         // own when it gets to that point.
4029         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4030           forgetMemoizedResults(Old);
4031           ValueExprMap.erase(It);
4032         }
4033         if (PHINode *PN = dyn_cast<PHINode>(I))
4034           ConstantEvolutionLoopExitValue.erase(PN);
4035       }
4036
4037       PushDefUseChildren(I, Worklist);
4038     }
4039   }
4040
4041   // Re-lookup the insert position, since the call to
4042   // ComputeBackedgeTakenCount above could result in a
4043   // recusive call to getBackedgeTakenInfo (on a different
4044   // loop), which would invalidate the iterator computed
4045   // earlier.
4046   return BackedgeTakenCounts.find(L)->second = Result;
4047 }
4048
4049 /// forgetLoop - This method should be called by the client when it has
4050 /// changed a loop in a way that may effect ScalarEvolution's ability to
4051 /// compute a trip count, or if the loop is deleted.
4052 void ScalarEvolution::forgetLoop(const Loop *L) {
4053   // Drop any stored trip count value.
4054   DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4055     BackedgeTakenCounts.find(L);
4056   if (BTCPos != BackedgeTakenCounts.end()) {
4057     BTCPos->second.clear();
4058     BackedgeTakenCounts.erase(BTCPos);
4059   }
4060
4061   // Drop information about expressions based on loop-header PHIs.
4062   SmallVector<Instruction *, 16> Worklist;
4063   PushLoopPHIs(L, Worklist);
4064
4065   SmallPtrSet<Instruction *, 8> Visited;
4066   while (!Worklist.empty()) {
4067     Instruction *I = Worklist.pop_back_val();
4068     if (!Visited.insert(I)) continue;
4069
4070     ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4071     if (It != ValueExprMap.end()) {
4072       forgetMemoizedResults(It->second);
4073       ValueExprMap.erase(It);
4074       if (PHINode *PN = dyn_cast<PHINode>(I))
4075         ConstantEvolutionLoopExitValue.erase(PN);
4076     }
4077
4078     PushDefUseChildren(I, Worklist);
4079   }
4080
4081   // Forget all contained loops too, to avoid dangling entries in the
4082   // ValuesAtScopes map.
4083   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4084     forgetLoop(*I);
4085 }
4086
4087 /// forgetValue - This method should be called by the client when it has
4088 /// changed a value in a way that may effect its value, or which may
4089 /// disconnect it from a def-use chain linking it to a loop.
4090 void ScalarEvolution::forgetValue(Value *V) {
4091   Instruction *I = dyn_cast<Instruction>(V);
4092   if (!I) return;
4093
4094   // Drop information about expressions based on loop-header PHIs.
4095   SmallVector<Instruction *, 16> Worklist;
4096   Worklist.push_back(I);
4097
4098   SmallPtrSet<Instruction *, 8> Visited;
4099   while (!Worklist.empty()) {
4100     I = Worklist.pop_back_val();
4101     if (!Visited.insert(I)) continue;
4102
4103     ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
4104     if (It != ValueExprMap.end()) {
4105       forgetMemoizedResults(It->second);
4106       ValueExprMap.erase(It);
4107       if (PHINode *PN = dyn_cast<PHINode>(I))
4108         ConstantEvolutionLoopExitValue.erase(PN);
4109     }
4110
4111     PushDefUseChildren(I, Worklist);
4112   }
4113 }
4114
4115 /// getExact - Get the exact loop backedge taken count considering all loop
4116 /// exits. If all exits are computable, this is the minimum computed count.
4117 const SCEV *
4118 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4119   // If any exits were not computable, the loop is not computable.
4120   if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4121
4122   // We need at least one computable exit.
4123   if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
4124   assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4125
4126   const SCEV *BECount = 0;
4127   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4128        ENT != 0; ENT = ENT->getNextExit()) {
4129
4130     assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4131
4132     if (!BECount)
4133       BECount = ENT->ExactNotTaken;
4134     else
4135       BECount = SE->getUMinFromMismatchedTypes(BECount, ENT->ExactNotTaken);
4136   }
4137   assert(BECount && "Invalid not taken count for loop exit");
4138   return BECount;
4139 }
4140
4141 /// getExact - Get the exact not taken count for this loop exit.
4142 const SCEV *
4143 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
4144                                              ScalarEvolution *SE) const {
4145   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
4146        ENT != 0; ENT = ENT->getNextExit()) {
4147
4148     if (ENT->ExitingBlock == ExitingBlock)
4149       return ENT->ExactNotTaken;
4150   }
4151   return SE->getCouldNotCompute();
4152 }
4153
4154 /// getMax - Get the max backedge taken count for the loop.
4155 const SCEV *
4156 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4157   return Max ? Max : SE->getCouldNotCompute();
4158 }
4159
4160 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4161 /// computable exit into a persistent ExitNotTakenInfo array.
4162 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4163   SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4164   bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4165
4166   if (!Complete)
4167     ExitNotTaken.setIncomplete();
4168
4169   unsigned NumExits = ExitCounts.size();
4170   if (NumExits == 0) return;
4171
4172   ExitNotTaken.ExitingBlock = ExitCounts[0].first;
4173   ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4174   if (NumExits == 1) return;
4175
4176   // Handle the rare case of multiple computable exits.
4177   ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4178
4179   ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4180   for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4181     PrevENT->setNextExit(ENT);
4182     ENT->ExitingBlock = ExitCounts[i].first;
4183     ENT->ExactNotTaken = ExitCounts[i].second;
4184   }
4185 }
4186
4187 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
4188 void ScalarEvolution::BackedgeTakenInfo::clear() {
4189   ExitNotTaken.ExitingBlock = 0;
4190   ExitNotTaken.ExactNotTaken = 0;
4191   delete[] ExitNotTaken.getNextExit();
4192 }
4193
4194 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
4195 /// of the specified loop will execute.
4196 ScalarEvolution::BackedgeTakenInfo
4197 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
4198   SmallVector<BasicBlock *, 8> ExitingBlocks;
4199   L->getExitingBlocks(ExitingBlocks);
4200
4201   // Examine all exits and pick the most conservative values.
4202   const SCEV *MaxBECount = getCouldNotCompute();
4203   bool CouldComputeBECount = true;
4204   SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
4205   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
4206     ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]);
4207     if (EL.Exact == getCouldNotCompute())
4208       // We couldn't compute an exact value for this exit, so
4209       // we won't be able to compute an exact value for the loop.
4210       CouldComputeBECount = false;
4211     else
4212       ExitCounts.push_back(std::make_pair(ExitingBlocks[i], EL.Exact));
4213
4214     if (MaxBECount == getCouldNotCompute())
4215       MaxBECount = EL.Max;
4216     else if (EL.Max != getCouldNotCompute())
4217       MaxBECount = getUMinFromMismatchedTypes(MaxBECount, EL.Max);
4218   }
4219
4220   return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
4221 }
4222
4223 /// ComputeExitLimit - Compute the number of times the backedge of the specified
4224 /// loop will execute if it exits via the specified block.
4225 ScalarEvolution::ExitLimit
4226 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
4227
4228   // Okay, we've chosen an exiting block.  See what condition causes us to
4229   // exit at this block.
4230   //
4231   // FIXME: we should be able to handle switch instructions (with a single exit)
4232   BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
4233   if (ExitBr == 0) return getCouldNotCompute();
4234   assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
4235
4236   // At this point, we know we have a conditional branch that determines whether
4237   // the loop is exited.  However, we don't know if the branch is executed each
4238   // time through the loop.  If not, then the execution count of the branch will
4239   // not be equal to the trip count of the loop.
4240   //
4241   // Currently we check for this by checking to see if the Exit branch goes to
4242   // the loop header.  If so, we know it will always execute the same number of
4243   // times as the loop.  We also handle the case where the exit block *is* the
4244   // loop header.  This is common for un-rotated loops.
4245   //
4246   // If both of those tests fail, walk up the unique predecessor chain to the
4247   // header, stopping if there is an edge that doesn't exit the loop. If the
4248   // header is reached, the execution count of the branch will be equal to the
4249   // trip count of the loop.
4250   //
4251   //  More extensive analysis could be done to handle more cases here.
4252   //
4253   if (ExitBr->getSuccessor(0) != L->getHeader() &&
4254       ExitBr->getSuccessor(1) != L->getHeader() &&
4255       ExitBr->getParent() != L->getHeader()) {
4256     // The simple checks failed, try climbing the unique predecessor chain
4257     // up to the header.
4258     bool Ok = false;
4259     for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
4260       BasicBlock *Pred = BB->getUniquePredecessor();
4261       if (!Pred)
4262         return getCouldNotCompute();
4263       TerminatorInst *PredTerm = Pred->getTerminator();
4264       for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4265         BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4266         if (PredSucc == BB)
4267           continue;
4268         // If the predecessor has a successor that isn't BB and isn't
4269         // outside the loop, assume the worst.
4270         if (L->contains(PredSucc))
4271           return getCouldNotCompute();
4272       }
4273       if (Pred == L->getHeader()) {
4274         Ok = true;
4275         break;
4276       }
4277       BB = Pred;
4278     }
4279     if (!Ok)
4280       return getCouldNotCompute();
4281   }
4282
4283   // Proceed to the next level to examine the exit condition expression.
4284   return ComputeExitLimitFromCond(L, ExitBr->getCondition(),
4285                                   ExitBr->getSuccessor(0),
4286                                   ExitBr->getSuccessor(1));
4287 }
4288
4289 /// ComputeExitLimitFromCond - Compute the number of times the
4290 /// backedge of the specified loop will execute if its exit condition
4291 /// were a conditional branch of ExitCond, TBB, and FBB.
4292 ScalarEvolution::ExitLimit
4293 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4294                                           Value *ExitCond,
4295                                           BasicBlock *TBB,
4296                                           BasicBlock *FBB) {
4297   // Check if the controlling expression for this loop is an And or Or.
4298   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4299     if (BO->getOpcode() == Instruction::And) {
4300       // Recurse on the operands of the and.
4301       ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4302       ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
4303       const SCEV *BECount = getCouldNotCompute();
4304       const SCEV *MaxBECount = getCouldNotCompute();
4305       if (L->contains(TBB)) {
4306         // Both conditions must be true for the loop to continue executing.
4307         // Choose the less conservative count.
4308         if (EL0.Exact == getCouldNotCompute() ||
4309             EL1.Exact == getCouldNotCompute())
4310           BECount = getCouldNotCompute();
4311         else
4312           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4313         if (EL0.Max == getCouldNotCompute())
4314           MaxBECount = EL1.Max;
4315         else if (EL1.Max == getCouldNotCompute())
4316           MaxBECount = EL0.Max;
4317         else
4318           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4319       } else {
4320         // Both conditions must be true at the same time for the loop to exit.
4321         // For now, be conservative.
4322         assert(L->contains(FBB) && "Loop block has no successor in loop!");
4323         if (EL0.Max == EL1.Max)
4324           MaxBECount = EL0.Max;
4325         if (EL0.Exact == EL1.Exact)
4326           BECount = EL0.Exact;
4327       }
4328
4329       return ExitLimit(BECount, MaxBECount);
4330     }
4331     if (BO->getOpcode() == Instruction::Or) {
4332       // Recurse on the operands of the or.
4333       ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB);
4334       ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB);
4335       const SCEV *BECount = getCouldNotCompute();
4336       const SCEV *MaxBECount = getCouldNotCompute();
4337       if (L->contains(FBB)) {
4338         // Both conditions must be false for the loop to continue executing.
4339         // Choose the less conservative count.
4340         if (EL0.Exact == getCouldNotCompute() ||
4341             EL1.Exact == getCouldNotCompute())
4342           BECount = getCouldNotCompute();
4343         else
4344           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4345         if (EL0.Max == getCouldNotCompute())
4346           MaxBECount = EL1.Max;
4347         else if (EL1.Max == getCouldNotCompute())
4348           MaxBECount = EL0.Max;
4349         else
4350           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
4351       } else {
4352         // Both conditions must be false at the same time for the loop to exit.
4353         // For now, be conservative.
4354         assert(L->contains(TBB) && "Loop block has no successor in loop!");
4355         if (EL0.Max == EL1.Max)
4356           MaxBECount = EL0.Max;
4357         if (EL0.Exact == EL1.Exact)
4358           BECount = EL0.Exact;
4359       }
4360
4361       return ExitLimit(BECount, MaxBECount);
4362     }
4363   }
4364
4365   // With an icmp, it may be feasible to compute an exact backedge-taken count.
4366   // Proceed to the next level to examine the icmp.
4367   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
4368     return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB);
4369
4370   // Check for a constant condition. These are normally stripped out by
4371   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4372   // preserve the CFG and is temporarily leaving constant conditions
4373   // in place.
4374   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4375     if (L->contains(FBB) == !CI->getZExtValue())
4376       // The backedge is always taken.
4377       return getCouldNotCompute();
4378     else
4379       // The backedge is never taken.
4380       return getConstant(CI->getType(), 0);
4381   }
4382
4383   // If it's not an integer or pointer comparison then compute it the hard way.
4384   return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
4385 }
4386
4387 /// ComputeExitLimitFromICmp - Compute the number of times the
4388 /// backedge of the specified loop will execute if its exit condition
4389 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
4390 ScalarEvolution::ExitLimit
4391 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
4392                                           ICmpInst *ExitCond,
4393                                           BasicBlock *TBB,
4394                                           BasicBlock *FBB) {
4395
4396   // If the condition was exit on true, convert the condition to exit on false
4397   ICmpInst::Predicate Cond;
4398   if (!L->contains(FBB))
4399     Cond = ExitCond->getPredicate();
4400   else
4401     Cond = ExitCond->getInversePredicate();
4402
4403   // Handle common loops like: for (X = "string"; *X; ++X)
4404   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4405     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
4406       ExitLimit ItCnt =
4407         ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
4408       if (ItCnt.hasAnyInfo())
4409         return ItCnt;
4410     }
4411
4412   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
4413   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
4414
4415   // Try to evaluate any dependencies out of the loop.
4416   LHS = getSCEVAtScope(LHS, L);
4417   RHS = getSCEVAtScope(RHS, L);
4418
4419   // At this point, we would like to compute how many iterations of the
4420   // loop the predicate will return true for these inputs.
4421   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
4422     // If there is a loop-invariant, force it into the RHS.
4423     std::swap(LHS, RHS);
4424     Cond = ICmpInst::getSwappedPredicate(Cond);
4425   }
4426
4427   // Simplify the operands before analyzing them.
4428   (void)SimplifyICmpOperands(Cond, LHS, RHS);
4429
4430   // If we have a comparison of a chrec against a constant, try to use value
4431   // ranges to answer this query.
4432   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
4433     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
4434       if (AddRec->getLoop() == L) {
4435         // Form the constant range.
4436         ConstantRange CompRange(
4437             ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
4438
4439         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
4440         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
4441       }
4442
4443   switch (Cond) {
4444   case ICmpInst::ICMP_NE: {                     // while (X != Y)
4445     // Convert to: while (X-Y != 0)
4446     ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4447     if (EL.hasAnyInfo()) return EL;
4448     break;
4449   }
4450   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
4451     // Convert to: while (X-Y == 0)
4452     ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4453     if (EL.hasAnyInfo()) return EL;
4454     break;
4455   }
4456   case ICmpInst::ICMP_SLT: {
4457     ExitLimit EL = HowManyLessThans(LHS, RHS, L, true);
4458     if (EL.hasAnyInfo()) return EL;
4459     break;
4460   }
4461   case ICmpInst::ICMP_SGT: {
4462     ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
4463                                              getNotSCEV(RHS), L, true);
4464     if (EL.hasAnyInfo()) return EL;
4465     break;
4466   }
4467   case ICmpInst::ICMP_ULT: {
4468     ExitLimit EL = HowManyLessThans(LHS, RHS, L, false);
4469     if (EL.hasAnyInfo()) return EL;
4470     break;
4471   }
4472   case ICmpInst::ICMP_UGT: {
4473     ExitLimit EL = HowManyLessThans(getNotSCEV(LHS),
4474                                              getNotSCEV(RHS), L, false);
4475     if (EL.hasAnyInfo()) return EL;
4476     break;
4477   }
4478   default:
4479 #if 0
4480     dbgs() << "ComputeBackedgeTakenCount ";
4481     if (ExitCond->getOperand(0)->getType()->isUnsigned())
4482       dbgs() << "[unsigned] ";
4483     dbgs() << *LHS << "   "
4484          << Instruction::getOpcodeName(Instruction::ICmp)
4485          << "   " << *RHS << "\n";
4486 #endif
4487     break;
4488   }
4489   return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
4490 }
4491
4492 static ConstantInt *
4493 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4494                                 ScalarEvolution &SE) {
4495   const SCEV *InVal = SE.getConstant(C);
4496   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4497   assert(isa<SCEVConstant>(Val) &&
4498          "Evaluation of SCEV at constant didn't fold correctly?");
4499   return cast<SCEVConstant>(Val)->getValue();
4500 }
4501
4502 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4503 /// and a GEP expression (missing the pointer index) indexing into it, return
4504 /// the addressed element of the initializer or null if the index expression is
4505 /// invalid.
4506 static Constant *
4507 GetAddressedElementFromGlobal(GlobalVariable *GV,
4508                               const std::vector<ConstantInt*> &Indices) {
4509   Constant *Init = GV->getInitializer();
4510   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4511     uint64_t Idx = Indices[i]->getZExtValue();
4512     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4513       assert(Idx < CS->getNumOperands() && "Bad struct index!");
4514       Init = cast<Constant>(CS->getOperand(Idx));
4515     } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4516       if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
4517       Init = cast<Constant>(CA->getOperand(Idx));
4518     } else if (isa<ConstantAggregateZero>(Init)) {
4519       if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
4520         assert(Idx < STy->getNumElements() && "Bad struct index!");
4521         Init = Constant::getNullValue(STy->getElementType(Idx));
4522       } else if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4523         if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
4524         Init = Constant::getNullValue(ATy->getElementType());
4525       } else {
4526         llvm_unreachable("Unknown constant aggregate type!");
4527       }
4528       return 0;
4529     } else {
4530       return 0; // Unknown initializer type
4531     }
4532   }
4533   return Init;
4534 }
4535
4536 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
4537 /// 'icmp op load X, cst', try to see if we can compute the backedge
4538 /// execution count.
4539 ScalarEvolution::ExitLimit
4540 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
4541   LoadInst *LI,
4542   Constant *RHS,
4543   const Loop *L,
4544   ICmpInst::Predicate predicate) {
4545
4546   if (LI->isVolatile()) return getCouldNotCompute();
4547
4548   // Check to see if the loaded pointer is a getelementptr of a global.
4549   // TODO: Use SCEV instead of manually grubbing with GEPs.
4550   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4551   if (!GEP) return getCouldNotCompute();
4552
4553   // Make sure that it is really a constant global we are gepping, with an
4554   // initializer, and make sure the first IDX is really 0.
4555   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4556   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4557       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4558       !cast<Constant>(GEP->getOperand(1))->isNullValue())
4559     return getCouldNotCompute();
4560
4561   // Okay, we allow one non-constant index into the GEP instruction.
4562   Value *VarIdx = 0;
4563   std::vector<ConstantInt*> Indexes;
4564   unsigned VarIdxNum = 0;
4565   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4566     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4567       Indexes.push_back(CI);
4568     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4569       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
4570       VarIdx = GEP->getOperand(i);
4571       VarIdxNum = i-2;
4572       Indexes.push_back(0);
4573     }
4574
4575   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4576   // Check to see if X is a loop variant variable value now.
4577   const SCEV *Idx = getSCEV(VarIdx);
4578   Idx = getSCEVAtScope(Idx, L);
4579
4580   // We can only recognize very limited forms of loop index expressions, in
4581   // particular, only affine AddRec's like {C1,+,C2}.
4582   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4583   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
4584       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4585       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4586     return getCouldNotCompute();
4587
4588   unsigned MaxSteps = MaxBruteForceIterations;
4589   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4590     ConstantInt *ItCst = ConstantInt::get(
4591                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
4592     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4593
4594     // Form the GEP offset.
4595     Indexes[VarIdxNum] = Val;
4596
4597     Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4598     if (Result == 0) break;  // Cannot compute!
4599
4600     // Evaluate the condition for this iteration.
4601     Result = ConstantExpr::getICmp(predicate, Result, RHS);
4602     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
4603     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4604 #if 0
4605       dbgs() << "\n***\n*** Computed loop count " << *ItCst
4606              << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4607              << "***\n";
4608 #endif
4609       ++NumArrayLenItCounts;
4610       return getConstant(ItCst);   // Found terminating iteration!
4611     }
4612   }
4613   return getCouldNotCompute();
4614 }
4615
4616
4617 /// CanConstantFold - Return true if we can constant fold an instruction of the
4618 /// specified type, assuming that all operands were constants.
4619 static bool CanConstantFold(const Instruction *I) {
4620   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4621       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4622     return true;
4623
4624   if (const CallInst *CI = dyn_cast<CallInst>(I))
4625     if (const Function *F = CI->getCalledFunction())
4626       return canConstantFoldCallTo(F);
4627   return false;
4628 }
4629
4630 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4631 /// in the loop that V is derived from.  We allow arbitrary operations along the
4632 /// way, but the operands of an operation must either be constants or a value
4633 /// derived from a constant PHI.  If this expression does not fit with these
4634 /// constraints, return null.
4635 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4636   // If this is not an instruction, or if this is an instruction outside of the
4637   // loop, it can't be derived from a loop PHI.
4638   Instruction *I = dyn_cast<Instruction>(V);
4639   if (I == 0 || !L->contains(I)) return 0;
4640
4641   if (PHINode *PN = dyn_cast<PHINode>(I)) {
4642     if (L->getHeader() == I->getParent())
4643       return PN;
4644     else
4645       // We don't currently keep track of the control flow needed to evaluate
4646       // PHIs, so we cannot handle PHIs inside of loops.
4647       return 0;
4648   }
4649
4650   // If we won't be able to constant fold this expression even if the operands
4651   // are constants, return early.
4652   if (!CanConstantFold(I)) return 0;
4653
4654   // Otherwise, we can evaluate this instruction if all of its operands are
4655   // constant or derived from a PHI node themselves.
4656   PHINode *PHI = 0;
4657   for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4658     if (!isa<Constant>(I->getOperand(Op))) {
4659       PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4660       if (P == 0) return 0;  // Not evolving from PHI
4661       if (PHI == 0)
4662         PHI = P;
4663       else if (PHI != P)
4664         return 0;  // Evolving from multiple different PHIs.
4665     }
4666
4667   // This is a expression evolving from a constant PHI!
4668   return PHI;
4669 }
4670
4671 /// EvaluateExpression - Given an expression that passes the
4672 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4673 /// in the loop has the value PHIVal.  If we can't fold this expression for some
4674 /// reason, return null.
4675 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4676                                     const TargetData *TD) {
4677   if (isa<PHINode>(V)) return PHIVal;
4678   if (Constant *C = dyn_cast<Constant>(V)) return C;
4679   Instruction *I = cast<Instruction>(V);
4680
4681   std::vector<Constant*> Operands(I->getNumOperands());
4682
4683   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4684     Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4685     if (Operands[i] == 0) return 0;
4686   }
4687
4688   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4689     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4690                                            Operands[1], TD);
4691   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, TD);
4692 }
4693
4694 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4695 /// in the header of its containing loop, we know the loop executes a
4696 /// constant number of times, and the PHI node is just a recurrence
4697 /// involving constants, fold it.
4698 Constant *
4699 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4700                                                    const APInt &BEs,
4701                                                    const Loop *L) {
4702   DenseMap<PHINode*, Constant*>::const_iterator I =
4703     ConstantEvolutionLoopExitValue.find(PN);
4704   if (I != ConstantEvolutionLoopExitValue.end())
4705     return I->second;
4706
4707   if (BEs.ugt(MaxBruteForceIterations))
4708     return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
4709
4710   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4711
4712   // Since the loop is canonicalized, the PHI node must have two entries.  One
4713   // entry must be a constant (coming in from outside of the loop), and the
4714   // second must be derived from the same PHI.
4715   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4716   Constant *StartCST =
4717     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4718   if (StartCST == 0)
4719     return RetVal = 0;  // Must be a constant.
4720
4721   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4722   if (getConstantEvolvingPHI(BEValue, L) != PN &&
4723       !isa<Constant>(BEValue))
4724     return RetVal = 0;  // Not derived from same PHI.
4725
4726   // Execute the loop symbolically to determine the exit value.
4727   if (BEs.getActiveBits() >= 32)
4728     return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4729
4730   unsigned NumIterations = BEs.getZExtValue(); // must be in range
4731   unsigned IterationNum = 0;
4732   for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4733     if (IterationNum == NumIterations)
4734       return RetVal = PHIVal;  // Got exit value!
4735
4736     // Compute the value of the PHI node for the next iteration.
4737     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4738     if (NextPHI == PHIVal)
4739       return RetVal = NextPHI;  // Stopped evolving!
4740     if (NextPHI == 0)
4741       return 0;        // Couldn't evaluate!
4742     PHIVal = NextPHI;
4743   }
4744 }
4745
4746 /// ComputeExitCountExhaustively - If the loop is known to execute a
4747 /// constant number of times (the condition evolves only from constants),
4748 /// try to evaluate a few iterations of the loop until we get the exit
4749 /// condition gets a value of ExitWhen (true or false).  If we cannot
4750 /// evaluate the trip count of the loop, return getCouldNotCompute().
4751 const SCEV * ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
4752                                                            Value *Cond,
4753                                                            bool ExitWhen) {
4754   PHINode *PN = getConstantEvolvingPHI(Cond, L);
4755   if (PN == 0) return getCouldNotCompute();
4756
4757   // If the loop is canonicalized, the PHI will have exactly two entries.
4758   // That's the only form we support here.
4759   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4760
4761   // One entry must be a constant (coming in from outside of the loop), and the
4762   // second must be derived from the same PHI.
4763   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4764   Constant *StartCST =
4765     dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4766   if (StartCST == 0) return getCouldNotCompute();  // Must be a constant.
4767
4768   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4769   if (getConstantEvolvingPHI(BEValue, L) != PN &&
4770       !isa<Constant>(BEValue))
4771     return getCouldNotCompute();  // Not derived from same PHI.
4772
4773   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
4774   // the loop symbolically to determine when the condition gets a value of
4775   // "ExitWhen".
4776   unsigned IterationNum = 0;
4777   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
4778   for (Constant *PHIVal = StartCST;
4779        IterationNum != MaxIterations; ++IterationNum) {
4780     ConstantInt *CondVal =
4781       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4782
4783     // Couldn't symbolically evaluate.
4784     if (!CondVal) return getCouldNotCompute();
4785
4786     if (CondVal->getValue() == uint64_t(ExitWhen)) {
4787       ++NumBruteForceTripCountsComputed;
4788       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4789     }
4790
4791     // Compute the value of the PHI node for the next iteration.
4792     Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4793     if (NextPHI == 0 || NextPHI == PHIVal)
4794       return getCouldNotCompute();// Couldn't evaluate or not making progress...
4795     PHIVal = NextPHI;
4796   }
4797
4798   // Too many iterations were needed to evaluate.
4799   return getCouldNotCompute();
4800 }
4801
4802 /// getSCEVAtScope - Return a SCEV expression for the specified value
4803 /// at the specified scope in the program.  The L value specifies a loop
4804 /// nest to evaluate the expression at, where null is the top-level or a
4805 /// specified loop is immediately inside of the loop.
4806 ///
4807 /// This method can be used to compute the exit value for a variable defined
4808 /// in a loop by querying what the value will hold in the parent loop.
4809 ///
4810 /// In the case that a relevant loop exit value cannot be computed, the
4811 /// original value V is returned.
4812 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4813   // Check to see if we've folded this expression at this loop before.
4814   std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4815   std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4816     Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4817   if (!Pair.second)
4818     return Pair.first->second ? Pair.first->second : V;
4819
4820   // Otherwise compute it.
4821   const SCEV *C = computeSCEVAtScope(V, L);
4822   ValuesAtScopes[V][L] = C;
4823   return C;
4824 }
4825
4826 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4827   if (isa<SCEVConstant>(V)) return V;
4828
4829   // If this instruction is evolved from a constant-evolving PHI, compute the
4830   // exit value from the loop without using SCEVs.
4831   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4832     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4833       const Loop *LI = (*this->LI)[I->getParent()];
4834       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
4835         if (PHINode *PN = dyn_cast<PHINode>(I))
4836           if (PN->getParent() == LI->getHeader()) {
4837             // Okay, there is no closed form solution for the PHI node.  Check
4838             // to see if the loop that contains it has a known backedge-taken
4839             // count.  If so, we may be able to force computation of the exit
4840             // value.
4841             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4842             if (const SCEVConstant *BTCC =
4843                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4844               // Okay, we know how many times the containing loop executes.  If
4845               // this is a constant evolving PHI node, get the final value at
4846               // the specified iteration number.
4847               Constant *RV = getConstantEvolutionLoopExitValue(PN,
4848                                                    BTCC->getValue()->getValue(),
4849                                                                LI);
4850               if (RV) return getSCEV(RV);
4851             }
4852           }
4853
4854       // Okay, this is an expression that we cannot symbolically evaluate
4855       // into a SCEV.  Check to see if it's possible to symbolically evaluate
4856       // the arguments into constants, and if so, try to constant propagate the
4857       // result.  This is particularly useful for computing loop exit values.
4858       if (CanConstantFold(I)) {
4859         SmallVector<Constant *, 4> Operands;
4860         bool MadeImprovement = false;
4861         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4862           Value *Op = I->getOperand(i);
4863           if (Constant *C = dyn_cast<Constant>(Op)) {
4864             Operands.push_back(C);
4865             continue;
4866           }
4867
4868           // If any of the operands is non-constant and if they are
4869           // non-integer and non-pointer, don't even try to analyze them
4870           // with scev techniques.
4871           if (!isSCEVable(Op->getType()))
4872             return V;
4873
4874           const SCEV *OrigV = getSCEV(Op);
4875           const SCEV *OpV = getSCEVAtScope(OrigV, L);
4876           MadeImprovement |= OrigV != OpV;
4877
4878           Constant *C = 0;
4879           if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4880             C = SC->getValue();
4881           if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4882             C = dyn_cast<Constant>(SU->getValue());
4883           if (!C) return V;
4884           if (C->getType() != Op->getType())
4885             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4886                                                               Op->getType(),
4887                                                               false),
4888                                       C, Op->getType());
4889           Operands.push_back(C);
4890         }
4891
4892         // Check to see if getSCEVAtScope actually made an improvement.
4893         if (MadeImprovement) {
4894           Constant *C = 0;
4895           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4896             C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4897                                                 Operands[0], Operands[1], TD);
4898           else
4899             C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4900                                          Operands, TD);
4901           if (!C) return V;
4902           return getSCEV(C);
4903         }
4904       }
4905     }
4906
4907     // This is some other type of SCEVUnknown, just return it.
4908     return V;
4909   }
4910
4911   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4912     // Avoid performing the look-up in the common case where the specified
4913     // expression has no loop-variant portions.
4914     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4915       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4916       if (OpAtScope != Comm->getOperand(i)) {
4917         // Okay, at least one of these operands is loop variant but might be
4918         // foldable.  Build a new instance of the folded commutative expression.
4919         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4920                                             Comm->op_begin()+i);
4921         NewOps.push_back(OpAtScope);
4922
4923         for (++i; i != e; ++i) {
4924           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4925           NewOps.push_back(OpAtScope);
4926         }
4927         if (isa<SCEVAddExpr>(Comm))
4928           return getAddExpr(NewOps);
4929         if (isa<SCEVMulExpr>(Comm))
4930           return getMulExpr(NewOps);
4931         if (isa<SCEVSMaxExpr>(Comm))
4932           return getSMaxExpr(NewOps);
4933         if (isa<SCEVUMaxExpr>(Comm))
4934           return getUMaxExpr(NewOps);
4935         llvm_unreachable("Unknown commutative SCEV type!");
4936       }
4937     }
4938     // If we got here, all operands are loop invariant.
4939     return Comm;
4940   }
4941
4942   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4943     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4944     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4945     if (LHS == Div->getLHS() && RHS == Div->getRHS())
4946       return Div;   // must be loop invariant
4947     return getUDivExpr(LHS, RHS);
4948   }
4949
4950   // If this is a loop recurrence for a loop that does not contain L, then we
4951   // are dealing with the final value computed by the loop.
4952   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4953     // First, attempt to evaluate each operand.
4954     // Avoid performing the look-up in the common case where the specified
4955     // expression has no loop-variant portions.
4956     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4957       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4958       if (OpAtScope == AddRec->getOperand(i))
4959         continue;
4960
4961       // Okay, at least one of these operands is loop variant but might be
4962       // foldable.  Build a new instance of the folded commutative expression.
4963       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4964                                           AddRec->op_begin()+i);
4965       NewOps.push_back(OpAtScope);
4966       for (++i; i != e; ++i)
4967         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4968
4969       const SCEV *FoldedRec =
4970         getAddRecExpr(NewOps, AddRec->getLoop(),
4971                       AddRec->getNoWrapFlags(SCEV::FlagNW));
4972       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
4973       // The addrec may be folded to a nonrecurrence, for example, if the
4974       // induction variable is multiplied by zero after constant folding. Go
4975       // ahead and return the folded value.
4976       if (!AddRec)
4977         return FoldedRec;
4978       break;
4979     }
4980
4981     // If the scope is outside the addrec's loop, evaluate it by using the
4982     // loop exit value of the addrec.
4983     if (!AddRec->getLoop()->contains(L)) {
4984       // To evaluate this recurrence, we need to know how many times the AddRec
4985       // loop iterates.  Compute this now.
4986       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4987       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4988
4989       // Then, evaluate the AddRec.
4990       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4991     }
4992
4993     return AddRec;
4994   }
4995
4996   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4997     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4998     if (Op == Cast->getOperand())
4999       return Cast;  // must be loop invariant
5000     return getZeroExtendExpr(Op, Cast->getType());
5001   }
5002
5003   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
5004     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5005     if (Op == Cast->getOperand())
5006       return Cast;  // must be loop invariant
5007     return getSignExtendExpr(Op, Cast->getType());
5008   }
5009
5010   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
5011     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
5012     if (Op == Cast->getOperand())
5013       return Cast;  // must be loop invariant
5014     return getTruncateExpr(Op, Cast->getType());
5015   }
5016
5017   llvm_unreachable("Unknown SCEV type!");
5018   return 0;
5019 }
5020
5021 /// getSCEVAtScope - This is a convenience function which does
5022 /// getSCEVAtScope(getSCEV(V), L).
5023 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
5024   return getSCEVAtScope(getSCEV(V), L);
5025 }
5026
5027 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5028 /// following equation:
5029 ///
5030 ///     A * X = B (mod N)
5031 ///
5032 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5033 /// A and B isn't important.
5034 ///
5035 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
5036 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
5037                                                ScalarEvolution &SE) {
5038   uint32_t BW = A.getBitWidth();
5039   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5040   assert(A != 0 && "A must be non-zero.");
5041
5042   // 1. D = gcd(A, N)
5043   //
5044   // The gcd of A and N may have only one prime factor: 2. The number of
5045   // trailing zeros in A is its multiplicity
5046   uint32_t Mult2 = A.countTrailingZeros();
5047   // D = 2^Mult2
5048
5049   // 2. Check if B is divisible by D.
5050   //
5051   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5052   // is not less than multiplicity of this prime factor for D.
5053   if (B.countTrailingZeros() < Mult2)
5054     return SE.getCouldNotCompute();
5055
5056   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5057   // modulo (N / D).
5058   //
5059   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
5060   // bit width during computations.
5061   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
5062   APInt Mod(BW + 1, 0);
5063   Mod.setBit(BW - Mult2);  // Mod = N / D
5064   APInt I = AD.multiplicativeInverse(Mod);
5065
5066   // 4. Compute the minimum unsigned root of the equation:
5067   // I * (B / D) mod (N / D)
5068   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5069
5070   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5071   // bits.
5072   return SE.getConstant(Result.trunc(BW));
5073 }
5074
5075 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5076 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
5077 /// might be the same) or two SCEVCouldNotCompute objects.
5078 ///
5079 static std::pair<const SCEV *,const SCEV *>
5080 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
5081   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
5082   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5083   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5084   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
5085
5086   // We currently can only solve this if the coefficients are constants.
5087   if (!LC || !MC || !NC) {
5088     const SCEV *CNC = SE.getCouldNotCompute();
5089     return std::make_pair(CNC, CNC);
5090   }
5091
5092   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
5093   const APInt &L = LC->getValue()->getValue();
5094   const APInt &M = MC->getValue()->getValue();
5095   const APInt &N = NC->getValue()->getValue();
5096   APInt Two(BitWidth, 2);
5097   APInt Four(BitWidth, 4);
5098
5099   {
5100     using namespace APIntOps;
5101     const APInt& C = L;
5102     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5103     // The B coefficient is M-N/2
5104     APInt B(M);
5105     B -= sdiv(N,Two);
5106
5107     // The A coefficient is N/2
5108     APInt A(N.sdiv(Two));
5109
5110     // Compute the B^2-4ac term.
5111     APInt SqrtTerm(B);
5112     SqrtTerm *= B;
5113     SqrtTerm -= Four * (A * C);
5114
5115     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5116     // integer value or else APInt::sqrt() will assert.
5117     APInt SqrtVal(SqrtTerm.sqrt());
5118
5119     // Compute the two solutions for the quadratic formula.
5120     // The divisions must be performed as signed divisions.
5121     APInt NegB(-B);
5122     APInt TwoA(A << 1);
5123     if (TwoA.isMinValue()) {
5124       const SCEV *CNC = SE.getCouldNotCompute();
5125       return std::make_pair(CNC, CNC);
5126     }
5127
5128     LLVMContext &Context = SE.getContext();
5129
5130     ConstantInt *Solution1 =
5131       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
5132     ConstantInt *Solution2 =
5133       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
5134
5135     return std::make_pair(SE.getConstant(Solution1),
5136                           SE.getConstant(Solution2));
5137   } // end APIntOps namespace
5138 }
5139
5140 /// HowFarToZero - Return the number of times a backedge comparing the specified
5141 /// value to zero will execute.  If not computable, return CouldNotCompute.
5142 ///
5143 /// This is only used for loops with a "x != y" exit test. The exit condition is
5144 /// now expressed as a single expression, V = x-y. So the exit test is
5145 /// effectively V != 0.  We know and take advantage of the fact that this
5146 /// expression only being used in a comparison by zero context.
5147 ScalarEvolution::ExitLimit
5148 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
5149   // If the value is a constant
5150   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5151     // If the value is already zero, the branch will execute zero times.
5152     if (C->getValue()->isZero()) return C;
5153     return getCouldNotCompute();  // Otherwise it will loop infinitely.
5154   }
5155
5156   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
5157   if (!AddRec || AddRec->getLoop() != L)
5158     return getCouldNotCompute();
5159
5160   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
5161   // the quadratic equation to solve it.
5162   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
5163     std::pair<const SCEV *,const SCEV *> Roots =
5164       SolveQuadraticEquation(AddRec, *this);
5165     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5166     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5167     if (R1 && R2) {
5168 #if 0
5169       dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
5170              << "  sol#2: " << *R2 << "\n";
5171 #endif
5172       // Pick the smallest positive root value.
5173       if (ConstantInt *CB =
5174           dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
5175                                                       R1->getValue(),
5176                                                       R2->getValue()))) {
5177         if (CB->getZExtValue() == false)
5178           std::swap(R1, R2);   // R1 is the minimum root now.
5179
5180         // We can only use this value if the chrec ends up with an exact zero
5181         // value at this index.  When solving for "X*X != 5", for example, we
5182         // should not accept a root of 2.
5183         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
5184         if (Val->isZero())
5185           return R1;  // We found a quadratic root!
5186       }
5187     }
5188     return getCouldNotCompute();
5189   }
5190
5191   // Otherwise we can only handle this if it is affine.
5192   if (!AddRec->isAffine())
5193     return getCouldNotCompute();
5194
5195   // If this is an affine expression, the execution count of this branch is
5196   // the minimum unsigned root of the following equation:
5197   //
5198   //     Start + Step*N = 0 (mod 2^BW)
5199   //
5200   // equivalent to:
5201   //
5202   //             Step*N = -Start (mod 2^BW)
5203   //
5204   // where BW is the common bit width of Start and Step.
5205
5206   // Get the initial value for the loop.
5207   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
5208   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
5209
5210   // For now we handle only constant steps.
5211   //
5212   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
5213   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
5214   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
5215   // We have not yet seen any such cases.
5216   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
5217   if (StepC == 0)
5218     return getCouldNotCompute();
5219
5220   // For positive steps (counting up until unsigned overflow):
5221   //   N = -Start/Step (as unsigned)
5222   // For negative steps (counting down to zero):
5223   //   N = Start/-Step
5224   // First compute the unsigned distance from zero in the direction of Step.
5225   bool CountDown = StepC->getValue()->getValue().isNegative();
5226   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
5227
5228   // Handle unitary steps, which cannot wraparound.
5229   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
5230   //   N = Distance (as unsigned)
5231   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
5232     ConstantRange CR = getUnsignedRange(Start);
5233     const SCEV *MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
5234                                                    : ~CR.getUnsignedMin());
5235     return ExitLimit(Distance, MaxBECount);
5236   }
5237
5238   // If the recurrence is known not to wraparound, unsigned divide computes the
5239   // back edge count. We know that the value will either become zero (and thus
5240   // the loop terminates), that the loop will terminate through some other exit
5241   // condition first, or that the loop has undefined behavior.  This means
5242   // we can't "miss" the exit value, even with nonunit stride.
5243   //
5244   // FIXME: Prove that loops always exhibits *acceptable* undefined
5245   // behavior. Loops must exhibit defined behavior until a wrapped value is
5246   // actually used. So the trip count computed by udiv could be smaller than the
5247   // number of well-defined iterations.
5248   if (AddRec->getNoWrapFlags(SCEV::FlagNW))
5249     // FIXME: We really want an "isexact" bit for udiv.
5250     return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
5251
5252   // Then, try to solve the above equation provided that Start is constant.
5253   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
5254     return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
5255                                         -StartC->getValue()->getValue(),
5256                                         *this);
5257   return getCouldNotCompute();
5258 }
5259
5260 /// HowFarToNonZero - Return the number of times a backedge checking the
5261 /// specified value for nonzero will execute.  If not computable, return
5262 /// CouldNotCompute
5263 ScalarEvolution::ExitLimit
5264 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
5265   // Loops that look like: while (X == 0) are very strange indeed.  We don't
5266   // handle them yet except for the trivial case.  This could be expanded in the
5267   // future as needed.
5268
5269   // If the value is a constant, check to see if it is known to be non-zero
5270   // already.  If so, the backedge will execute zero times.
5271   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
5272     if (!C->getValue()->isNullValue())
5273       return getConstant(C->getType(), 0);
5274     return getCouldNotCompute();  // Otherwise it will loop infinitely.
5275   }
5276
5277   // We could implement others, but I really doubt anyone writes loops like
5278   // this, and if they did, they would already be constant folded.
5279   return getCouldNotCompute();
5280 }
5281
5282 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
5283 /// (which may not be an immediate predecessor) which has exactly one
5284 /// successor from which BB is reachable, or null if no such block is
5285 /// found.
5286 ///
5287 std::pair<BasicBlock *, BasicBlock *>
5288 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
5289   // If the block has a unique predecessor, then there is no path from the
5290   // predecessor to the block that does not go through the direct edge
5291   // from the predecessor to the block.
5292   if (BasicBlock *Pred = BB->getSinglePredecessor())
5293     return std::make_pair(Pred, BB);
5294
5295   // A loop's header is defined to be a block that dominates the loop.
5296   // If the header has a unique predecessor outside the loop, it must be
5297   // a block that has exactly one successor that can reach the loop.
5298   if (Loop *L = LI->getLoopFor(BB))
5299     return std::make_pair(L->getLoopPredecessor(), L->getHeader());
5300
5301   return std::pair<BasicBlock *, BasicBlock *>();
5302 }
5303
5304 /// HasSameValue - SCEV structural equivalence is usually sufficient for
5305 /// testing whether two expressions are equal, however for the purposes of
5306 /// looking for a condition guarding a loop, it can be useful to be a little
5307 /// more general, since a front-end may have replicated the controlling
5308 /// expression.
5309 ///
5310 static bool HasSameValue(const SCEV *A, const SCEV *B) {
5311   // Quick check to see if they are the same SCEV.
5312   if (A == B) return true;
5313
5314   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
5315   // two different instructions with the same value. Check for this case.
5316   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
5317     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
5318       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
5319         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
5320           if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
5321             return true;
5322
5323   // Otherwise assume they may have a different value.
5324   return false;
5325 }
5326
5327 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
5328 /// predicate Pred. Return true iff any changes were made.
5329 ///
5330 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
5331                                            const SCEV *&LHS, const SCEV *&RHS) {
5332   bool Changed = false;
5333
5334   // Canonicalize a constant to the right side.
5335   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
5336     // Check for both operands constant.
5337     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
5338       if (ConstantExpr::getICmp(Pred,
5339                                 LHSC->getValue(),
5340                                 RHSC->getValue())->isNullValue())
5341         goto trivially_false;
5342       else
5343         goto trivially_true;
5344     }
5345     // Otherwise swap the operands to put the constant on the right.
5346     std::swap(LHS, RHS);
5347     Pred = ICmpInst::getSwappedPredicate(Pred);
5348     Changed = true;
5349   }
5350
5351   // If we're comparing an addrec with a value which is loop-invariant in the
5352   // addrec's loop, put the addrec on the left. Also make a dominance check,
5353   // as both operands could be addrecs loop-invariant in each other's loop.
5354   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
5355     const Loop *L = AR->getLoop();
5356     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
5357       std::swap(LHS, RHS);
5358       Pred = ICmpInst::getSwappedPredicate(Pred);
5359       Changed = true;
5360     }
5361   }
5362
5363   // If there's a constant operand, canonicalize comparisons with boundary
5364   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
5365   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
5366     const APInt &RA = RC->getValue()->getValue();
5367     switch (Pred) {
5368     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5369     case ICmpInst::ICMP_EQ:
5370     case ICmpInst::ICMP_NE:
5371       break;
5372     case ICmpInst::ICMP_UGE:
5373       if ((RA - 1).isMinValue()) {
5374         Pred = ICmpInst::ICMP_NE;
5375         RHS = getConstant(RA - 1);
5376         Changed = true;
5377         break;
5378       }
5379       if (RA.isMaxValue()) {
5380         Pred = ICmpInst::ICMP_EQ;
5381         Changed = true;
5382         break;
5383       }
5384       if (RA.isMinValue()) goto trivially_true;
5385
5386       Pred = ICmpInst::ICMP_UGT;
5387       RHS = getConstant(RA - 1);
5388       Changed = true;
5389       break;
5390     case ICmpInst::ICMP_ULE:
5391       if ((RA + 1).isMaxValue()) {
5392         Pred = ICmpInst::ICMP_NE;
5393         RHS = getConstant(RA + 1);
5394         Changed = true;
5395         break;
5396       }
5397       if (RA.isMinValue()) {
5398         Pred = ICmpInst::ICMP_EQ;
5399         Changed = true;
5400         break;
5401       }
5402       if (RA.isMaxValue()) goto trivially_true;
5403
5404       Pred = ICmpInst::ICMP_ULT;
5405       RHS = getConstant(RA + 1);
5406       Changed = true;
5407       break;
5408     case ICmpInst::ICMP_SGE:
5409       if ((RA - 1).isMinSignedValue()) {
5410         Pred = ICmpInst::ICMP_NE;
5411         RHS = getConstant(RA - 1);
5412         Changed = true;
5413         break;
5414       }
5415       if (RA.isMaxSignedValue()) {
5416         Pred = ICmpInst::ICMP_EQ;
5417         Changed = true;
5418         break;
5419       }
5420       if (RA.isMinSignedValue()) goto trivially_true;
5421
5422       Pred = ICmpInst::ICMP_SGT;
5423       RHS = getConstant(RA - 1);
5424       Changed = true;
5425       break;
5426     case ICmpInst::ICMP_SLE:
5427       if ((RA + 1).isMaxSignedValue()) {
5428         Pred = ICmpInst::ICMP_NE;
5429         RHS = getConstant(RA + 1);
5430         Changed = true;
5431         break;
5432       }
5433       if (RA.isMinSignedValue()) {
5434         Pred = ICmpInst::ICMP_EQ;
5435         Changed = true;
5436         break;
5437       }
5438       if (RA.isMaxSignedValue()) goto trivially_true;
5439
5440       Pred = ICmpInst::ICMP_SLT;
5441       RHS = getConstant(RA + 1);
5442       Changed = true;
5443       break;
5444     case ICmpInst::ICMP_UGT:
5445       if (RA.isMinValue()) {
5446         Pred = ICmpInst::ICMP_NE;
5447         Changed = true;
5448         break;
5449       }
5450       if ((RA + 1).isMaxValue()) {
5451         Pred = ICmpInst::ICMP_EQ;
5452         RHS = getConstant(RA + 1);
5453         Changed = true;
5454         break;
5455       }
5456       if (RA.isMaxValue()) goto trivially_false;
5457       break;
5458     case ICmpInst::ICMP_ULT:
5459       if (RA.isMaxValue()) {
5460         Pred = ICmpInst::ICMP_NE;
5461         Changed = true;
5462         break;
5463       }
5464       if ((RA - 1).isMinValue()) {
5465         Pred = ICmpInst::ICMP_EQ;
5466         RHS = getConstant(RA - 1);
5467         Changed = true;
5468         break;
5469       }
5470       if (RA.isMinValue()) goto trivially_false;
5471       break;
5472     case ICmpInst::ICMP_SGT:
5473       if (RA.isMinSignedValue()) {
5474         Pred = ICmpInst::ICMP_NE;
5475         Changed = true;
5476         break;
5477       }
5478       if ((RA + 1).isMaxSignedValue()) {
5479         Pred = ICmpInst::ICMP_EQ;
5480         RHS = getConstant(RA + 1);
5481         Changed = true;
5482         break;
5483       }
5484       if (RA.isMaxSignedValue()) goto trivially_false;
5485       break;
5486     case ICmpInst::ICMP_SLT:
5487       if (RA.isMaxSignedValue()) {
5488         Pred = ICmpInst::ICMP_NE;
5489         Changed = true;
5490         break;
5491       }
5492       if ((RA - 1).isMinSignedValue()) {
5493        Pred = ICmpInst::ICMP_EQ;
5494        RHS = getConstant(RA - 1);
5495         Changed = true;
5496        break;
5497       }
5498       if (RA.isMinSignedValue()) goto trivially_false;
5499       break;
5500     }
5501   }
5502
5503   // Check for obvious equality.
5504   if (HasSameValue(LHS, RHS)) {
5505     if (ICmpInst::isTrueWhenEqual(Pred))
5506       goto trivially_true;
5507     if (ICmpInst::isFalseWhenEqual(Pred))
5508       goto trivially_false;
5509   }
5510
5511   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5512   // adding or subtracting 1 from one of the operands.
5513   switch (Pred) {
5514   case ICmpInst::ICMP_SLE:
5515     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5516       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5517                        SCEV::FlagNSW);
5518       Pred = ICmpInst::ICMP_SLT;
5519       Changed = true;
5520     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5521       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5522                        SCEV::FlagNSW);
5523       Pred = ICmpInst::ICMP_SLT;
5524       Changed = true;
5525     }
5526     break;
5527   case ICmpInst::ICMP_SGE:
5528     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5529       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5530                        SCEV::FlagNSW);
5531       Pred = ICmpInst::ICMP_SGT;
5532       Changed = true;
5533     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5534       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5535                        SCEV::FlagNSW);
5536       Pred = ICmpInst::ICMP_SGT;
5537       Changed = true;
5538     }
5539     break;
5540   case ICmpInst::ICMP_ULE:
5541     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5542       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5543                        SCEV::FlagNUW);
5544       Pred = ICmpInst::ICMP_ULT;
5545       Changed = true;
5546     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5547       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5548                        SCEV::FlagNUW);
5549       Pred = ICmpInst::ICMP_ULT;
5550       Changed = true;
5551     }
5552     break;
5553   case ICmpInst::ICMP_UGE:
5554     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5555       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5556                        SCEV::FlagNUW);
5557       Pred = ICmpInst::ICMP_UGT;
5558       Changed = true;
5559     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5560       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5561                        SCEV::FlagNUW);
5562       Pred = ICmpInst::ICMP_UGT;
5563       Changed = true;
5564     }
5565     break;
5566   default:
5567     break;
5568   }
5569
5570   // TODO: More simplifications are possible here.
5571
5572   return Changed;
5573
5574 trivially_true:
5575   // Return 0 == 0.
5576   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5577   Pred = ICmpInst::ICMP_EQ;
5578   return true;
5579
5580 trivially_false:
5581   // Return 0 != 0.
5582   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
5583   Pred = ICmpInst::ICMP_NE;
5584   return true;
5585 }
5586
5587 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5588   return getSignedRange(S).getSignedMax().isNegative();
5589 }
5590
5591 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5592   return getSignedRange(S).getSignedMin().isStrictlyPositive();
5593 }
5594
5595 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5596   return !getSignedRange(S).getSignedMin().isNegative();
5597 }
5598
5599 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5600   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5601 }
5602
5603 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5604   return isKnownNegative(S) || isKnownPositive(S);
5605 }
5606
5607 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5608                                        const SCEV *LHS, const SCEV *RHS) {
5609   // Canonicalize the inputs first.
5610   (void)SimplifyICmpOperands(Pred, LHS, RHS);
5611
5612   // If LHS or RHS is an addrec, check to see if the condition is true in
5613   // every iteration of the loop.
5614   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5615     if (isLoopEntryGuardedByCond(
5616           AR->getLoop(), Pred, AR->getStart(), RHS) &&
5617         isLoopBackedgeGuardedByCond(
5618           AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5619       return true;
5620   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5621     if (isLoopEntryGuardedByCond(
5622           AR->getLoop(), Pred, LHS, AR->getStart()) &&
5623         isLoopBackedgeGuardedByCond(
5624           AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5625       return true;
5626
5627   // Otherwise see what can be done with known constant ranges.
5628   return isKnownPredicateWithRanges(Pred, LHS, RHS);
5629 }
5630
5631 bool
5632 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5633                                             const SCEV *LHS, const SCEV *RHS) {
5634   if (HasSameValue(LHS, RHS))
5635     return ICmpInst::isTrueWhenEqual(Pred);
5636
5637   // This code is split out from isKnownPredicate because it is called from
5638   // within isLoopEntryGuardedByCond.
5639   switch (Pred) {
5640   default:
5641     llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5642     break;
5643   case ICmpInst::ICMP_SGT:
5644     Pred = ICmpInst::ICMP_SLT;
5645     std::swap(LHS, RHS);
5646   case ICmpInst::ICMP_SLT: {
5647     ConstantRange LHSRange = getSignedRange(LHS);
5648     ConstantRange RHSRange = getSignedRange(RHS);
5649     if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5650       return true;
5651     if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5652       return false;
5653     break;
5654   }
5655   case ICmpInst::ICMP_SGE:
5656     Pred = ICmpInst::ICMP_SLE;
5657     std::swap(LHS, RHS);
5658   case ICmpInst::ICMP_SLE: {
5659     ConstantRange LHSRange = getSignedRange(LHS);
5660     ConstantRange RHSRange = getSignedRange(RHS);
5661     if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5662       return true;
5663     if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5664       return false;
5665     break;
5666   }
5667   case ICmpInst::ICMP_UGT:
5668     Pred = ICmpInst::ICMP_ULT;
5669     std::swap(LHS, RHS);
5670   case ICmpInst::ICMP_ULT: {
5671     ConstantRange LHSRange = getUnsignedRange(LHS);
5672     ConstantRange RHSRange = getUnsignedRange(RHS);
5673     if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5674       return true;
5675     if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5676       return false;
5677     break;
5678   }
5679   case ICmpInst::ICMP_UGE:
5680     Pred = ICmpInst::ICMP_ULE;
5681     std::swap(LHS, RHS);
5682   case ICmpInst::ICMP_ULE: {
5683     ConstantRange LHSRange = getUnsignedRange(LHS);
5684     ConstantRange RHSRange = getUnsignedRange(RHS);
5685     if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5686       return true;
5687     if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5688       return false;
5689     break;
5690   }
5691   case ICmpInst::ICMP_NE: {
5692     if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5693       return true;
5694     if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5695       return true;
5696
5697     const SCEV *Diff = getMinusSCEV(LHS, RHS);
5698     if (isKnownNonZero(Diff))
5699       return true;
5700     break;
5701   }
5702   case ICmpInst::ICMP_EQ:
5703     // The check at the top of the function catches the case where
5704     // the values are known to be equal.
5705     break;
5706   }
5707   return false;
5708 }
5709
5710 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5711 /// protected by a conditional between LHS and RHS.  This is used to
5712 /// to eliminate casts.
5713 bool
5714 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5715                                              ICmpInst::Predicate Pred,
5716                                              const SCEV *LHS, const SCEV *RHS) {
5717   // Interpret a null as meaning no loop, where there is obviously no guard
5718   // (interprocedural conditions notwithstanding).
5719   if (!L) return true;
5720
5721   BasicBlock *Latch = L->getLoopLatch();
5722   if (!Latch)
5723     return false;
5724
5725   BranchInst *LoopContinuePredicate =
5726     dyn_cast<BranchInst>(Latch->getTerminator());
5727   if (!LoopContinuePredicate ||
5728       LoopContinuePredicate->isUnconditional())
5729     return false;
5730
5731   return isImpliedCond(Pred, LHS, RHS,
5732                        LoopContinuePredicate->getCondition(),
5733                        LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5734 }
5735
5736 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5737 /// by a conditional between LHS and RHS.  This is used to help avoid max
5738 /// expressions in loop trip counts, and to eliminate casts.
5739 bool
5740 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5741                                           ICmpInst::Predicate Pred,
5742                                           const SCEV *LHS, const SCEV *RHS) {
5743   // Interpret a null as meaning no loop, where there is obviously no guard
5744   // (interprocedural conditions notwithstanding).
5745   if (!L) return false;
5746
5747   // Starting at the loop predecessor, climb up the predecessor chain, as long
5748   // as there are predecessors that can be found that have unique successors
5749   // leading to the original header.
5750   for (std::pair<BasicBlock *, BasicBlock *>
5751          Pair(L->getLoopPredecessor(), L->getHeader());
5752        Pair.first;
5753        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5754
5755     BranchInst *LoopEntryPredicate =
5756       dyn_cast<BranchInst>(Pair.first->getTerminator());
5757     if (!LoopEntryPredicate ||
5758         LoopEntryPredicate->isUnconditional())
5759       continue;
5760
5761     if (isImpliedCond(Pred, LHS, RHS,
5762                       LoopEntryPredicate->getCondition(),
5763                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
5764       return true;
5765   }
5766
5767   return false;
5768 }
5769
5770 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5771 /// and RHS is true whenever the given Cond value evaluates to true.
5772 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5773                                     const SCEV *LHS, const SCEV *RHS,
5774                                     Value *FoundCondValue,
5775                                     bool Inverse) {
5776   // Recursively handle And and Or conditions.
5777   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5778     if (BO->getOpcode() == Instruction::And) {
5779       if (!Inverse)
5780         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5781                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5782     } else if (BO->getOpcode() == Instruction::Or) {
5783       if (Inverse)
5784         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5785                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5786     }
5787   }
5788
5789   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5790   if (!ICI) return false;
5791
5792   // Bail if the ICmp's operands' types are wider than the needed type
5793   // before attempting to call getSCEV on them. This avoids infinite
5794   // recursion, since the analysis of widening casts can require loop
5795   // exit condition information for overflow checking, which would
5796   // lead back here.
5797   if (getTypeSizeInBits(LHS->getType()) <
5798       getTypeSizeInBits(ICI->getOperand(0)->getType()))
5799     return false;
5800
5801   // Now that we found a conditional branch that dominates the loop, check to
5802   // see if it is the comparison we are looking for.
5803   ICmpInst::Predicate FoundPred;
5804   if (Inverse)
5805     FoundPred = ICI->getInversePredicate();
5806   else
5807     FoundPred = ICI->getPredicate();
5808
5809   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5810   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5811
5812   // Balance the types. The case where FoundLHS' type is wider than
5813   // LHS' type is checked for above.
5814   if (getTypeSizeInBits(LHS->getType()) >
5815       getTypeSizeInBits(FoundLHS->getType())) {
5816     if (CmpInst::isSigned(Pred)) {
5817       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5818       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5819     } else {
5820       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5821       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5822     }
5823   }
5824
5825   // Canonicalize the query to match the way instcombine will have
5826   // canonicalized the comparison.
5827   if (SimplifyICmpOperands(Pred, LHS, RHS))
5828     if (LHS == RHS)
5829       return CmpInst::isTrueWhenEqual(Pred);
5830   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5831     if (FoundLHS == FoundRHS)
5832       return CmpInst::isFalseWhenEqual(Pred);
5833
5834   // Check to see if we can make the LHS or RHS match.
5835   if (LHS == FoundRHS || RHS == FoundLHS) {
5836     if (isa<SCEVConstant>(RHS)) {
5837       std::swap(FoundLHS, FoundRHS);
5838       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5839     } else {
5840       std::swap(LHS, RHS);
5841       Pred = ICmpInst::getSwappedPredicate(Pred);
5842     }
5843   }
5844
5845   // Check whether the found predicate is the same as the desired predicate.
5846   if (FoundPred == Pred)
5847     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5848
5849   // Check whether swapping the found predicate makes it the same as the
5850   // desired predicate.
5851   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5852     if (isa<SCEVConstant>(RHS))
5853       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5854     else
5855       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5856                                    RHS, LHS, FoundLHS, FoundRHS);
5857   }
5858
5859   // Check whether the actual condition is beyond sufficient.
5860   if (FoundPred == ICmpInst::ICMP_EQ)
5861     if (ICmpInst::isTrueWhenEqual(Pred))
5862       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5863         return true;
5864   if (Pred == ICmpInst::ICMP_NE)
5865     if (!ICmpInst::isTrueWhenEqual(FoundPred))
5866       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5867         return true;
5868
5869   // Otherwise assume the worst.
5870   return false;
5871 }
5872
5873 /// isImpliedCondOperands - Test whether the condition described by Pred,
5874 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5875 /// and FoundRHS is true.
5876 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5877                                             const SCEV *LHS, const SCEV *RHS,
5878                                             const SCEV *FoundLHS,
5879                                             const SCEV *FoundRHS) {
5880   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5881                                      FoundLHS, FoundRHS) ||
5882          // ~x < ~y --> x > y
5883          isImpliedCondOperandsHelper(Pred, LHS, RHS,
5884                                      getNotSCEV(FoundRHS),
5885                                      getNotSCEV(FoundLHS));
5886 }
5887
5888 /// isImpliedCondOperandsHelper - Test whether the condition described by
5889 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5890 /// FoundLHS, and FoundRHS is true.
5891 bool
5892 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5893                                              const SCEV *LHS, const SCEV *RHS,
5894                                              const SCEV *FoundLHS,
5895                                              const SCEV *FoundRHS) {
5896   switch (Pred) {
5897   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5898   case ICmpInst::ICMP_EQ:
5899   case ICmpInst::ICMP_NE:
5900     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5901       return true;
5902     break;
5903   case ICmpInst::ICMP_SLT:
5904   case ICmpInst::ICMP_SLE:
5905     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5906         isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5907       return true;
5908     break;
5909   case ICmpInst::ICMP_SGT:
5910   case ICmpInst::ICMP_SGE:
5911     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5912         isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5913       return true;
5914     break;
5915   case ICmpInst::ICMP_ULT:
5916   case ICmpInst::ICMP_ULE:
5917     if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5918         isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5919       return true;
5920     break;
5921   case ICmpInst::ICMP_UGT:
5922   case ICmpInst::ICMP_UGE:
5923     if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5924         isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5925       return true;
5926     break;
5927   }
5928
5929   return false;
5930 }
5931
5932 /// getBECount - Subtract the end and start values and divide by the step,
5933 /// rounding up, to get the number of times the backedge is executed. Return
5934 /// CouldNotCompute if an intermediate computation overflows.
5935 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5936                                         const SCEV *End,
5937                                         const SCEV *Step,
5938                                         bool NoWrap) {
5939   assert(!isKnownNegative(Step) &&
5940          "This code doesn't handle negative strides yet!");
5941
5942   Type *Ty = Start->getType();
5943
5944   // When Start == End, we have an exact BECount == 0. Short-circuit this case
5945   // here because SCEV may not be able to determine that the unsigned division
5946   // after rounding is zero.
5947   if (Start == End)
5948     return getConstant(Ty, 0);
5949
5950   const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5951   const SCEV *Diff = getMinusSCEV(End, Start);
5952   const SCEV *RoundUp = getAddExpr(Step, NegOne);
5953
5954   // Add an adjustment to the difference between End and Start so that
5955   // the division will effectively round up.
5956   const SCEV *Add = getAddExpr(Diff, RoundUp);
5957
5958   if (!NoWrap) {
5959     // Check Add for unsigned overflow.
5960     // TODO: More sophisticated things could be done here.
5961     Type *WideTy = IntegerType::get(getContext(),
5962                                           getTypeSizeInBits(Ty) + 1);
5963     const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5964     const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5965     const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5966     if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5967       return getCouldNotCompute();
5968   }
5969
5970   return getUDivExpr(Add, Step);
5971 }
5972
5973 /// HowManyLessThans - Return the number of times a backedge containing the
5974 /// specified less-than comparison will execute.  If not computable, return
5975 /// CouldNotCompute.
5976 ScalarEvolution::ExitLimit
5977 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5978                                   const Loop *L, bool isSigned) {
5979   // Only handle:  "ADDREC < LoopInvariant".
5980   if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
5981
5982   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5983   if (!AddRec || AddRec->getLoop() != L)
5984     return getCouldNotCompute();
5985
5986   // Check to see if we have a flag which makes analysis easy.
5987   bool NoWrap = isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
5988                            AddRec->getNoWrapFlags(SCEV::FlagNUW);
5989
5990   if (AddRec->isAffine()) {
5991     unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5992     const SCEV *Step = AddRec->getStepRecurrence(*this);
5993
5994     if (Step->isZero())
5995       return getCouldNotCompute();
5996     if (Step->isOne()) {
5997       // With unit stride, the iteration never steps past the limit value.
5998     } else if (isKnownPositive(Step)) {
5999       // Test whether a positive iteration can step past the limit
6000       // value and past the maximum value for its type in a single step.
6001       // Note that it's not sufficient to check NoWrap here, because even
6002       // though the value after a wrap is undefined, it's not undefined
6003       // behavior, so if wrap does occur, the loop could either terminate or
6004       // loop infinitely, but in either case, the loop is guaranteed to
6005       // iterate at least until the iteration where the wrapping occurs.
6006       const SCEV *One = getConstant(Step->getType(), 1);
6007       if (isSigned) {
6008         APInt Max = APInt::getSignedMaxValue(BitWidth);
6009         if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
6010               .slt(getSignedRange(RHS).getSignedMax()))
6011           return getCouldNotCompute();
6012       } else {
6013         APInt Max = APInt::getMaxValue(BitWidth);
6014         if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
6015               .ult(getUnsignedRange(RHS).getUnsignedMax()))
6016           return getCouldNotCompute();
6017       }
6018     } else
6019       // TODO: Handle negative strides here and below.
6020       return getCouldNotCompute();
6021
6022     // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
6023     // m.  So, we count the number of iterations in which {n,+,s} < m is true.
6024     // Note that we cannot simply return max(m-n,0)/s because it's not safe to
6025     // treat m-n as signed nor unsigned due to overflow possibility.
6026
6027     // First, we get the value of the LHS in the first iteration: n
6028     const SCEV *Start = AddRec->getOperand(0);
6029
6030     // Determine the minimum constant start value.
6031     const SCEV *MinStart = getConstant(isSigned ?
6032       getSignedRange(Start).getSignedMin() :
6033       getUnsignedRange(Start).getUnsignedMin());
6034
6035     // If we know that the condition is true in order to enter the loop,
6036     // then we know that it will run exactly (m-n)/s times. Otherwise, we
6037     // only know that it will execute (max(m,n)-n)/s times. In both cases,
6038     // the division must round up.
6039     const SCEV *End = RHS;
6040     if (!isLoopEntryGuardedByCond(L,
6041                                   isSigned ? ICmpInst::ICMP_SLT :
6042                                              ICmpInst::ICMP_ULT,
6043                                   getMinusSCEV(Start, Step), RHS))
6044       End = isSigned ? getSMaxExpr(RHS, Start)
6045                      : getUMaxExpr(RHS, Start);
6046
6047     // Determine the maximum constant end value.
6048     const SCEV *MaxEnd = getConstant(isSigned ?
6049       getSignedRange(End).getSignedMax() :
6050       getUnsignedRange(End).getUnsignedMax());
6051
6052     // If MaxEnd is within a step of the maximum integer value in its type,
6053     // adjust it down to the minimum value which would produce the same effect.
6054     // This allows the subsequent ceiling division of (N+(step-1))/step to
6055     // compute the correct value.
6056     const SCEV *StepMinusOne = getMinusSCEV(Step,
6057                                             getConstant(Step->getType(), 1));
6058     MaxEnd = isSigned ?
6059       getSMinExpr(MaxEnd,
6060                   getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
6061                                StepMinusOne)) :
6062       getUMinExpr(MaxEnd,
6063                   getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
6064                                StepMinusOne));
6065
6066     // Finally, we subtract these two values and divide, rounding up, to get
6067     // the number of times the backedge is executed.
6068     const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
6069
6070     // The maximum backedge count is similar, except using the minimum start
6071     // value and the maximum end value.
6072     // If we already have an exact constant BECount, use it instead.
6073     const SCEV *MaxBECount = isa<SCEVConstant>(BECount) ? BECount
6074       : getBECount(MinStart, MaxEnd, Step, NoWrap);
6075
6076     // If the stride is nonconstant, and NoWrap == true, then
6077     // getBECount(MinStart, MaxEnd) may not compute. This would result in an
6078     // exact BECount and invalid MaxBECount, which should be avoided to catch
6079     // more optimization opportunities.
6080     if (isa<SCEVCouldNotCompute>(MaxBECount))
6081       MaxBECount = BECount;
6082
6083     return ExitLimit(BECount, MaxBECount);
6084   }
6085
6086   return getCouldNotCompute();
6087 }
6088
6089 /// getNumIterationsInRange - Return the number of iterations of this loop that
6090 /// produce values in the specified constant range.  Another way of looking at
6091 /// this is that it returns the first iteration number where the value is not in
6092 /// the condition, thus computing the exit count. If the iteration count can't
6093 /// be computed, an instance of SCEVCouldNotCompute is returned.
6094 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
6095                                                     ScalarEvolution &SE) const {
6096   if (Range.isFullSet())  // Infinite loop.
6097     return SE.getCouldNotCompute();
6098
6099   // If the start is a non-zero constant, shift the range to simplify things.
6100   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
6101     if (!SC->getValue()->isZero()) {
6102       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
6103       Operands[0] = SE.getConstant(SC->getType(), 0);
6104       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
6105                                              getNoWrapFlags(FlagNW));
6106       if (const SCEVAddRecExpr *ShiftedAddRec =
6107             dyn_cast<SCEVAddRecExpr>(Shifted))
6108         return ShiftedAddRec->getNumIterationsInRange(
6109                            Range.subtract(SC->getValue()->getValue()), SE);
6110       // This is strange and shouldn't happen.
6111       return SE.getCouldNotCompute();
6112     }
6113
6114   // The only time we can solve this is when we have all constant indices.
6115   // Otherwise, we cannot determine the overflow conditions.
6116   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6117     if (!isa<SCEVConstant>(getOperand(i)))
6118       return SE.getCouldNotCompute();
6119
6120
6121   // Okay at this point we know that all elements of the chrec are constants and
6122   // that the start element is zero.
6123
6124   // First check to see if the range contains zero.  If not, the first
6125   // iteration exits.
6126   unsigned BitWidth = SE.getTypeSizeInBits(getType());
6127   if (!Range.contains(APInt(BitWidth, 0)))
6128     return SE.getConstant(getType(), 0);
6129
6130   if (isAffine()) {
6131     // If this is an affine expression then we have this situation:
6132     //   Solve {0,+,A} in Range  ===  Ax in Range
6133
6134     // We know that zero is in the range.  If A is positive then we know that
6135     // the upper value of the range must be the first possible exit value.
6136     // If A is negative then the lower of the range is the last possible loop
6137     // value.  Also note that we already checked for a full range.
6138     APInt One(BitWidth,1);
6139     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
6140     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
6141
6142     // The exit value should be (End+A)/A.
6143     APInt ExitVal = (End + A).udiv(A);
6144     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
6145
6146     // Evaluate at the exit value.  If we really did fall out of the valid
6147     // range, then we computed our trip count, otherwise wrap around or other
6148     // things must have happened.
6149     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
6150     if (Range.contains(Val->getValue()))
6151       return SE.getCouldNotCompute();  // Something strange happened
6152
6153     // Ensure that the previous value is in the range.  This is a sanity check.
6154     assert(Range.contains(
6155            EvaluateConstantChrecAtConstant(this,
6156            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
6157            "Linear scev computation is off in a bad way!");
6158     return SE.getConstant(ExitValue);
6159   } else if (isQuadratic()) {
6160     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
6161     // quadratic equation to solve it.  To do this, we must frame our problem in
6162     // terms of figuring out when zero is crossed, instead of when
6163     // Range.getUpper() is crossed.
6164     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
6165     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
6166     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
6167                                              // getNoWrapFlags(FlagNW)
6168                                              FlagAnyWrap);
6169
6170     // Next, solve the constructed addrec
6171     std::pair<const SCEV *,const SCEV *> Roots =
6172       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
6173     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
6174     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
6175     if (R1) {
6176       // Pick the smallest positive root value.
6177       if (ConstantInt *CB =
6178           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
6179                          R1->getValue(), R2->getValue()))) {
6180         if (CB->getZExtValue() == false)
6181           std::swap(R1, R2);   // R1 is the minimum root now.
6182
6183         // Make sure the root is not off by one.  The returned iteration should
6184         // not be in the range, but the previous one should be.  When solving
6185         // for "X*X < 5", for example, we should not return a root of 2.
6186         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
6187                                                              R1->getValue(),
6188                                                              SE);
6189         if (Range.contains(R1Val->getValue())) {
6190           // The next iteration must be out of the range...
6191           ConstantInt *NextVal =
6192                 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
6193
6194           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
6195           if (!Range.contains(R1Val->getValue()))
6196             return SE.getConstant(NextVal);
6197           return SE.getCouldNotCompute();  // Something strange happened
6198         }
6199
6200         // If R1 was not in the range, then it is a good return value.  Make
6201         // sure that R1-1 WAS in the range though, just in case.
6202         ConstantInt *NextVal =
6203                ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
6204         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
6205         if (Range.contains(R1Val->getValue()))
6206           return R1;
6207         return SE.getCouldNotCompute();  // Something strange happened
6208       }
6209     }
6210   }
6211
6212   return SE.getCouldNotCompute();
6213 }
6214
6215
6216
6217 //===----------------------------------------------------------------------===//
6218 //                   SCEVCallbackVH Class Implementation
6219 //===----------------------------------------------------------------------===//
6220
6221 void ScalarEvolution::SCEVCallbackVH::deleted() {
6222   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
6223   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
6224     SE->ConstantEvolutionLoopExitValue.erase(PN);
6225   SE->ValueExprMap.erase(getValPtr());
6226   // this now dangles!
6227 }
6228
6229 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
6230   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
6231
6232   // Forget all the expressions associated with users of the old value,
6233   // so that future queries will recompute the expressions using the new
6234   // value.
6235   Value *Old = getValPtr();
6236   SmallVector<User *, 16> Worklist;
6237   SmallPtrSet<User *, 8> Visited;
6238   for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
6239        UI != UE; ++UI)
6240     Worklist.push_back(*UI);
6241   while (!Worklist.empty()) {
6242     User *U = Worklist.pop_back_val();
6243     // Deleting the Old value will cause this to dangle. Postpone
6244     // that until everything else is done.
6245     if (U == Old)
6246       continue;
6247     if (!Visited.insert(U))
6248       continue;
6249     if (PHINode *PN = dyn_cast<PHINode>(U))
6250       SE->ConstantEvolutionLoopExitValue.erase(PN);
6251     SE->ValueExprMap.erase(U);
6252     for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
6253          UI != UE; ++UI)
6254       Worklist.push_back(*UI);
6255   }
6256   // Delete the Old value.
6257   if (PHINode *PN = dyn_cast<PHINode>(Old))
6258     SE->ConstantEvolutionLoopExitValue.erase(PN);
6259   SE->ValueExprMap.erase(Old);
6260   // this now dangles!
6261 }
6262
6263 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
6264   : CallbackVH(V), SE(se) {}
6265
6266 //===----------------------------------------------------------------------===//
6267 //                   ScalarEvolution Class Implementation
6268 //===----------------------------------------------------------------------===//
6269
6270 ScalarEvolution::ScalarEvolution()
6271   : FunctionPass(ID), FirstUnknown(0) {
6272   initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
6273 }
6274
6275 bool ScalarEvolution::runOnFunction(Function &F) {
6276   this->F = &F;
6277   LI = &getAnalysis<LoopInfo>();
6278   TD = getAnalysisIfAvailable<TargetData>();
6279   DT = &getAnalysis<DominatorTree>();
6280   return false;
6281 }
6282
6283 void ScalarEvolution::releaseMemory() {
6284   // Iterate through all the SCEVUnknown instances and call their
6285   // destructors, so that they release their references to their values.
6286   for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
6287     U->~SCEVUnknown();
6288   FirstUnknown = 0;
6289
6290   ValueExprMap.clear();
6291
6292   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
6293   // that a loop had multiple computable exits.
6294   for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
6295          BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
6296        I != E; ++I) {
6297     I->second.clear();
6298   }
6299
6300   BackedgeTakenCounts.clear();
6301   ConstantEvolutionLoopExitValue.clear();
6302   ValuesAtScopes.clear();
6303   LoopDispositions.clear();
6304   BlockDispositions.clear();
6305   UnsignedRanges.clear();
6306   SignedRanges.clear();
6307   UniqueSCEVs.clear();
6308   SCEVAllocator.Reset();
6309 }
6310
6311 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
6312   AU.setPreservesAll();
6313   AU.addRequiredTransitive<LoopInfo>();
6314   AU.addRequiredTransitive<DominatorTree>();
6315 }
6316
6317 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
6318   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
6319 }
6320
6321 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
6322                           const Loop *L) {
6323   // Print all inner loops first
6324   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
6325     PrintLoopInfo(OS, SE, *I);
6326
6327   OS << "Loop ";
6328   WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6329   OS << ": ";
6330
6331   SmallVector<BasicBlock *, 8> ExitBlocks;
6332   L->getExitBlocks(ExitBlocks);
6333   if (ExitBlocks.size() != 1)
6334     OS << "<multiple exits> ";
6335
6336   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
6337     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
6338   } else {
6339     OS << "Unpredictable backedge-taken count. ";
6340   }
6341
6342   OS << "\n"
6343         "Loop ";
6344   WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
6345   OS << ": ";
6346
6347   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
6348     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
6349   } else {
6350     OS << "Unpredictable max backedge-taken count. ";
6351   }
6352
6353   OS << "\n";
6354 }
6355
6356 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
6357   // ScalarEvolution's implementation of the print method is to print
6358   // out SCEV values of all instructions that are interesting. Doing
6359   // this potentially causes it to create new SCEV objects though,
6360   // which technically conflicts with the const qualifier. This isn't
6361   // observable from outside the class though, so casting away the
6362   // const isn't dangerous.
6363   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6364
6365   OS << "Classifying expressions for: ";
6366   WriteAsOperand(OS, F, /*PrintType=*/false);
6367   OS << "\n";
6368   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
6369     if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
6370       OS << *I << '\n';
6371       OS << "  -->  ";
6372       const SCEV *SV = SE.getSCEV(&*I);
6373       SV->print(OS);
6374
6375       const Loop *L = LI->getLoopFor((*I).getParent());
6376
6377       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
6378       if (AtUse != SV) {
6379         OS << "  -->  ";
6380         AtUse->print(OS);
6381       }
6382
6383       if (L) {
6384         OS << "\t\t" "Exits: ";
6385         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
6386         if (!SE.isLoopInvariant(ExitValue, L)) {
6387           OS << "<<Unknown>>";
6388         } else {
6389           OS << *ExitValue;
6390         }
6391       }
6392
6393       OS << "\n";
6394     }
6395
6396   OS << "Determining loop execution counts for: ";
6397   WriteAsOperand(OS, F, /*PrintType=*/false);
6398   OS << "\n";
6399   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
6400     PrintLoopInfo(OS, &SE, *I);
6401 }
6402
6403 ScalarEvolution::LoopDisposition
6404 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
6405   std::map<const Loop *, LoopDisposition> &Values = LoopDispositions[S];
6406   std::pair<std::map<const Loop *, LoopDisposition>::iterator, bool> Pair =
6407     Values.insert(std::make_pair(L, LoopVariant));
6408   if (!Pair.second)
6409     return Pair.first->second;
6410
6411   LoopDisposition D = computeLoopDisposition(S, L);
6412   return LoopDispositions[S][L] = D;
6413 }
6414
6415 ScalarEvolution::LoopDisposition
6416 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
6417   switch (S->getSCEVType()) {
6418   case scConstant:
6419     return LoopInvariant;
6420   case scTruncate:
6421   case scZeroExtend:
6422   case scSignExtend:
6423     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
6424   case scAddRecExpr: {
6425     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6426
6427     // If L is the addrec's loop, it's computable.
6428     if (AR->getLoop() == L)
6429       return LoopComputable;
6430
6431     // Add recurrences are never invariant in the function-body (null loop).
6432     if (!L)
6433       return LoopVariant;
6434
6435     // This recurrence is variant w.r.t. L if L contains AR's loop.
6436     if (L->contains(AR->getLoop()))
6437       return LoopVariant;
6438
6439     // This recurrence is invariant w.r.t. L if AR's loop contains L.
6440     if (AR->getLoop()->contains(L))
6441       return LoopInvariant;
6442
6443     // This recurrence is variant w.r.t. L if any of its operands
6444     // are variant.
6445     for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
6446          I != E; ++I)
6447       if (!isLoopInvariant(*I, L))
6448         return LoopVariant;
6449
6450     // Otherwise it's loop-invariant.
6451     return LoopInvariant;
6452   }
6453   case scAddExpr:
6454   case scMulExpr:
6455   case scUMaxExpr:
6456   case scSMaxExpr: {
6457     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6458     bool HasVarying = false;
6459     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6460          I != E; ++I) {
6461       LoopDisposition D = getLoopDisposition(*I, L);
6462       if (D == LoopVariant)
6463         return LoopVariant;
6464       if (D == LoopComputable)
6465         HasVarying = true;
6466     }
6467     return HasVarying ? LoopComputable : LoopInvariant;
6468   }
6469   case scUDivExpr: {
6470     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6471     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
6472     if (LD == LoopVariant)
6473       return LoopVariant;
6474     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
6475     if (RD == LoopVariant)
6476       return LoopVariant;
6477     return (LD == LoopInvariant && RD == LoopInvariant) ?
6478            LoopInvariant : LoopComputable;
6479   }
6480   case scUnknown:
6481     // All non-instruction values are loop invariant.  All instructions are loop
6482     // invariant if they are not contained in the specified loop.
6483     // Instructions are never considered invariant in the function body
6484     // (null loop) because they are defined within the "loop".
6485     if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6486       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
6487     return LoopInvariant;
6488   case scCouldNotCompute:
6489     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6490     return LoopVariant;
6491   default: break;
6492   }
6493   llvm_unreachable("Unknown SCEV kind!");
6494   return LoopVariant;
6495 }
6496
6497 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
6498   return getLoopDisposition(S, L) == LoopInvariant;
6499 }
6500
6501 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
6502   return getLoopDisposition(S, L) == LoopComputable;
6503 }
6504
6505 ScalarEvolution::BlockDisposition
6506 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6507   std::map<const BasicBlock *, BlockDisposition> &Values = BlockDispositions[S];
6508   std::pair<std::map<const BasicBlock *, BlockDisposition>::iterator, bool>
6509     Pair = Values.insert(std::make_pair(BB, DoesNotDominateBlock));
6510   if (!Pair.second)
6511     return Pair.first->second;
6512
6513   BlockDisposition D = computeBlockDisposition(S, BB);
6514   return BlockDispositions[S][BB] = D;
6515 }
6516
6517 ScalarEvolution::BlockDisposition
6518 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
6519   switch (S->getSCEVType()) {
6520   case scConstant:
6521     return ProperlyDominatesBlock;
6522   case scTruncate:
6523   case scZeroExtend:
6524   case scSignExtend:
6525     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
6526   case scAddRecExpr: {
6527     // This uses a "dominates" query instead of "properly dominates" query
6528     // to test for proper dominance too, because the instruction which
6529     // produces the addrec's value is a PHI, and a PHI effectively properly
6530     // dominates its entire containing block.
6531     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6532     if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6533       return DoesNotDominateBlock;
6534   }
6535   // FALL THROUGH into SCEVNAryExpr handling.
6536   case scAddExpr:
6537   case scMulExpr:
6538   case scUMaxExpr:
6539   case scSMaxExpr: {
6540     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6541     bool Proper = true;
6542     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6543          I != E; ++I) {
6544       BlockDisposition D = getBlockDisposition(*I, BB);
6545       if (D == DoesNotDominateBlock)
6546         return DoesNotDominateBlock;
6547       if (D == DominatesBlock)
6548         Proper = false;
6549     }
6550     return Proper ? ProperlyDominatesBlock : DominatesBlock;
6551   }
6552   case scUDivExpr: {
6553     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6554     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6555     BlockDisposition LD = getBlockDisposition(LHS, BB);
6556     if (LD == DoesNotDominateBlock)
6557       return DoesNotDominateBlock;
6558     BlockDisposition RD = getBlockDisposition(RHS, BB);
6559     if (RD == DoesNotDominateBlock)
6560       return DoesNotDominateBlock;
6561     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
6562       ProperlyDominatesBlock : DominatesBlock;
6563   }
6564   case scUnknown:
6565     if (Instruction *I =
6566           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
6567       if (I->getParent() == BB)
6568         return DominatesBlock;
6569       if (DT->properlyDominates(I->getParent(), BB))
6570         return ProperlyDominatesBlock;
6571       return DoesNotDominateBlock;
6572     }
6573     return ProperlyDominatesBlock;
6574   case scCouldNotCompute:
6575     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6576     return DoesNotDominateBlock;
6577   default: break;
6578   }
6579   llvm_unreachable("Unknown SCEV kind!");
6580   return DoesNotDominateBlock;
6581 }
6582
6583 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
6584   return getBlockDisposition(S, BB) >= DominatesBlock;
6585 }
6586
6587 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
6588   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
6589 }
6590
6591 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
6592   switch (S->getSCEVType()) {
6593   case scConstant:
6594     return false;
6595   case scTruncate:
6596   case scZeroExtend:
6597   case scSignExtend: {
6598     const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6599     const SCEV *CastOp = Cast->getOperand();
6600     return Op == CastOp || hasOperand(CastOp, Op);
6601   }
6602   case scAddRecExpr:
6603   case scAddExpr:
6604   case scMulExpr:
6605   case scUMaxExpr:
6606   case scSMaxExpr: {
6607     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6608     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6609          I != E; ++I) {
6610       const SCEV *NAryOp = *I;
6611       if (NAryOp == Op || hasOperand(NAryOp, Op))
6612         return true;
6613     }
6614     return false;
6615   }
6616   case scUDivExpr: {
6617     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6618     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
6619     return LHS == Op || hasOperand(LHS, Op) ||
6620            RHS == Op || hasOperand(RHS, Op);
6621   }
6622   case scUnknown:
6623     return false;
6624   case scCouldNotCompute:
6625     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6626     return false;
6627   default: break;
6628   }
6629   llvm_unreachable("Unknown SCEV kind!");
6630   return false;
6631 }
6632
6633 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
6634   ValuesAtScopes.erase(S);
6635   LoopDispositions.erase(S);
6636   BlockDispositions.erase(S);
6637   UnsignedRanges.erase(S);
6638   SignedRanges.erase(S);
6639 }