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