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