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