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