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