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