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