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