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