1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
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.
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.
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
38 //===----------------------------------------------------------------------===//
40 // There are several good references for the techniques used in this analysis.
42 // Chains of recurrences -- a method to expedite the evaluation
43 // of closed-form functions
44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46 // On computational properties of chains of recurrences
49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 // Robert A. van Engelen
52 // Efficient Symbolic Analysis for Optimizing Compilers
53 // Robert A. van Engelen
55 // Using the chains of recurrences algebra for data dependence testing and
56 // induction variable substitution
57 // MS Thesis, Johnie Birch
59 //===----------------------------------------------------------------------===//
61 #define DEBUG_TYPE "scalar-evolution"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/Constants.h"
64 #include "llvm/DerivedTypes.h"
65 #include "llvm/GlobalVariable.h"
66 #include "llvm/GlobalAlias.h"
67 #include "llvm/Instructions.h"
68 #include "llvm/LLVMContext.h"
69 #include "llvm/Operator.h"
70 #include "llvm/Analysis/ConstantFolding.h"
71 #include "llvm/Analysis/Dominators.h"
72 #include "llvm/Analysis/LoopInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/Assembly/Writer.h"
75 #include "llvm/Target/TargetData.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/ConstantRange.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/GetElementPtrTypeIterator.h"
81 #include "llvm/Support/InstIterator.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/ADT/Statistic.h"
85 #include "llvm/ADT/STLExtras.h"
86 #include "llvm/ADT/SmallPtrSet.h"
90 STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92 STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94 STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96 STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
99 static cl::opt<unsigned>
100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant "
106 static RegisterPass<ScalarEvolution>
107 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
108 char ScalarEvolution::ID = 0;
110 //===----------------------------------------------------------------------===//
111 // SCEV class definitions
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
115 // Implementation of the SCEV class.
120 void SCEV::dump() const {
125 bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
131 bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
137 bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
143 SCEVCouldNotCompute::SCEVCouldNotCompute() :
144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
146 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
151 const Type *SCEVCouldNotCompute::getType() const {
152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
156 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
161 bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
166 void SCEVCouldNotCompute::print(raw_ostream &OS) const {
167 OS << "***COULDNOTCOMPUTE***";
170 bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
174 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
176 ID.AddInteger(scConstant);
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
181 new (S) SCEVConstant(ID, V);
182 UniqueSCEVs.InsertNode(S, IP);
186 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(getContext(), Val));
191 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
196 const Type *SCEVConstant::getType() const { return V->getType(); }
198 void SCEVConstant::print(raw_ostream &OS) const {
199 WriteAsOperand(OS, V, false);
202 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
206 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
210 bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
214 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
217 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
218 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
219 "Cannot truncate non-integer value!");
222 void SCEVTruncateExpr::print(raw_ostream &OS) const {
223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
226 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
229 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
230 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
231 "Cannot zero extend non-integer value!");
234 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
238 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
241 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
242 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
243 "Cannot sign extend non-integer value!");
246 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
250 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
251 assert(NumOperands > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = NumOperands; i != e; ++i)
255 OS << OpStr << *Operands[i];
259 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
267 bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
275 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
279 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
283 void SCEVUDivExpr::print(raw_ostream &OS) const {
284 OS << "(" << *LHS << " /u " << *RHS << ")";
287 const Type *SCEVUDivExpr::getType() const {
288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
296 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
297 // Add recurrences are never invariant in the function-body (null loop).
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
302 if (QueryLoop->contains(L))
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
311 // Otherwise it's loop-invariant.
316 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
317 return DT->dominates(L->getHeader(), BB) &&
318 SCEVNAryExpr::dominates(BB, DT);
322 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
323 // This uses a "dominates" query instead of "properly dominates" query because
324 // the instruction which produces the addrec's value is a PHI, and a PHI
325 // effectively properly dominates its entire containing block.
326 return DT->dominates(L->getHeader(), BB) &&
327 SCEVNAryExpr::properlyDominates(BB, DT);
330 void SCEVAddRecExpr::print(raw_ostream &OS) const {
331 OS << "{" << *Operands[0];
332 for (unsigned i = 1, e = NumOperands; i != e; ++i)
333 OS << ",+," << *Operands[i];
335 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
339 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
340 // All non-instruction values are loop invariant. All instructions are loop
341 // invariant if they are not contained in the specified loop.
342 // Instructions are never considered invariant in the function body
343 // (null loop) because they are defined within the "loop".
344 if (Instruction *I = dyn_cast<Instruction>(V))
345 return L && !L->contains(I);
349 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
350 if (Instruction *I = dyn_cast<Instruction>(getValue()))
351 return DT->dominates(I->getParent(), BB);
355 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
356 if (Instruction *I = dyn_cast<Instruction>(getValue()))
357 return DT->properlyDominates(I->getParent(), BB);
361 const Type *SCEVUnknown::getType() const {
365 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
366 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
367 if (VCE->getOpcode() == Instruction::PtrToInt)
368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
369 if (CE->getOpcode() == Instruction::GetElementPtr &&
370 CE->getOperand(0)->isNullValue() &&
371 CE->getNumOperands() == 2)
372 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
374 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
382 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
384 if (VCE->getOpcode() == Instruction::PtrToInt)
385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
386 if (CE->getOpcode() == Instruction::GetElementPtr &&
387 CE->getOperand(0)->isNullValue()) {
389 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
390 if (const StructType *STy = dyn_cast<StructType>(Ty))
391 if (!STy->isPacked() &&
392 CE->getNumOperands() == 3 &&
393 CE->getOperand(1)->isNullValue()) {
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
396 STy->getNumElements() == 2 &&
397 STy->getElementType(0)->isIntegerTy(1)) {
398 AllocTy = STy->getElementType(1);
407 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getNumOperands() == 3 &&
413 CE->getOperand(0)->isNullValue() &&
414 CE->getOperand(1)->isNullValue()) {
416 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
417 // Ignore vector types here so that ScalarEvolutionExpander doesn't
418 // emit getelementptrs that index into vectors.
419 if (Ty->isStructTy() || Ty->isArrayTy()) {
421 FieldNo = CE->getOperand(2);
429 void SCEVUnknown::print(raw_ostream &OS) const {
431 if (isSizeOf(AllocTy)) {
432 OS << "sizeof(" << *AllocTy << ")";
435 if (isAlignOf(AllocTy)) {
436 OS << "alignof(" << *AllocTy << ")";
442 if (isOffsetOf(CTy, FieldNo)) {
443 OS << "offsetof(" << *CTy << ", ";
444 WriteAsOperand(OS, FieldNo, false);
449 // Otherwise just print it normally.
450 WriteAsOperand(OS, V, false);
453 //===----------------------------------------------------------------------===//
455 //===----------------------------------------------------------------------===//
457 static bool CompareTypes(const Type *A, const Type *B) {
458 if (A->getTypeID() != B->getTypeID())
459 return A->getTypeID() < B->getTypeID();
460 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
461 const IntegerType *BI = cast<IntegerType>(B);
462 return AI->getBitWidth() < BI->getBitWidth();
464 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
465 const PointerType *BI = cast<PointerType>(B);
466 return CompareTypes(AI->getElementType(), BI->getElementType());
468 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
469 const ArrayType *BI = cast<ArrayType>(B);
470 if (AI->getNumElements() != BI->getNumElements())
471 return AI->getNumElements() < BI->getNumElements();
472 return CompareTypes(AI->getElementType(), BI->getElementType());
474 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
475 const VectorType *BI = cast<VectorType>(B);
476 if (AI->getNumElements() != BI->getNumElements())
477 return AI->getNumElements() < BI->getNumElements();
478 return CompareTypes(AI->getElementType(), BI->getElementType());
480 if (const StructType *AI = dyn_cast<StructType>(A)) {
481 const StructType *BI = cast<StructType>(B);
482 if (AI->getNumElements() != BI->getNumElements())
483 return AI->getNumElements() < BI->getNumElements();
484 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
485 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
486 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
487 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
493 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
494 /// than the complexity of the RHS. This comparator is used to canonicalize
496 class SCEVComplexityCompare {
499 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
501 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
502 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
506 // Primarily, sort the SCEVs by their getSCEVType().
507 if (LHS->getSCEVType() != RHS->getSCEVType())
508 return LHS->getSCEVType() < RHS->getSCEVType();
510 // Aside from the getSCEVType() ordering, the particular ordering
511 // isn't very important except that it's beneficial to be consistent,
512 // so that (a + b) and (b + a) don't end up as different expressions.
514 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
515 // not as complete as it could be.
516 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
517 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
519 // Order pointer values after integer values. This helps SCEVExpander
521 if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
523 if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
526 // Compare getValueID values.
527 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
528 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
530 // Sort arguments by their position.
531 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
532 const Argument *RA = cast<Argument>(RU->getValue());
533 return LA->getArgNo() < RA->getArgNo();
536 // For instructions, compare their loop depth, and their opcode.
537 // This is pretty loose.
538 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
539 Instruction *RV = cast<Instruction>(RU->getValue());
541 // Compare loop depths.
542 if (LI->getLoopDepth(LV->getParent()) !=
543 LI->getLoopDepth(RV->getParent()))
544 return LI->getLoopDepth(LV->getParent()) <
545 LI->getLoopDepth(RV->getParent());
548 if (LV->getOpcode() != RV->getOpcode())
549 return LV->getOpcode() < RV->getOpcode();
551 // Compare the number of operands.
552 if (LV->getNumOperands() != RV->getNumOperands())
553 return LV->getNumOperands() < RV->getNumOperands();
559 // Compare constant values.
560 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
561 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
562 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
563 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
564 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
567 // Compare addrec loop depths.
568 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
569 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
570 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
571 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
574 // Lexicographically compare n-ary expressions.
575 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
576 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
577 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
578 if (i >= RC->getNumOperands())
580 if (operator()(LC->getOperand(i), RC->getOperand(i)))
582 if (operator()(RC->getOperand(i), LC->getOperand(i)))
585 return LC->getNumOperands() < RC->getNumOperands();
588 // Lexicographically compare udiv expressions.
589 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
590 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
591 if (operator()(LC->getLHS(), RC->getLHS()))
593 if (operator()(RC->getLHS(), LC->getLHS()))
595 if (operator()(LC->getRHS(), RC->getRHS()))
597 if (operator()(RC->getRHS(), LC->getRHS()))
602 // Compare cast expressions by operand.
603 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
604 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
605 return operator()(LC->getOperand(), RC->getOperand());
608 llvm_unreachable("Unknown SCEV kind!");
614 /// GroupByComplexity - Given a list of SCEV objects, order them by their
615 /// complexity, and group objects of the same complexity together by value.
616 /// When this routine is finished, we know that any duplicates in the vector are
617 /// consecutive and that complexity is monotonically increasing.
619 /// Note that we go take special precautions to ensure that we get deterministic
620 /// results from this routine. In other words, we don't want the results of
621 /// this to depend on where the addresses of various SCEV objects happened to
624 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
626 if (Ops.size() < 2) return; // Noop
627 if (Ops.size() == 2) {
628 // This is the common case, which also happens to be trivially simple.
630 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
631 std::swap(Ops[0], Ops[1]);
635 // Do the rough sort by complexity.
636 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
638 // Now that we are sorted by complexity, group elements of the same
639 // complexity. Note that this is, at worst, N^2, but the vector is likely to
640 // be extremely short in practice. Note that we take this approach because we
641 // do not want to depend on the addresses of the objects we are grouping.
642 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
643 const SCEV *S = Ops[i];
644 unsigned Complexity = S->getSCEVType();
646 // If there are any objects of the same complexity and same value as this
648 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
649 if (Ops[j] == S) { // Found a duplicate.
650 // Move it to immediately after i'th element.
651 std::swap(Ops[i+1], Ops[j]);
652 ++i; // no need to rescan it.
653 if (i == e-2) return; // Done!
661 //===----------------------------------------------------------------------===//
662 // Simple SCEV method implementations
663 //===----------------------------------------------------------------------===//
665 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
667 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
669 const Type* ResultTy) {
670 // Handle the simplest case efficiently.
672 return SE.getTruncateOrZeroExtend(It, ResultTy);
674 // We are using the following formula for BC(It, K):
676 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
678 // Suppose, W is the bitwidth of the return value. We must be prepared for
679 // overflow. Hence, we must assure that the result of our computation is
680 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
681 // safe in modular arithmetic.
683 // However, this code doesn't use exactly that formula; the formula it uses
684 // is something like the following, where T is the number of factors of 2 in
685 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
688 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
690 // This formula is trivially equivalent to the previous formula. However,
691 // this formula can be implemented much more efficiently. The trick is that
692 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
693 // arithmetic. To do exact division in modular arithmetic, all we have
694 // to do is multiply by the inverse. Therefore, this step can be done at
697 // The next issue is how to safely do the division by 2^T. The way this
698 // is done is by doing the multiplication step at a width of at least W + T
699 // bits. This way, the bottom W+T bits of the product are accurate. Then,
700 // when we perform the division by 2^T (which is equivalent to a right shift
701 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
702 // truncated out after the division by 2^T.
704 // In comparison to just directly using the first formula, this technique
705 // is much more efficient; using the first formula requires W * K bits,
706 // but this formula less than W + K bits. Also, the first formula requires
707 // a division step, whereas this formula only requires multiplies and shifts.
709 // It doesn't matter whether the subtraction step is done in the calculation
710 // width or the input iteration count's width; if the subtraction overflows,
711 // the result must be zero anyway. We prefer here to do it in the width of
712 // the induction variable because it helps a lot for certain cases; CodeGen
713 // isn't smart enough to ignore the overflow, which leads to much less
714 // efficient code if the width of the subtraction is wider than the native
717 // (It's possible to not widen at all by pulling out factors of 2 before
718 // the multiplication; for example, K=2 can be calculated as
719 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
720 // extra arithmetic, so it's not an obvious win, and it gets
721 // much more complicated for K > 3.)
723 // Protection from insane SCEVs; this bound is conservative,
724 // but it probably doesn't matter.
726 return SE.getCouldNotCompute();
728 unsigned W = SE.getTypeSizeInBits(ResultTy);
730 // Calculate K! / 2^T and T; we divide out the factors of two before
731 // multiplying for calculating K! / 2^T to avoid overflow.
732 // Other overflow doesn't matter because we only care about the bottom
733 // W bits of the result.
734 APInt OddFactorial(W, 1);
736 for (unsigned i = 3; i <= K; ++i) {
738 unsigned TwoFactors = Mult.countTrailingZeros();
740 Mult = Mult.lshr(TwoFactors);
741 OddFactorial *= Mult;
744 // We need at least W + T bits for the multiplication step
745 unsigned CalculationBits = W + T;
747 // Calculate 2^T, at width T+W.
748 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
750 // Calculate the multiplicative inverse of K! / 2^T;
751 // this multiplication factor will perform the exact division by
753 APInt Mod = APInt::getSignedMinValue(W+1);
754 APInt MultiplyFactor = OddFactorial.zext(W+1);
755 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
756 MultiplyFactor = MultiplyFactor.trunc(W);
758 // Calculate the product, at width T+W
759 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
761 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
762 for (unsigned i = 1; i != K; ++i) {
763 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
764 Dividend = SE.getMulExpr(Dividend,
765 SE.getTruncateOrZeroExtend(S, CalculationTy));
769 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
771 // Truncate the result, and divide by K! / 2^T.
773 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
774 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
777 /// evaluateAtIteration - Return the value of this chain of recurrences at
778 /// the specified iteration number. We can evaluate this recurrence by
779 /// multiplying each element in the chain by the binomial coefficient
780 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
782 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
784 /// where BC(It, k) stands for binomial coefficient.
786 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
787 ScalarEvolution &SE) const {
788 const SCEV *Result = getStart();
789 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
790 // The computation is correct in the face of overflow provided that the
791 // multiplication is performed _after_ the evaluation of the binomial
793 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
794 if (isa<SCEVCouldNotCompute>(Coeff))
797 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
802 //===----------------------------------------------------------------------===//
803 // SCEV Expression folder implementations
804 //===----------------------------------------------------------------------===//
806 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
808 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
809 "This is not a truncating conversion!");
810 assert(isSCEVable(Ty) &&
811 "This is not a conversion to a SCEVable type!");
812 Ty = getEffectiveSCEVType(Ty);
815 ID.AddInteger(scTruncate);
819 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
821 // Fold if the operand is constant.
822 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
824 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
826 // trunc(trunc(x)) --> trunc(x)
827 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
828 return getTruncateExpr(ST->getOperand(), Ty);
830 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
831 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
832 return getTruncateOrSignExtend(SS->getOperand(), Ty);
834 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
835 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
836 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
838 // If the input value is a chrec scev, truncate the chrec's operands.
839 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
840 SmallVector<const SCEV *, 4> Operands;
841 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
842 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
843 return getAddRecExpr(Operands, AddRec->getLoop());
846 // The cast wasn't folded; create an explicit cast node.
847 // Recompute the insert position, as it may have been invalidated.
848 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
849 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
850 new (S) SCEVTruncateExpr(ID, Op, Ty);
851 UniqueSCEVs.InsertNode(S, IP);
855 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
857 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
858 "This is not an extending conversion!");
859 assert(isSCEVable(Ty) &&
860 "This is not a conversion to a SCEVable type!");
861 Ty = getEffectiveSCEVType(Ty);
863 // Fold if the operand is constant.
864 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
865 const Type *IntTy = getEffectiveSCEVType(Ty);
866 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
867 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
868 return getConstant(cast<ConstantInt>(C));
871 // zext(zext(x)) --> zext(x)
872 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
873 return getZeroExtendExpr(SZ->getOperand(), Ty);
875 // Before doing any expensive analysis, check to see if we've already
876 // computed a SCEV for this Op and Ty.
878 ID.AddInteger(scZeroExtend);
882 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
884 // If the input value is a chrec scev, and we can prove that the value
885 // did not overflow the old, smaller, value, we can zero extend all of the
886 // operands (often constants). This allows analysis of something like
887 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
888 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
889 if (AR->isAffine()) {
890 const SCEV *Start = AR->getStart();
891 const SCEV *Step = AR->getStepRecurrence(*this);
892 unsigned BitWidth = getTypeSizeInBits(AR->getType());
893 const Loop *L = AR->getLoop();
895 // If we have special knowledge that this addrec won't overflow,
896 // we don't need to do any further analysis.
897 if (AR->hasNoUnsignedWrap())
898 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
899 getZeroExtendExpr(Step, Ty),
902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
910 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
912 // Manually compute the final value for AR, checking for
915 // Check whether the backedge-taken count can be losslessly casted to
916 // the addrec's type. The count is always unsigned.
917 const SCEV *CastedMaxBECount =
918 getTruncateOrZeroExtend(MaxBECount, Start->getType());
919 const SCEV *RecastedMaxBECount =
920 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
921 if (MaxBECount == RecastedMaxBECount) {
922 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
923 // Check whether Start+Step*MaxBECount has no unsigned overflow.
924 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
925 const SCEV *Add = getAddExpr(Start, ZMul);
926 const SCEV *OperandExtendedAdd =
927 getAddExpr(getZeroExtendExpr(Start, WideTy),
928 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
929 getZeroExtendExpr(Step, WideTy)));
930 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
931 // Return the expression with the addrec on the outside.
932 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
933 getZeroExtendExpr(Step, Ty),
936 // Similar to above, only this time treat the step value as signed.
937 // This covers loops that count down.
938 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
939 Add = getAddExpr(Start, SMul);
941 getAddExpr(getZeroExtendExpr(Start, WideTy),
942 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
943 getSignExtendExpr(Step, WideTy)));
944 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
945 // Return the expression with the addrec on the outside.
946 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
947 getSignExtendExpr(Step, Ty),
951 // If the backedge is guarded by a comparison with the pre-inc value
952 // the addrec is safe. Also, if the entry is guarded by a comparison
953 // with the start value and the backedge is guarded by a comparison
954 // with the post-inc value, the addrec is safe.
955 if (isKnownPositive(Step)) {
956 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
957 getUnsignedRange(Step).getUnsignedMax());
958 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
959 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
960 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
961 AR->getPostIncExpr(*this), N)))
962 // Return the expression with the addrec on the outside.
963 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
964 getZeroExtendExpr(Step, Ty),
966 } else if (isKnownNegative(Step)) {
967 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
968 getSignedRange(Step).getSignedMin());
969 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
970 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
971 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
972 AR->getPostIncExpr(*this), N)))
973 // Return the expression with the addrec on the outside.
974 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
975 getSignExtendExpr(Step, Ty),
981 // The cast wasn't folded; create an explicit cast node.
982 // Recompute the insert position, as it may have been invalidated.
983 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
984 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
985 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
986 UniqueSCEVs.InsertNode(S, IP);
990 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
992 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
993 "This is not an extending conversion!");
994 assert(isSCEVable(Ty) &&
995 "This is not a conversion to a SCEVable type!");
996 Ty = getEffectiveSCEVType(Ty);
998 // Fold if the operand is constant.
999 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
1000 const Type *IntTy = getEffectiveSCEVType(Ty);
1001 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
1002 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
1003 return getConstant(cast<ConstantInt>(C));
1006 // sext(sext(x)) --> sext(x)
1007 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1008 return getSignExtendExpr(SS->getOperand(), Ty);
1010 // Before doing any expensive analysis, check to see if we've already
1011 // computed a SCEV for this Op and Ty.
1012 FoldingSetNodeID ID;
1013 ID.AddInteger(scSignExtend);
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1019 // If the input value is a chrec scev, and we can prove that the value
1020 // did not overflow the old, smaller, value, we can sign extend all of the
1021 // operands (often constants). This allows analysis of something like
1022 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1023 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1024 if (AR->isAffine()) {
1025 const SCEV *Start = AR->getStart();
1026 const SCEV *Step = AR->getStepRecurrence(*this);
1027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1028 const Loop *L = AR->getLoop();
1030 // If we have special knowledge that this addrec won't overflow,
1031 // we don't need to do any further analysis.
1032 if (AR->hasNoSignedWrap())
1033 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1034 getSignExtendExpr(Step, Ty),
1037 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1038 // Note that this serves two purposes: It filters out loops that are
1039 // simply not analyzable, and it covers the case where this code is
1040 // being called from within backedge-taken count analysis, such that
1041 // attempting to ask for the backedge-taken count would likely result
1042 // in infinite recursion. In the later case, the analysis code will
1043 // cope with a conservative value, and it will take care to purge
1044 // that value once it has finished.
1045 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1046 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1047 // Manually compute the final value for AR, checking for
1050 // Check whether the backedge-taken count can be losslessly casted to
1051 // the addrec's type. The count is always unsigned.
1052 const SCEV *CastedMaxBECount =
1053 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1054 const SCEV *RecastedMaxBECount =
1055 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1056 if (MaxBECount == RecastedMaxBECount) {
1057 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1058 // Check whether Start+Step*MaxBECount has no signed overflow.
1059 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1060 const SCEV *Add = getAddExpr(Start, SMul);
1061 const SCEV *OperandExtendedAdd =
1062 getAddExpr(getSignExtendExpr(Start, WideTy),
1063 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1064 getSignExtendExpr(Step, WideTy)));
1065 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1066 // Return the expression with the addrec on the outside.
1067 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1068 getSignExtendExpr(Step, Ty),
1071 // Similar to above, only this time treat the step value as unsigned.
1072 // This covers loops that count up with an unsigned step.
1073 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1074 Add = getAddExpr(Start, UMul);
1075 OperandExtendedAdd =
1076 getAddExpr(getSignExtendExpr(Start, WideTy),
1077 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1078 getZeroExtendExpr(Step, WideTy)));
1079 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1080 // Return the expression with the addrec on the outside.
1081 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1082 getZeroExtendExpr(Step, Ty),
1086 // If the backedge is guarded by a comparison with the pre-inc value
1087 // the addrec is safe. Also, if the entry is guarded by a comparison
1088 // with the start value and the backedge is guarded by a comparison
1089 // with the post-inc value, the addrec is safe.
1090 if (isKnownPositive(Step)) {
1091 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1092 getSignedRange(Step).getSignedMax());
1093 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1094 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1095 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1096 AR->getPostIncExpr(*this), N)))
1097 // Return the expression with the addrec on the outside.
1098 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1099 getSignExtendExpr(Step, Ty),
1101 } else if (isKnownNegative(Step)) {
1102 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1103 getSignedRange(Step).getSignedMin());
1104 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1105 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1106 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1107 AR->getPostIncExpr(*this), N)))
1108 // Return the expression with the addrec on the outside.
1109 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1110 getSignExtendExpr(Step, Ty),
1116 // The cast wasn't folded; create an explicit cast node.
1117 // Recompute the insert position, as it may have been invalidated.
1118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1119 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
1120 new (S) SCEVSignExtendExpr(ID, Op, Ty);
1121 UniqueSCEVs.InsertNode(S, IP);
1125 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1126 /// unspecified bits out to the given type.
1128 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1130 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1131 "This is not an extending conversion!");
1132 assert(isSCEVable(Ty) &&
1133 "This is not a conversion to a SCEVable type!");
1134 Ty = getEffectiveSCEVType(Ty);
1136 // Sign-extend negative constants.
1137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1138 if (SC->getValue()->getValue().isNegative())
1139 return getSignExtendExpr(Op, Ty);
1141 // Peel off a truncate cast.
1142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1143 const SCEV *NewOp = T->getOperand();
1144 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1145 return getAnyExtendExpr(NewOp, Ty);
1146 return getTruncateOrNoop(NewOp, Ty);
1149 // Next try a zext cast. If the cast is folded, use it.
1150 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1151 if (!isa<SCEVZeroExtendExpr>(ZExt))
1154 // Next try a sext cast. If the cast is folded, use it.
1155 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1156 if (!isa<SCEVSignExtendExpr>(SExt))
1159 // Force the cast to be folded into the operands of an addrec.
1160 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1161 SmallVector<const SCEV *, 4> Ops;
1162 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1164 Ops.push_back(getAnyExtendExpr(*I, Ty));
1165 return getAddRecExpr(Ops, AR->getLoop());
1168 // If the expression is obviously signed, use the sext cast value.
1169 if (isa<SCEVSMaxExpr>(Op))
1172 // Absent any other information, use the zext cast value.
1176 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1177 /// a list of operands to be added under the given scale, update the given
1178 /// map. This is a helper function for getAddRecExpr. As an example of
1179 /// what it does, given a sequence of operands that would form an add
1180 /// expression like this:
1182 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1184 /// where A and B are constants, update the map with these values:
1186 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1188 /// and add 13 + A*B*29 to AccumulatedConstant.
1189 /// This will allow getAddRecExpr to produce this:
1191 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1193 /// This form often exposes folding opportunities that are hidden in
1194 /// the original operand list.
1196 /// Return true iff it appears that any interesting folding opportunities
1197 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1198 /// the common case where no interesting opportunities are present, and
1199 /// is also used as a check to avoid infinite recursion.
1202 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1203 SmallVector<const SCEV *, 8> &NewOps,
1204 APInt &AccumulatedConstant,
1205 const SCEV *const *Ops, size_t NumOperands,
1207 ScalarEvolution &SE) {
1208 bool Interesting = false;
1210 // Iterate over the add operands.
1211 for (unsigned i = 0, e = NumOperands; i != e; ++i) {
1212 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1213 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1215 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1216 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1217 // A multiplication of a constant with another add; recurse.
1218 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1220 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1221 Add->op_begin(), Add->getNumOperands(),
1224 // A multiplication of a constant with some other value. Update
1226 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1227 const SCEV *Key = SE.getMulExpr(MulOps);
1228 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1229 M.insert(std::make_pair(Key, NewScale));
1231 NewOps.push_back(Pair.first->first);
1233 Pair.first->second += NewScale;
1234 // The map already had an entry for this value, which may indicate
1235 // a folding opportunity.
1239 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1240 // Pull a buried constant out to the outside.
1241 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1243 AccumulatedConstant += Scale * C->getValue()->getValue();
1245 // An ordinary operand. Update the map.
1246 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1247 M.insert(std::make_pair(Ops[i], Scale));
1249 NewOps.push_back(Pair.first->first);
1251 Pair.first->second += Scale;
1252 // The map already had an entry for this value, which may indicate
1253 // a folding opportunity.
1263 struct APIntCompare {
1264 bool operator()(const APInt &LHS, const APInt &RHS) const {
1265 return LHS.ult(RHS);
1270 /// getAddExpr - Get a canonical add expression, or something simpler if
1272 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1273 bool HasNUW, bool HasNSW) {
1274 assert(!Ops.empty() && "Cannot get empty add!");
1275 if (Ops.size() == 1) return Ops[0];
1277 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1278 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1279 getEffectiveSCEVType(Ops[0]->getType()) &&
1280 "SCEVAddExpr operand types don't match!");
1283 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1284 if (!HasNUW && HasNSW) {
1286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1287 if (!isKnownNonNegative(Ops[i])) {
1291 if (All) HasNUW = true;
1294 // Sort by complexity, this groups all similar expression types together.
1295 GroupByComplexity(Ops, LI);
1297 // If there are any constants, fold them together.
1299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1301 assert(Idx < Ops.size());
1302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1303 // We found two constants, fold them together!
1304 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1305 RHSC->getValue()->getValue());
1306 if (Ops.size() == 2) return Ops[0];
1307 Ops.erase(Ops.begin()+1); // Erase the folded element
1308 LHSC = cast<SCEVConstant>(Ops[0]);
1311 // If we are left with a constant zero being added, strip it off.
1312 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1313 Ops.erase(Ops.begin());
1318 if (Ops.size() == 1) return Ops[0];
1320 // Okay, check to see if the same value occurs in the operand list twice. If
1321 // so, merge them together into an multiply expression. Since we sorted the
1322 // list, these values are required to be adjacent.
1323 const Type *Ty = Ops[0]->getType();
1324 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1325 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1326 // Found a match, merge the two values into a multiply, and add any
1327 // remaining values to the result.
1328 const SCEV *Two = getIntegerSCEV(2, Ty);
1329 const SCEV *Mul = getMulExpr(Ops[i], Two);
1330 if (Ops.size() == 2)
1332 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1334 return getAddExpr(Ops, HasNUW, HasNSW);
1337 // Check for truncates. If all the operands are truncated from the same
1338 // type, see if factoring out the truncate would permit the result to be
1339 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1340 // if the contents of the resulting outer trunc fold to something simple.
1341 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1342 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1343 const Type *DstType = Trunc->getType();
1344 const Type *SrcType = Trunc->getOperand()->getType();
1345 SmallVector<const SCEV *, 8> LargeOps;
1347 // Check all the operands to see if they can be represented in the
1348 // source type of the truncate.
1349 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1350 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1351 if (T->getOperand()->getType() != SrcType) {
1355 LargeOps.push_back(T->getOperand());
1356 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1357 // This could be either sign or zero extension, but sign extension
1358 // is much more likely to be foldable here.
1359 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1360 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1361 SmallVector<const SCEV *, 8> LargeMulOps;
1362 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1363 if (const SCEVTruncateExpr *T =
1364 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1365 if (T->getOperand()->getType() != SrcType) {
1369 LargeMulOps.push_back(T->getOperand());
1370 } else if (const SCEVConstant *C =
1371 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1372 // This could be either sign or zero extension, but sign extension
1373 // is much more likely to be foldable here.
1374 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1381 LargeOps.push_back(getMulExpr(LargeMulOps));
1388 // Evaluate the expression in the larger type.
1389 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1390 // If it folds to something simple, use it. Otherwise, don't.
1391 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1392 return getTruncateExpr(Fold, DstType);
1396 // Skip past any other cast SCEVs.
1397 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1400 // If there are add operands they would be next.
1401 if (Idx < Ops.size()) {
1402 bool DeletedAdd = false;
1403 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1404 // If we have an add, expand the add operands onto the end of the operands
1406 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1407 Ops.erase(Ops.begin()+Idx);
1411 // If we deleted at least one add, we added operands to the end of the list,
1412 // and they are not necessarily sorted. Recurse to resort and resimplify
1413 // any operands we just acquired.
1415 return getAddExpr(Ops);
1418 // Skip over the add expression until we get to a multiply.
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1422 // Check to see if there are any folding opportunities present with
1423 // operands multiplied by constant values.
1424 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1425 uint64_t BitWidth = getTypeSizeInBits(Ty);
1426 DenseMap<const SCEV *, APInt> M;
1427 SmallVector<const SCEV *, 8> NewOps;
1428 APInt AccumulatedConstant(BitWidth, 0);
1429 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1430 Ops.data(), Ops.size(),
1431 APInt(BitWidth, 1), *this)) {
1432 // Some interesting folding opportunity is present, so its worthwhile to
1433 // re-generate the operands list. Group the operands by constant scale,
1434 // to avoid multiplying by the same constant scale multiple times.
1435 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1436 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1437 E = NewOps.end(); I != E; ++I)
1438 MulOpLists[M.find(*I)->second].push_back(*I);
1439 // Re-generate the operands list.
1441 if (AccumulatedConstant != 0)
1442 Ops.push_back(getConstant(AccumulatedConstant));
1443 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1444 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1446 Ops.push_back(getMulExpr(getConstant(I->first),
1447 getAddExpr(I->second)));
1449 return getIntegerSCEV(0, Ty);
1450 if (Ops.size() == 1)
1452 return getAddExpr(Ops);
1456 // If we are adding something to a multiply expression, make sure the
1457 // something is not already an operand of the multiply. If so, merge it into
1459 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1460 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1461 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1462 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1463 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1464 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1465 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1466 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1467 if (Mul->getNumOperands() != 2) {
1468 // If the multiply has more than two operands, we must get the
1470 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1471 MulOps.erase(MulOps.begin()+MulOp);
1472 InnerMul = getMulExpr(MulOps);
1474 const SCEV *One = getIntegerSCEV(1, Ty);
1475 const SCEV *AddOne = getAddExpr(InnerMul, One);
1476 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1477 if (Ops.size() == 2) return OuterMul;
1479 Ops.erase(Ops.begin()+AddOp);
1480 Ops.erase(Ops.begin()+Idx-1);
1482 Ops.erase(Ops.begin()+Idx);
1483 Ops.erase(Ops.begin()+AddOp-1);
1485 Ops.push_back(OuterMul);
1486 return getAddExpr(Ops);
1489 // Check this multiply against other multiplies being added together.
1490 for (unsigned OtherMulIdx = Idx+1;
1491 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1493 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1494 // If MulOp occurs in OtherMul, we can fold the two multiplies
1496 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1497 OMulOp != e; ++OMulOp)
1498 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1499 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1500 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1501 if (Mul->getNumOperands() != 2) {
1502 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1504 MulOps.erase(MulOps.begin()+MulOp);
1505 InnerMul1 = getMulExpr(MulOps);
1507 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1508 if (OtherMul->getNumOperands() != 2) {
1509 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1510 OtherMul->op_end());
1511 MulOps.erase(MulOps.begin()+OMulOp);
1512 InnerMul2 = getMulExpr(MulOps);
1514 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1515 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1516 if (Ops.size() == 2) return OuterMul;
1517 Ops.erase(Ops.begin()+Idx);
1518 Ops.erase(Ops.begin()+OtherMulIdx-1);
1519 Ops.push_back(OuterMul);
1520 return getAddExpr(Ops);
1526 // If there are any add recurrences in the operands list, see if any other
1527 // added values are loop invariant. If so, we can fold them into the
1529 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1532 // Scan over all recurrences, trying to fold loop invariants into them.
1533 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1534 // Scan all of the other operands to this add and add them to the vector if
1535 // they are loop invariant w.r.t. the recurrence.
1536 SmallVector<const SCEV *, 8> LIOps;
1537 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1538 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1539 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1540 LIOps.push_back(Ops[i]);
1541 Ops.erase(Ops.begin()+i);
1545 // If we found some loop invariants, fold them into the recurrence.
1546 if (!LIOps.empty()) {
1547 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1548 LIOps.push_back(AddRec->getStart());
1550 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1552 AddRecOps[0] = getAddExpr(LIOps);
1554 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
1555 // is not associative so this isn't necessarily safe.
1556 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
1558 // If all of the other operands were loop invariant, we are done.
1559 if (Ops.size() == 1) return NewRec;
1561 // Otherwise, add the folded AddRec by the non-liv parts.
1562 for (unsigned i = 0;; ++i)
1563 if (Ops[i] == AddRec) {
1567 return getAddExpr(Ops);
1570 // Okay, if there weren't any loop invariants to be folded, check to see if
1571 // there are multiple AddRec's with the same loop induction variable being
1572 // added together. If so, we can fold them.
1573 for (unsigned OtherIdx = Idx+1;
1574 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1575 if (OtherIdx != Idx) {
1576 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1577 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1578 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1579 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1581 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1582 if (i >= NewOps.size()) {
1583 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1584 OtherAddRec->op_end());
1587 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1589 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
1591 if (Ops.size() == 2) return NewAddRec;
1593 Ops.erase(Ops.begin()+Idx);
1594 Ops.erase(Ops.begin()+OtherIdx-1);
1595 Ops.push_back(NewAddRec);
1596 return getAddExpr(Ops);
1600 // Otherwise couldn't fold anything into this recurrence. Move onto the
1604 // Okay, it looks like we really DO need an add expr. Check to see if we
1605 // already have one, otherwise create a new one.
1606 FoldingSetNodeID ID;
1607 ID.AddInteger(scAddExpr);
1608 ID.AddInteger(Ops.size());
1609 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1610 ID.AddPointer(Ops[i]);
1613 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1615 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1616 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1617 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1618 new (S) SCEVAddExpr(ID, O, Ops.size());
1619 UniqueSCEVs.InsertNode(S, IP);
1621 if (HasNUW) S->setHasNoUnsignedWrap(true);
1622 if (HasNSW) S->setHasNoSignedWrap(true);
1626 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1628 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1629 bool HasNUW, bool HasNSW) {
1630 assert(!Ops.empty() && "Cannot get empty mul!");
1631 if (Ops.size() == 1) return Ops[0];
1633 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1634 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1635 getEffectiveSCEVType(Ops[0]->getType()) &&
1636 "SCEVMulExpr operand types don't match!");
1639 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1640 if (!HasNUW && HasNSW) {
1642 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1643 if (!isKnownNonNegative(Ops[i])) {
1647 if (All) HasNUW = true;
1650 // Sort by complexity, this groups all similar expression types together.
1651 GroupByComplexity(Ops, LI);
1653 // If there are any constants, fold them together.
1655 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1657 // C1*(C2+V) -> C1*C2 + C1*V
1658 if (Ops.size() == 2)
1659 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1660 if (Add->getNumOperands() == 2 &&
1661 isa<SCEVConstant>(Add->getOperand(0)))
1662 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1663 getMulExpr(LHSC, Add->getOperand(1)));
1666 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1667 // We found two constants, fold them together!
1668 ConstantInt *Fold = ConstantInt::get(getContext(),
1669 LHSC->getValue()->getValue() *
1670 RHSC->getValue()->getValue());
1671 Ops[0] = getConstant(Fold);
1672 Ops.erase(Ops.begin()+1); // Erase the folded element
1673 if (Ops.size() == 1) return Ops[0];
1674 LHSC = cast<SCEVConstant>(Ops[0]);
1677 // If we are left with a constant one being multiplied, strip it off.
1678 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1679 Ops.erase(Ops.begin());
1681 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1682 // If we have a multiply of zero, it will always be zero.
1684 } else if (Ops[0]->isAllOnesValue()) {
1685 // If we have a mul by -1 of an add, try distributing the -1 among the
1687 if (Ops.size() == 2)
1688 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1689 SmallVector<const SCEV *, 4> NewOps;
1690 bool AnyFolded = false;
1691 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1693 const SCEV *Mul = getMulExpr(Ops[0], *I);
1694 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1695 NewOps.push_back(Mul);
1698 return getAddExpr(NewOps);
1703 // Skip over the add expression until we get to a multiply.
1704 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1707 if (Ops.size() == 1)
1710 // If there are mul operands inline them all into this expression.
1711 if (Idx < Ops.size()) {
1712 bool DeletedMul = false;
1713 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1714 // If we have an mul, expand the mul operands onto the end of the operands
1716 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1717 Ops.erase(Ops.begin()+Idx);
1721 // If we deleted at least one mul, we added operands to the end of the list,
1722 // and they are not necessarily sorted. Recurse to resort and resimplify
1723 // any operands we just acquired.
1725 return getMulExpr(Ops);
1728 // If there are any add recurrences in the operands list, see if any other
1729 // added values are loop invariant. If so, we can fold them into the
1731 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1734 // Scan over all recurrences, trying to fold loop invariants into them.
1735 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1736 // Scan all of the other operands to this mul and add them to the vector if
1737 // they are loop invariant w.r.t. the recurrence.
1738 SmallVector<const SCEV *, 8> LIOps;
1739 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1740 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1741 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1742 LIOps.push_back(Ops[i]);
1743 Ops.erase(Ops.begin()+i);
1747 // If we found some loop invariants, fold them into the recurrence.
1748 if (!LIOps.empty()) {
1749 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1750 SmallVector<const SCEV *, 4> NewOps;
1751 NewOps.reserve(AddRec->getNumOperands());
1752 if (LIOps.size() == 1) {
1753 const SCEV *Scale = LIOps[0];
1754 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1755 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1757 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1758 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
1759 MulOps.push_back(AddRec->getOperand(i));
1760 NewOps.push_back(getMulExpr(MulOps));
1764 // It's tempting to propagate the NSW flag here, but nsw multiplication
1765 // is not associative so this isn't necessarily safe.
1766 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1767 HasNUW && AddRec->hasNoUnsignedWrap(),
1770 // If all of the other operands were loop invariant, we are done.
1771 if (Ops.size() == 1) return NewRec;
1773 // Otherwise, multiply the folded AddRec by the non-liv parts.
1774 for (unsigned i = 0;; ++i)
1775 if (Ops[i] == AddRec) {
1779 return getMulExpr(Ops);
1782 // Okay, if there weren't any loop invariants to be folded, check to see if
1783 // there are multiple AddRec's with the same loop induction variable being
1784 // multiplied together. If so, we can fold them.
1785 for (unsigned OtherIdx = Idx+1;
1786 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1787 if (OtherIdx != Idx) {
1788 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1789 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1790 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1791 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1792 const SCEV *NewStart = getMulExpr(F->getStart(),
1794 const SCEV *B = F->getStepRecurrence(*this);
1795 const SCEV *D = G->getStepRecurrence(*this);
1796 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1799 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1801 if (Ops.size() == 2) return NewAddRec;
1803 Ops.erase(Ops.begin()+Idx);
1804 Ops.erase(Ops.begin()+OtherIdx-1);
1805 Ops.push_back(NewAddRec);
1806 return getMulExpr(Ops);
1810 // Otherwise couldn't fold anything into this recurrence. Move onto the
1814 // Okay, it looks like we really DO need an mul expr. Check to see if we
1815 // already have one, otherwise create a new one.
1816 FoldingSetNodeID ID;
1817 ID.AddInteger(scMulExpr);
1818 ID.AddInteger(Ops.size());
1819 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1820 ID.AddPointer(Ops[i]);
1823 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1825 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1826 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1827 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1828 new (S) SCEVMulExpr(ID, O, Ops.size());
1829 UniqueSCEVs.InsertNode(S, IP);
1831 if (HasNUW) S->setHasNoUnsignedWrap(true);
1832 if (HasNSW) S->setHasNoSignedWrap(true);
1836 /// getUDivExpr - Get a canonical unsigned division expression, or something
1837 /// simpler if possible.
1838 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1840 assert(getEffectiveSCEVType(LHS->getType()) ==
1841 getEffectiveSCEVType(RHS->getType()) &&
1842 "SCEVUDivExpr operand types don't match!");
1844 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1845 if (RHSC->getValue()->equalsInt(1))
1846 return LHS; // X udiv 1 --> x
1848 return getIntegerSCEV(0, LHS->getType()); // value is undefined
1850 // Determine if the division can be folded into the operands of
1852 // TODO: Generalize this to non-constants by using known-bits information.
1853 const Type *Ty = LHS->getType();
1854 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1855 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1856 // For non-power-of-two values, effectively round the value up to the
1857 // nearest power of two.
1858 if (!RHSC->getValue()->getValue().isPowerOf2())
1860 const IntegerType *ExtTy =
1861 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1862 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1863 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1864 if (const SCEVConstant *Step =
1865 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1866 if (!Step->getValue()->getValue()
1867 .urem(RHSC->getValue()->getValue()) &&
1868 getZeroExtendExpr(AR, ExtTy) ==
1869 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1870 getZeroExtendExpr(Step, ExtTy),
1872 SmallVector<const SCEV *, 4> Operands;
1873 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1874 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1875 return getAddRecExpr(Operands, AR->getLoop());
1877 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1878 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1879 SmallVector<const SCEV *, 4> Operands;
1880 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1881 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1882 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1883 // Find an operand that's safely divisible.
1884 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1885 const SCEV *Op = M->getOperand(i);
1886 const SCEV *Div = getUDivExpr(Op, RHSC);
1887 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1888 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), M->op_end());
1890 return getMulExpr(Operands);
1894 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1895 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1896 SmallVector<const SCEV *, 4> Operands;
1897 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1898 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1899 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1901 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1902 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1903 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1905 Operands.push_back(Op);
1907 if (Operands.size() == A->getNumOperands())
1908 return getAddExpr(Operands);
1912 // Fold if both operands are constant.
1913 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1914 Constant *LHSCV = LHSC->getValue();
1915 Constant *RHSCV = RHSC->getValue();
1916 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1921 FoldingSetNodeID ID;
1922 ID.AddInteger(scUDivExpr);
1926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1927 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1928 new (S) SCEVUDivExpr(ID, LHS, RHS);
1929 UniqueSCEVs.InsertNode(S, IP);
1934 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1935 /// Simplify the expression as much as possible.
1936 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1937 const SCEV *Step, const Loop *L,
1938 bool HasNUW, bool HasNSW) {
1939 SmallVector<const SCEV *, 4> Operands;
1940 Operands.push_back(Start);
1941 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1942 if (StepChrec->getLoop() == L) {
1943 Operands.insert(Operands.end(), StepChrec->op_begin(),
1944 StepChrec->op_end());
1945 return getAddRecExpr(Operands, L);
1948 Operands.push_back(Step);
1949 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
1952 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1953 /// Simplify the expression as much as possible.
1955 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1957 bool HasNUW, bool HasNSW) {
1958 if (Operands.size() == 1) return Operands[0];
1960 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1961 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1962 getEffectiveSCEVType(Operands[0]->getType()) &&
1963 "SCEVAddRecExpr operand types don't match!");
1966 if (Operands.back()->isZero()) {
1967 Operands.pop_back();
1968 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
1971 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1972 // use that information to infer NUW and NSW flags. However, computing a
1973 // BE count requires calling getAddRecExpr, so we may not yet have a
1974 // meaningful BE count at this point (and if we don't, we'd be stuck
1975 // with a SCEVCouldNotCompute as the cached BE count).
1977 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1978 if (!HasNUW && HasNSW) {
1980 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1981 if (!isKnownNonNegative(Operands[i])) {
1985 if (All) HasNUW = true;
1988 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1989 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1990 const Loop *NestedLoop = NestedAR->getLoop();
1991 if (L->contains(NestedLoop->getHeader()) ?
1992 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1993 (!NestedLoop->contains(L->getHeader()) &&
1994 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
1995 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
1996 NestedAR->op_end());
1997 Operands[0] = NestedAR->getStart();
1998 // AddRecs require their operands be loop-invariant with respect to their
1999 // loops. Don't perform this transformation if it would break this
2001 bool AllInvariant = true;
2002 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2003 if (!Operands[i]->isLoopInvariant(L)) {
2004 AllInvariant = false;
2008 NestedOperands[0] = getAddRecExpr(Operands, L);
2009 AllInvariant = true;
2010 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2011 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2012 AllInvariant = false;
2016 // Ok, both add recurrences are valid after the transformation.
2017 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2019 // Reset Operands to its original state.
2020 Operands[0] = NestedAR;
2024 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2025 // already have one, otherwise create a new one.
2026 FoldingSetNodeID ID;
2027 ID.AddInteger(scAddRecExpr);
2028 ID.AddInteger(Operands.size());
2029 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2030 ID.AddPointer(Operands[i]);
2034 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2036 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2037 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2038 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2039 new (S) SCEVAddRecExpr(ID, O, Operands.size(), L);
2040 UniqueSCEVs.InsertNode(S, IP);
2042 if (HasNUW) S->setHasNoUnsignedWrap(true);
2043 if (HasNSW) S->setHasNoSignedWrap(true);
2047 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2049 SmallVector<const SCEV *, 2> Ops;
2052 return getSMaxExpr(Ops);
2056 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2057 assert(!Ops.empty() && "Cannot get empty smax!");
2058 if (Ops.size() == 1) return Ops[0];
2060 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2061 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2062 getEffectiveSCEVType(Ops[0]->getType()) &&
2063 "SCEVSMaxExpr operand types don't match!");
2066 // Sort by complexity, this groups all similar expression types together.
2067 GroupByComplexity(Ops, LI);
2069 // If there are any constants, fold them together.
2071 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2073 assert(Idx < Ops.size());
2074 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2075 // We found two constants, fold them together!
2076 ConstantInt *Fold = ConstantInt::get(getContext(),
2077 APIntOps::smax(LHSC->getValue()->getValue(),
2078 RHSC->getValue()->getValue()));
2079 Ops[0] = getConstant(Fold);
2080 Ops.erase(Ops.begin()+1); // Erase the folded element
2081 if (Ops.size() == 1) return Ops[0];
2082 LHSC = cast<SCEVConstant>(Ops[0]);
2085 // If we are left with a constant minimum-int, strip it off.
2086 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2087 Ops.erase(Ops.begin());
2089 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2090 // If we have an smax with a constant maximum-int, it will always be
2096 if (Ops.size() == 1) return Ops[0];
2098 // Find the first SMax
2099 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2102 // Check to see if one of the operands is an SMax. If so, expand its operands
2103 // onto our operand list, and recurse to simplify.
2104 if (Idx < Ops.size()) {
2105 bool DeletedSMax = false;
2106 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2107 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2108 Ops.erase(Ops.begin()+Idx);
2113 return getSMaxExpr(Ops);
2116 // Okay, check to see if the same value occurs in the operand list twice. If
2117 // so, delete one. Since we sorted the list, these values are required to
2119 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2120 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2121 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2125 if (Ops.size() == 1) return Ops[0];
2127 assert(!Ops.empty() && "Reduced smax down to nothing!");
2129 // Okay, it looks like we really DO need an smax expr. Check to see if we
2130 // already have one, otherwise create a new one.
2131 FoldingSetNodeID ID;
2132 ID.AddInteger(scSMaxExpr);
2133 ID.AddInteger(Ops.size());
2134 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2135 ID.AddPointer(Ops[i]);
2137 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2138 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
2139 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2140 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2141 new (S) SCEVSMaxExpr(ID, O, Ops.size());
2142 UniqueSCEVs.InsertNode(S, IP);
2146 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2148 SmallVector<const SCEV *, 2> Ops;
2151 return getUMaxExpr(Ops);
2155 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2156 assert(!Ops.empty() && "Cannot get empty umax!");
2157 if (Ops.size() == 1) return Ops[0];
2159 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2160 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2161 getEffectiveSCEVType(Ops[0]->getType()) &&
2162 "SCEVUMaxExpr operand types don't match!");
2165 // Sort by complexity, this groups all similar expression types together.
2166 GroupByComplexity(Ops, LI);
2168 // If there are any constants, fold them together.
2170 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2172 assert(Idx < Ops.size());
2173 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2174 // We found two constants, fold them together!
2175 ConstantInt *Fold = ConstantInt::get(getContext(),
2176 APIntOps::umax(LHSC->getValue()->getValue(),
2177 RHSC->getValue()->getValue()));
2178 Ops[0] = getConstant(Fold);
2179 Ops.erase(Ops.begin()+1); // Erase the folded element
2180 if (Ops.size() == 1) return Ops[0];
2181 LHSC = cast<SCEVConstant>(Ops[0]);
2184 // If we are left with a constant minimum-int, strip it off.
2185 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2186 Ops.erase(Ops.begin());
2188 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2189 // If we have an umax with a constant maximum-int, it will always be
2195 if (Ops.size() == 1) return Ops[0];
2197 // Find the first UMax
2198 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2201 // Check to see if one of the operands is a UMax. If so, expand its operands
2202 // onto our operand list, and recurse to simplify.
2203 if (Idx < Ops.size()) {
2204 bool DeletedUMax = false;
2205 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2206 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2207 Ops.erase(Ops.begin()+Idx);
2212 return getUMaxExpr(Ops);
2215 // Okay, check to see if the same value occurs in the operand list twice. If
2216 // so, delete one. Since we sorted the list, these values are required to
2218 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2219 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2220 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2224 if (Ops.size() == 1) return Ops[0];
2226 assert(!Ops.empty() && "Reduced umax down to nothing!");
2228 // Okay, it looks like we really DO need a umax expr. Check to see if we
2229 // already have one, otherwise create a new one.
2230 FoldingSetNodeID ID;
2231 ID.AddInteger(scUMaxExpr);
2232 ID.AddInteger(Ops.size());
2233 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2234 ID.AddPointer(Ops[i]);
2236 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2237 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
2238 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2239 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2240 new (S) SCEVUMaxExpr(ID, O, Ops.size());
2241 UniqueSCEVs.InsertNode(S, IP);
2245 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2247 // ~smax(~x, ~y) == smin(x, y).
2248 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2251 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2253 // ~umax(~x, ~y) == umin(x, y)
2254 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2257 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2258 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2259 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2260 C = ConstantFoldConstantExpression(CE, TD);
2261 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2262 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2265 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2266 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2268 C = ConstantFoldConstantExpression(CE, TD);
2269 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2270 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2273 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2275 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2276 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2277 C = ConstantFoldConstantExpression(CE, TD);
2278 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2279 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2282 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2283 Constant *FieldNo) {
2284 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2286 C = ConstantFoldConstantExpression(CE, TD);
2287 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2288 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2291 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2292 // Don't attempt to do anything other than create a SCEVUnknown object
2293 // here. createSCEV only calls getUnknown after checking for all other
2294 // interesting possibilities, and any other code that calls getUnknown
2295 // is doing so in order to hide a value from SCEV canonicalization.
2297 FoldingSetNodeID ID;
2298 ID.AddInteger(scUnknown);
2301 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2302 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2303 new (S) SCEVUnknown(ID, V);
2304 UniqueSCEVs.InsertNode(S, IP);
2308 //===----------------------------------------------------------------------===//
2309 // Basic SCEV Analysis and PHI Idiom Recognition Code
2312 /// isSCEVable - Test if values of the given type are analyzable within
2313 /// the SCEV framework. This primarily includes integer types, and it
2314 /// can optionally include pointer types if the ScalarEvolution class
2315 /// has access to target-specific information.
2316 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2317 // Integers and pointers are always SCEVable.
2318 return Ty->isIntegerTy() || Ty->isPointerTy();
2321 /// getTypeSizeInBits - Return the size in bits of the specified type,
2322 /// for which isSCEVable must return true.
2323 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2324 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2326 // If we have a TargetData, use it!
2328 return TD->getTypeSizeInBits(Ty);
2330 // Integer types have fixed sizes.
2331 if (Ty->isIntegerTy())
2332 return Ty->getPrimitiveSizeInBits();
2334 // The only other support type is pointer. Without TargetData, conservatively
2335 // assume pointers are 64-bit.
2336 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2340 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2341 /// the given type and which represents how SCEV will treat the given
2342 /// type, for which isSCEVable must return true. For pointer types,
2343 /// this is the pointer-sized integer type.
2344 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2345 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2347 if (Ty->isIntegerTy())
2350 // The only other support type is pointer.
2351 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2352 if (TD) return TD->getIntPtrType(getContext());
2354 // Without TargetData, conservatively assume pointers are 64-bit.
2355 return Type::getInt64Ty(getContext());
2358 const SCEV *ScalarEvolution::getCouldNotCompute() {
2359 return &CouldNotCompute;
2362 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2363 /// expression and create a new one.
2364 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2365 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2367 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2368 if (I != Scalars.end()) return I->second;
2369 const SCEV *S = createSCEV(V);
2370 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2374 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
2375 /// specified signed integer value and return a SCEV for the constant.
2376 const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
2377 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2378 return getConstant(ConstantInt::get(ITy, Val));
2381 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2383 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2384 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2386 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2388 const Type *Ty = V->getType();
2389 Ty = getEffectiveSCEVType(Ty);
2390 return getMulExpr(V,
2391 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2394 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2395 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2396 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2398 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2400 const Type *Ty = V->getType();
2401 Ty = getEffectiveSCEVType(Ty);
2402 const SCEV *AllOnes =
2403 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2404 return getMinusSCEV(AllOnes, V);
2407 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2409 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2412 return getAddExpr(LHS, getNegativeSCEV(RHS));
2415 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2416 /// input value to the specified type. If the type must be extended, it is zero
2419 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2421 const Type *SrcTy = V->getType();
2422 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2423 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2424 "Cannot truncate or zero extend with non-integer arguments!");
2425 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2426 return V; // No conversion
2427 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2428 return getTruncateExpr(V, Ty);
2429 return getZeroExtendExpr(V, Ty);
2432 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2433 /// input value to the specified type. If the type must be extended, it is sign
2436 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2438 const Type *SrcTy = V->getType();
2439 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2440 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2441 "Cannot truncate or zero extend with non-integer arguments!");
2442 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2443 return V; // No conversion
2444 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2445 return getTruncateExpr(V, Ty);
2446 return getSignExtendExpr(V, Ty);
2449 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2450 /// input value to the specified type. If the type must be extended, it is zero
2451 /// extended. The conversion must not be narrowing.
2453 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2454 const Type *SrcTy = V->getType();
2455 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2456 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2457 "Cannot noop or zero extend with non-integer arguments!");
2458 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2459 "getNoopOrZeroExtend cannot truncate!");
2460 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2461 return V; // No conversion
2462 return getZeroExtendExpr(V, Ty);
2465 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2466 /// input value to the specified type. If the type must be extended, it is sign
2467 /// extended. The conversion must not be narrowing.
2469 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2470 const Type *SrcTy = V->getType();
2471 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2472 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2473 "Cannot noop or sign extend with non-integer arguments!");
2474 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2475 "getNoopOrSignExtend cannot truncate!");
2476 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2477 return V; // No conversion
2478 return getSignExtendExpr(V, Ty);
2481 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2482 /// the input value to the specified type. If the type must be extended,
2483 /// it is extended with unspecified bits. The conversion must not be
2486 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2487 const Type *SrcTy = V->getType();
2488 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2489 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2490 "Cannot noop or any extend with non-integer arguments!");
2491 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2492 "getNoopOrAnyExtend cannot truncate!");
2493 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2494 return V; // No conversion
2495 return getAnyExtendExpr(V, Ty);
2498 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2499 /// input value to the specified type. The conversion must not be widening.
2501 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2502 const Type *SrcTy = V->getType();
2503 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2504 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2505 "Cannot truncate or noop with non-integer arguments!");
2506 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2507 "getTruncateOrNoop cannot extend!");
2508 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2509 return V; // No conversion
2510 return getTruncateExpr(V, Ty);
2513 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2514 /// the types using zero-extension, and then perform a umax operation
2516 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2518 const SCEV *PromotedLHS = LHS;
2519 const SCEV *PromotedRHS = RHS;
2521 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2522 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2524 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2526 return getUMaxExpr(PromotedLHS, PromotedRHS);
2529 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2530 /// the types using zero-extension, and then perform a umin operation
2532 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2534 const SCEV *PromotedLHS = LHS;
2535 const SCEV *PromotedRHS = RHS;
2537 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2538 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2540 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2542 return getUMinExpr(PromotedLHS, PromotedRHS);
2545 /// PushDefUseChildren - Push users of the given Instruction
2546 /// onto the given Worklist.
2548 PushDefUseChildren(Instruction *I,
2549 SmallVectorImpl<Instruction *> &Worklist) {
2550 // Push the def-use children onto the Worklist stack.
2551 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2553 Worklist.push_back(cast<Instruction>(UI));
2556 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2557 /// instructions that depend on the given instruction and removes them from
2558 /// the Scalars map if they reference SymName. This is used during PHI
2561 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2562 SmallVector<Instruction *, 16> Worklist;
2563 PushDefUseChildren(PN, Worklist);
2565 SmallPtrSet<Instruction *, 8> Visited;
2567 while (!Worklist.empty()) {
2568 Instruction *I = Worklist.pop_back_val();
2569 if (!Visited.insert(I)) continue;
2571 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2572 Scalars.find(static_cast<Value *>(I));
2573 if (It != Scalars.end()) {
2574 // Short-circuit the def-use traversal if the symbolic name
2575 // ceases to appear in expressions.
2576 if (It->second != SymName && !It->second->hasOperand(SymName))
2579 // SCEVUnknown for a PHI either means that it has an unrecognized
2580 // structure, it's a PHI that's in the progress of being computed
2581 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2582 // additional loop trip count information isn't going to change anything.
2583 // In the second case, createNodeForPHI will perform the necessary
2584 // updates on its own when it gets to that point. In the third, we do
2585 // want to forget the SCEVUnknown.
2586 if (!isa<PHINode>(I) ||
2587 !isa<SCEVUnknown>(It->second) ||
2588 (I != PN && It->second == SymName)) {
2589 ValuesAtScopes.erase(It->second);
2594 PushDefUseChildren(I, Worklist);
2598 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2599 /// a loop header, making it a potential recurrence, or it doesn't.
2601 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2602 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
2603 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2604 if (L->getHeader() == PN->getParent()) {
2605 // If it lives in the loop header, it has two incoming values, one
2606 // from outside the loop, and one from inside.
2607 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2608 unsigned BackEdge = IncomingEdge^1;
2610 // While we are analyzing this PHI node, handle its value symbolically.
2611 const SCEV *SymbolicName = getUnknown(PN);
2612 assert(Scalars.find(PN) == Scalars.end() &&
2613 "PHI node already processed?");
2614 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2616 // Using this symbolic name for the PHI, analyze the value coming around
2618 Value *BEValueV = PN->getIncomingValue(BackEdge);
2619 const SCEV *BEValue = getSCEV(BEValueV);
2621 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2622 // has a special value for the first iteration of the loop.
2624 // If the value coming around the backedge is an add with the symbolic
2625 // value we just inserted, then we found a simple induction variable!
2626 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2627 // If there is a single occurrence of the symbolic value, replace it
2628 // with a recurrence.
2629 unsigned FoundIndex = Add->getNumOperands();
2630 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2631 if (Add->getOperand(i) == SymbolicName)
2632 if (FoundIndex == e) {
2637 if (FoundIndex != Add->getNumOperands()) {
2638 // Create an add with everything but the specified operand.
2639 SmallVector<const SCEV *, 8> Ops;
2640 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2641 if (i != FoundIndex)
2642 Ops.push_back(Add->getOperand(i));
2643 const SCEV *Accum = getAddExpr(Ops);
2645 // This is not a valid addrec if the step amount is varying each
2646 // loop iteration, but is not itself an addrec in this loop.
2647 if (Accum->isLoopInvariant(L) ||
2648 (isa<SCEVAddRecExpr>(Accum) &&
2649 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2650 bool HasNUW = false;
2651 bool HasNSW = false;
2653 // If the increment doesn't overflow, then neither the addrec nor
2654 // the post-increment will overflow.
2655 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2656 if (OBO->hasNoUnsignedWrap())
2658 if (OBO->hasNoSignedWrap())
2662 const SCEV *StartVal =
2663 getSCEV(PN->getIncomingValue(IncomingEdge));
2664 const SCEV *PHISCEV =
2665 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2667 // Since the no-wrap flags are on the increment, they apply to the
2668 // post-incremented value as well.
2669 if (Accum->isLoopInvariant(L))
2670 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2671 Accum, L, HasNUW, HasNSW);
2673 // Okay, for the entire analysis of this edge we assumed the PHI
2674 // to be symbolic. We now need to go back and purge all of the
2675 // entries for the scalars that use the symbolic expression.
2676 ForgetSymbolicName(PN, SymbolicName);
2677 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2681 } else if (const SCEVAddRecExpr *AddRec =
2682 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2683 // Otherwise, this could be a loop like this:
2684 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2685 // In this case, j = {1,+,1} and BEValue is j.
2686 // Because the other in-value of i (0) fits the evolution of BEValue
2687 // i really is an addrec evolution.
2688 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2689 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2691 // If StartVal = j.start - j.stride, we can use StartVal as the
2692 // initial step of the addrec evolution.
2693 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2694 AddRec->getOperand(1))) {
2695 const SCEV *PHISCEV =
2696 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2698 // Okay, for the entire analysis of this edge we assumed the PHI
2699 // to be symbolic. We now need to go back and purge all of the
2700 // entries for the scalars that use the symbolic expression.
2701 ForgetSymbolicName(PN, SymbolicName);
2702 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2708 return SymbolicName;
2711 // If the PHI has a single incoming value, follow that value, unless the
2712 // PHI's incoming blocks are in a different loop, in which case doing so
2713 // risks breaking LCSSA form. Instcombine would normally zap these, but
2714 // it doesn't have DominatorTree information, so it may miss cases.
2715 if (Value *V = PN->hasConstantValue(DT)) {
2716 bool AllSameLoop = true;
2717 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2718 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2719 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2720 AllSameLoop = false;
2727 // If it's not a loop phi, we can't handle it yet.
2728 return getUnknown(PN);
2731 /// createNodeForGEP - Expand GEP instructions into add and multiply
2732 /// operations. This allows them to be analyzed by regular SCEV code.
2734 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2736 bool InBounds = GEP->isInBounds();
2737 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2738 Value *Base = GEP->getOperand(0);
2739 // Don't attempt to analyze GEPs over unsized objects.
2740 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2741 return getUnknown(GEP);
2742 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
2743 gep_type_iterator GTI = gep_type_begin(GEP);
2744 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2748 // Compute the (potentially symbolic) offset in bytes for this index.
2749 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2750 // For a struct, add the member offset.
2751 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2752 TotalOffset = getAddExpr(TotalOffset,
2753 getOffsetOfExpr(STy, FieldNo),
2754 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2756 // For an array, add the element offset, explicitly scaled.
2757 const SCEV *LocalOffset = getSCEV(Index);
2758 // Getelementptr indices are signed.
2759 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
2760 // Lower "inbounds" GEPs to NSW arithmetic.
2761 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
2762 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2763 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2764 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2767 return getAddExpr(getSCEV(Base), TotalOffset,
2768 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2771 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2772 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2773 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2774 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2776 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2777 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2778 return C->getValue()->getValue().countTrailingZeros();
2780 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2781 return std::min(GetMinTrailingZeros(T->getOperand()),
2782 (uint32_t)getTypeSizeInBits(T->getType()));
2784 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2785 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2786 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2787 getTypeSizeInBits(E->getType()) : OpRes;
2790 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2791 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2792 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2793 getTypeSizeInBits(E->getType()) : OpRes;
2796 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2797 // The result is the min of all operands results.
2798 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2799 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2800 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2804 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2805 // The result is the sum of all operands results.
2806 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2807 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2808 for (unsigned i = 1, e = M->getNumOperands();
2809 SumOpRes != BitWidth && i != e; ++i)
2810 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2815 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2816 // The result is the min of all operands results.
2817 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2818 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2819 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2823 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2824 // The result is the min of all operands results.
2825 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2826 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2827 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2831 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2832 // The result is the min of all operands results.
2833 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2834 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2835 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2839 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2840 // For a SCEVUnknown, ask ValueTracking.
2841 unsigned BitWidth = getTypeSizeInBits(U->getType());
2842 APInt Mask = APInt::getAllOnesValue(BitWidth);
2843 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2844 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2845 return Zeros.countTrailingOnes();
2852 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2855 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2857 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2858 return ConstantRange(C->getValue()->getValue());
2860 unsigned BitWidth = getTypeSizeInBits(S->getType());
2861 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2863 // If the value has known zeros, the maximum unsigned value will have those
2864 // known zeros as well.
2865 uint32_t TZ = GetMinTrailingZeros(S);
2867 ConservativeResult =
2868 ConstantRange(APInt::getMinValue(BitWidth),
2869 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2871 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2872 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2873 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2874 X = X.add(getUnsignedRange(Add->getOperand(i)));
2875 return ConservativeResult.intersectWith(X);
2878 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2879 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2880 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2881 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2882 return ConservativeResult.intersectWith(X);
2885 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2886 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2887 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2888 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2889 return ConservativeResult.intersectWith(X);
2892 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2893 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2894 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2895 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2896 return ConservativeResult.intersectWith(X);
2899 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2900 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2901 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2902 return ConservativeResult.intersectWith(X.udiv(Y));
2905 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2906 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2907 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
2910 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2911 ConstantRange X = getUnsignedRange(SExt->getOperand());
2912 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
2915 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2916 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2917 return ConservativeResult.intersectWith(X.truncate(BitWidth));
2920 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2921 // If there's no unsigned wrap, the value will never be less than its
2923 if (AddRec->hasNoUnsignedWrap())
2924 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2925 ConservativeResult =
2926 ConstantRange(C->getValue()->getValue(),
2927 APInt(getTypeSizeInBits(C->getType()), 0));
2929 // TODO: non-affine addrec
2930 if (AddRec->isAffine()) {
2931 const Type *Ty = AddRec->getType();
2932 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2933 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2934 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
2935 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2937 const SCEV *Start = AddRec->getStart();
2938 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2940 // Check for overflow.
2941 if (!AddRec->hasNoUnsignedWrap())
2942 return ConservativeResult;
2944 ConstantRange StartRange = getUnsignedRange(Start);
2945 ConstantRange EndRange = getUnsignedRange(End);
2946 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2947 EndRange.getUnsignedMin());
2948 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2949 EndRange.getUnsignedMax());
2950 if (Min.isMinValue() && Max.isMaxValue())
2951 return ConservativeResult;
2952 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
2956 return ConservativeResult;
2959 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2960 // For a SCEVUnknown, ask ValueTracking.
2961 APInt Mask = APInt::getAllOnesValue(BitWidth);
2962 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2963 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2964 if (Ones == ~Zeros + 1)
2965 return ConservativeResult;
2966 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
2969 return ConservativeResult;
2972 /// getSignedRange - Determine the signed range for a particular SCEV.
2975 ScalarEvolution::getSignedRange(const SCEV *S) {
2977 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2978 return ConstantRange(C->getValue()->getValue());
2980 unsigned BitWidth = getTypeSizeInBits(S->getType());
2981 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2983 // If the value has known zeros, the maximum signed value will have those
2984 // known zeros as well.
2985 uint32_t TZ = GetMinTrailingZeros(S);
2987 ConservativeResult =
2988 ConstantRange(APInt::getSignedMinValue(BitWidth),
2989 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2991 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2992 ConstantRange X = getSignedRange(Add->getOperand(0));
2993 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2994 X = X.add(getSignedRange(Add->getOperand(i)));
2995 return ConservativeResult.intersectWith(X);
2998 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2999 ConstantRange X = getSignedRange(Mul->getOperand(0));
3000 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3001 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3002 return ConservativeResult.intersectWith(X);
3005 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3006 ConstantRange X = getSignedRange(SMax->getOperand(0));
3007 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3008 X = X.smax(getSignedRange(SMax->getOperand(i)));
3009 return ConservativeResult.intersectWith(X);
3012 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3013 ConstantRange X = getSignedRange(UMax->getOperand(0));
3014 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3015 X = X.umax(getSignedRange(UMax->getOperand(i)));
3016 return ConservativeResult.intersectWith(X);
3019 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3020 ConstantRange X = getSignedRange(UDiv->getLHS());
3021 ConstantRange Y = getSignedRange(UDiv->getRHS());
3022 return ConservativeResult.intersectWith(X.udiv(Y));
3025 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3026 ConstantRange X = getSignedRange(ZExt->getOperand());
3027 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3030 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3031 ConstantRange X = getSignedRange(SExt->getOperand());
3032 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3035 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3036 ConstantRange X = getSignedRange(Trunc->getOperand());
3037 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3040 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3041 // If there's no signed wrap, and all the operands have the same sign or
3042 // zero, the value won't ever change sign.
3043 if (AddRec->hasNoSignedWrap()) {
3044 bool AllNonNeg = true;
3045 bool AllNonPos = true;
3046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3047 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3048 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3051 ConservativeResult = ConservativeResult.intersectWith(
3052 ConstantRange(APInt(BitWidth, 0),
3053 APInt::getSignedMinValue(BitWidth)));
3055 ConservativeResult = ConservativeResult.intersectWith(
3056 ConstantRange(APInt::getSignedMinValue(BitWidth),
3057 APInt(BitWidth, 1)));
3060 // TODO: non-affine addrec
3061 if (AddRec->isAffine()) {
3062 const Type *Ty = AddRec->getType();
3063 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3064 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3065 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3066 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3068 const SCEV *Start = AddRec->getStart();
3069 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3071 // Check for overflow.
3072 if (!AddRec->hasNoSignedWrap())
3073 return ConservativeResult;
3075 ConstantRange StartRange = getSignedRange(Start);
3076 ConstantRange EndRange = getSignedRange(End);
3077 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3078 EndRange.getSignedMin());
3079 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3080 EndRange.getSignedMax());
3081 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3082 return ConservativeResult;
3083 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3087 return ConservativeResult;
3090 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3091 // For a SCEVUnknown, ask ValueTracking.
3092 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3093 return ConservativeResult;
3094 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3096 return ConservativeResult;
3097 return ConservativeResult.intersectWith(
3098 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3099 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3102 return ConservativeResult;
3105 /// createSCEV - We know that there is no SCEV for the specified value.
3106 /// Analyze the expression.
3108 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3109 if (!isSCEVable(V->getType()))
3110 return getUnknown(V);
3112 unsigned Opcode = Instruction::UserOp1;
3113 if (Instruction *I = dyn_cast<Instruction>(V)) {
3114 Opcode = I->getOpcode();
3116 // Don't attempt to analyze instructions in blocks that aren't
3117 // reachable. Such instructions don't matter, and they aren't required
3118 // to obey basic rules for definitions dominating uses which this
3119 // analysis depends on.
3120 if (!DT->isReachableFromEntry(I->getParent()))
3121 return getUnknown(V);
3122 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3123 Opcode = CE->getOpcode();
3124 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3125 return getConstant(CI);
3126 else if (isa<ConstantPointerNull>(V))
3127 return getIntegerSCEV(0, V->getType());
3128 else if (isa<UndefValue>(V))
3129 return getIntegerSCEV(0, V->getType());
3130 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3131 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3133 return getUnknown(V);
3135 Operator *U = cast<Operator>(V);
3137 case Instruction::Add:
3138 // Don't transfer the NSW and NUW bits from the Add instruction to the
3139 // Add expression, because the Instruction may be guarded by control
3140 // flow and the no-overflow bits may not be valid for the expression in
3142 return getAddExpr(getSCEV(U->getOperand(0)),
3143 getSCEV(U->getOperand(1)));
3144 case Instruction::Mul:
3145 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3146 // Mul expression, as with Add.
3147 return getMulExpr(getSCEV(U->getOperand(0)),
3148 getSCEV(U->getOperand(1)));
3149 case Instruction::UDiv:
3150 return getUDivExpr(getSCEV(U->getOperand(0)),
3151 getSCEV(U->getOperand(1)));
3152 case Instruction::Sub:
3153 return getMinusSCEV(getSCEV(U->getOperand(0)),
3154 getSCEV(U->getOperand(1)));
3155 case Instruction::And:
3156 // For an expression like x&255 that merely masks off the high bits,
3157 // use zext(trunc(x)) as the SCEV expression.
3158 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3159 if (CI->isNullValue())
3160 return getSCEV(U->getOperand(1));
3161 if (CI->isAllOnesValue())
3162 return getSCEV(U->getOperand(0));
3163 const APInt &A = CI->getValue();
3165 // Instcombine's ShrinkDemandedConstant may strip bits out of
3166 // constants, obscuring what would otherwise be a low-bits mask.
3167 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3168 // knew about to reconstruct a low-bits mask value.
3169 unsigned LZ = A.countLeadingZeros();
3170 unsigned BitWidth = A.getBitWidth();
3171 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3172 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3173 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3175 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3177 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3179 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3180 IntegerType::get(getContext(), BitWidth - LZ)),
3185 case Instruction::Or:
3186 // If the RHS of the Or is a constant, we may have something like:
3187 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3188 // optimizations will transparently handle this case.
3190 // In order for this transformation to be safe, the LHS must be of the
3191 // form X*(2^n) and the Or constant must be less than 2^n.
3192 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3193 const SCEV *LHS = getSCEV(U->getOperand(0));
3194 const APInt &CIVal = CI->getValue();
3195 if (GetMinTrailingZeros(LHS) >=
3196 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3197 // Build a plain add SCEV.
3198 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3199 // If the LHS of the add was an addrec and it has no-wrap flags,
3200 // transfer the no-wrap flags, since an or won't introduce a wrap.
3201 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3202 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3203 if (OldAR->hasNoUnsignedWrap())
3204 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3205 if (OldAR->hasNoSignedWrap())
3206 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3212 case Instruction::Xor:
3213 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3214 // If the RHS of the xor is a signbit, then this is just an add.
3215 // Instcombine turns add of signbit into xor as a strength reduction step.
3216 if (CI->getValue().isSignBit())
3217 return getAddExpr(getSCEV(U->getOperand(0)),
3218 getSCEV(U->getOperand(1)));
3220 // If the RHS of xor is -1, then this is a not operation.
3221 if (CI->isAllOnesValue())
3222 return getNotSCEV(getSCEV(U->getOperand(0)));
3224 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3225 // This is a variant of the check for xor with -1, and it handles
3226 // the case where instcombine has trimmed non-demanded bits out
3227 // of an xor with -1.
3228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3229 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3230 if (BO->getOpcode() == Instruction::And &&
3231 LCI->getValue() == CI->getValue())
3232 if (const SCEVZeroExtendExpr *Z =
3233 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3234 const Type *UTy = U->getType();
3235 const SCEV *Z0 = Z->getOperand();
3236 const Type *Z0Ty = Z0->getType();
3237 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3239 // If C is a low-bits mask, the zero extend is serving to
3240 // mask off the high bits. Complement the operand and
3241 // re-apply the zext.
3242 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3243 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3245 // If C is a single bit, it may be in the sign-bit position
3246 // before the zero-extend. In this case, represent the xor
3247 // using an add, which is equivalent, and re-apply the zext.
3248 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3249 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3251 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3257 case Instruction::Shl:
3258 // Turn shift left of a constant amount into a multiply.
3259 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3260 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3261 Constant *X = ConstantInt::get(getContext(),
3262 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3263 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3267 case Instruction::LShr:
3268 // Turn logical shift right of a constant into a unsigned divide.
3269 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3270 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3271 Constant *X = ConstantInt::get(getContext(),
3272 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
3273 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3277 case Instruction::AShr:
3278 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3279 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3280 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3281 if (L->getOpcode() == Instruction::Shl &&
3282 L->getOperand(1) == U->getOperand(1)) {
3283 unsigned BitWidth = getTypeSizeInBits(U->getType());
3284 uint64_t Amt = BitWidth - CI->getZExtValue();
3285 if (Amt == BitWidth)
3286 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3288 return getIntegerSCEV(0, U->getType()); // value is undefined
3290 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3291 IntegerType::get(getContext(), Amt)),
3296 case Instruction::Trunc:
3297 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3299 case Instruction::ZExt:
3300 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3302 case Instruction::SExt:
3303 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3305 case Instruction::BitCast:
3306 // BitCasts are no-op casts so we just eliminate the cast.
3307 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3308 return getSCEV(U->getOperand(0));
3311 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3312 // lead to pointer expressions which cannot safely be expanded to GEPs,
3313 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3314 // simplifying integer expressions.
3316 case Instruction::GetElementPtr:
3317 return createNodeForGEP(cast<GEPOperator>(U));
3319 case Instruction::PHI:
3320 return createNodeForPHI(cast<PHINode>(U));
3322 case Instruction::Select:
3323 // This could be a smax or umax that was lowered earlier.
3324 // Try to recover it.
3325 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3326 Value *LHS = ICI->getOperand(0);
3327 Value *RHS = ICI->getOperand(1);
3328 switch (ICI->getPredicate()) {
3329 case ICmpInst::ICMP_SLT:
3330 case ICmpInst::ICMP_SLE:
3331 std::swap(LHS, RHS);
3333 case ICmpInst::ICMP_SGT:
3334 case ICmpInst::ICMP_SGE:
3335 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3336 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
3337 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3338 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
3340 case ICmpInst::ICMP_ULT:
3341 case ICmpInst::ICMP_ULE:
3342 std::swap(LHS, RHS);
3344 case ICmpInst::ICMP_UGT:
3345 case ICmpInst::ICMP_UGE:
3346 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
3347 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
3348 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
3349 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
3351 case ICmpInst::ICMP_NE:
3352 // n != 0 ? n : 1 -> umax(n, 1)
3353 if (LHS == U->getOperand(1) &&
3354 isa<ConstantInt>(U->getOperand(2)) &&
3355 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3356 isa<ConstantInt>(RHS) &&
3357 cast<ConstantInt>(RHS)->isZero())
3358 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3360 case ICmpInst::ICMP_EQ:
3361 // n == 0 ? 1 : n -> umax(n, 1)
3362 if (LHS == U->getOperand(2) &&
3363 isa<ConstantInt>(U->getOperand(1)) &&
3364 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3365 isa<ConstantInt>(RHS) &&
3366 cast<ConstantInt>(RHS)->isZero())
3367 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3374 default: // We cannot analyze this expression.
3378 return getUnknown(V);
3383 //===----------------------------------------------------------------------===//
3384 // Iteration Count Computation Code
3387 /// getBackedgeTakenCount - If the specified loop has a predictable
3388 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3389 /// object. The backedge-taken count is the number of times the loop header
3390 /// will be branched to from within the loop. This is one less than the
3391 /// trip count of the loop, since it doesn't count the first iteration,
3392 /// when the header is branched to from outside the loop.
3394 /// Note that it is not valid to call this method on a loop without a
3395 /// loop-invariant backedge-taken count (see
3396 /// hasLoopInvariantBackedgeTakenCount).
3398 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3399 return getBackedgeTakenInfo(L).Exact;
3402 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3403 /// return the least SCEV value that is known never to be less than the
3404 /// actual backedge taken count.
3405 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3406 return getBackedgeTakenInfo(L).Max;
3409 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3410 /// onto the given Worklist.
3412 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3413 BasicBlock *Header = L->getHeader();
3415 // Push all Loop-header PHIs onto the Worklist stack.
3416 for (BasicBlock::iterator I = Header->begin();
3417 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3418 Worklist.push_back(PN);
3421 const ScalarEvolution::BackedgeTakenInfo &
3422 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3423 // Initially insert a CouldNotCompute for this loop. If the insertion
3424 // succeeds, proceed to actually compute a backedge-taken count and
3425 // update the value. The temporary CouldNotCompute value tells SCEV
3426 // code elsewhere that it shouldn't attempt to request a new
3427 // backedge-taken count, which could result in infinite recursion.
3428 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3429 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3431 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3432 if (BECount.Exact != getCouldNotCompute()) {
3433 assert(BECount.Exact->isLoopInvariant(L) &&
3434 BECount.Max->isLoopInvariant(L) &&
3435 "Computed backedge-taken count isn't loop invariant for loop!");
3436 ++NumTripCountsComputed;
3438 // Update the value in the map.
3439 Pair.first->second = BECount;
3441 if (BECount.Max != getCouldNotCompute())
3442 // Update the value in the map.
3443 Pair.first->second = BECount;
3444 if (isa<PHINode>(L->getHeader()->begin()))
3445 // Only count loops that have phi nodes as not being computable.
3446 ++NumTripCountsNotComputed;
3449 // Now that we know more about the trip count for this loop, forget any
3450 // existing SCEV values for PHI nodes in this loop since they are only
3451 // conservative estimates made without the benefit of trip count
3452 // information. This is similar to the code in forgetLoop, except that
3453 // it handles SCEVUnknown PHI nodes specially.
3454 if (BECount.hasAnyInfo()) {
3455 SmallVector<Instruction *, 16> Worklist;
3456 PushLoopPHIs(L, Worklist);
3458 SmallPtrSet<Instruction *, 8> Visited;
3459 while (!Worklist.empty()) {
3460 Instruction *I = Worklist.pop_back_val();
3461 if (!Visited.insert(I)) continue;
3463 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3464 Scalars.find(static_cast<Value *>(I));
3465 if (It != Scalars.end()) {
3466 // SCEVUnknown for a PHI either means that it has an unrecognized
3467 // structure, or it's a PHI that's in the progress of being computed
3468 // by createNodeForPHI. In the former case, additional loop trip
3469 // count information isn't going to change anything. In the later
3470 // case, createNodeForPHI will perform the necessary updates on its
3471 // own when it gets to that point.
3472 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3473 ValuesAtScopes.erase(It->second);
3476 if (PHINode *PN = dyn_cast<PHINode>(I))
3477 ConstantEvolutionLoopExitValue.erase(PN);
3480 PushDefUseChildren(I, Worklist);
3484 return Pair.first->second;
3487 /// forgetLoop - This method should be called by the client when it has
3488 /// changed a loop in a way that may effect ScalarEvolution's ability to
3489 /// compute a trip count, or if the loop is deleted.
3490 void ScalarEvolution::forgetLoop(const Loop *L) {
3491 // Drop any stored trip count value.
3492 BackedgeTakenCounts.erase(L);
3494 // Drop information about expressions based on loop-header PHIs.
3495 SmallVector<Instruction *, 16> Worklist;
3496 PushLoopPHIs(L, Worklist);
3498 SmallPtrSet<Instruction *, 8> Visited;
3499 while (!Worklist.empty()) {
3500 Instruction *I = Worklist.pop_back_val();
3501 if (!Visited.insert(I)) continue;
3503 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3504 Scalars.find(static_cast<Value *>(I));
3505 if (It != Scalars.end()) {
3506 ValuesAtScopes.erase(It->second);
3508 if (PHINode *PN = dyn_cast<PHINode>(I))
3509 ConstantEvolutionLoopExitValue.erase(PN);
3512 PushDefUseChildren(I, Worklist);
3516 /// forgetValue - This method should be called by the client when it has
3517 /// changed a value in a way that may effect its value, or which may
3518 /// disconnect it from a def-use chain linking it to a loop.
3519 void ScalarEvolution::forgetValue(Value *V) {
3520 Instruction *I = dyn_cast<Instruction>(V);
3523 // Drop information about expressions based on loop-header PHIs.
3524 SmallVector<Instruction *, 16> Worklist;
3525 Worklist.push_back(I);
3527 SmallPtrSet<Instruction *, 8> Visited;
3528 while (!Worklist.empty()) {
3529 I = Worklist.pop_back_val();
3530 if (!Visited.insert(I)) continue;
3532 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3533 Scalars.find(static_cast<Value *>(I));
3534 if (It != Scalars.end()) {
3535 ValuesAtScopes.erase(It->second);
3537 if (PHINode *PN = dyn_cast<PHINode>(I))
3538 ConstantEvolutionLoopExitValue.erase(PN);
3541 PushDefUseChildren(I, Worklist);
3545 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3546 /// of the specified loop will execute.
3547 ScalarEvolution::BackedgeTakenInfo
3548 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3549 SmallVector<BasicBlock *, 8> ExitingBlocks;
3550 L->getExitingBlocks(ExitingBlocks);
3552 // Examine all exits and pick the most conservative values.
3553 const SCEV *BECount = getCouldNotCompute();
3554 const SCEV *MaxBECount = getCouldNotCompute();
3555 bool CouldNotComputeBECount = false;
3556 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3557 BackedgeTakenInfo NewBTI =
3558 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3560 if (NewBTI.Exact == getCouldNotCompute()) {
3561 // We couldn't compute an exact value for this exit, so
3562 // we won't be able to compute an exact value for the loop.
3563 CouldNotComputeBECount = true;
3564 BECount = getCouldNotCompute();
3565 } else if (!CouldNotComputeBECount) {
3566 if (BECount == getCouldNotCompute())
3567 BECount = NewBTI.Exact;
3569 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3571 if (MaxBECount == getCouldNotCompute())
3572 MaxBECount = NewBTI.Max;
3573 else if (NewBTI.Max != getCouldNotCompute())
3574 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3577 return BackedgeTakenInfo(BECount, MaxBECount);
3580 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3581 /// of the specified loop will execute if it exits via the specified block.
3582 ScalarEvolution::BackedgeTakenInfo
3583 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3584 BasicBlock *ExitingBlock) {
3586 // Okay, we've chosen an exiting block. See what condition causes us to
3587 // exit at this block.
3589 // FIXME: we should be able to handle switch instructions (with a single exit)
3590 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3591 if (ExitBr == 0) return getCouldNotCompute();
3592 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3594 // At this point, we know we have a conditional branch that determines whether
3595 // the loop is exited. However, we don't know if the branch is executed each
3596 // time through the loop. If not, then the execution count of the branch will
3597 // not be equal to the trip count of the loop.
3599 // Currently we check for this by checking to see if the Exit branch goes to
3600 // the loop header. If so, we know it will always execute the same number of
3601 // times as the loop. We also handle the case where the exit block *is* the
3602 // loop header. This is common for un-rotated loops.
3604 // If both of those tests fail, walk up the unique predecessor chain to the
3605 // header, stopping if there is an edge that doesn't exit the loop. If the
3606 // header is reached, the execution count of the branch will be equal to the
3607 // trip count of the loop.
3609 // More extensive analysis could be done to handle more cases here.
3611 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3612 ExitBr->getSuccessor(1) != L->getHeader() &&
3613 ExitBr->getParent() != L->getHeader()) {
3614 // The simple checks failed, try climbing the unique predecessor chain
3615 // up to the header.
3617 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3618 BasicBlock *Pred = BB->getUniquePredecessor();
3620 return getCouldNotCompute();
3621 TerminatorInst *PredTerm = Pred->getTerminator();
3622 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3623 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3626 // If the predecessor has a successor that isn't BB and isn't
3627 // outside the loop, assume the worst.
3628 if (L->contains(PredSucc))
3629 return getCouldNotCompute();
3631 if (Pred == L->getHeader()) {
3638 return getCouldNotCompute();
3641 // Proceed to the next level to examine the exit condition expression.
3642 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3643 ExitBr->getSuccessor(0),
3644 ExitBr->getSuccessor(1));
3647 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3648 /// backedge of the specified loop will execute if its exit condition
3649 /// were a conditional branch of ExitCond, TBB, and FBB.
3650 ScalarEvolution::BackedgeTakenInfo
3651 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3655 // Check if the controlling expression for this loop is an And or Or.
3656 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3657 if (BO->getOpcode() == Instruction::And) {
3658 // Recurse on the operands of the and.
3659 BackedgeTakenInfo BTI0 =
3660 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3661 BackedgeTakenInfo BTI1 =
3662 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3663 const SCEV *BECount = getCouldNotCompute();
3664 const SCEV *MaxBECount = getCouldNotCompute();
3665 if (L->contains(TBB)) {
3666 // Both conditions must be true for the loop to continue executing.
3667 // Choose the less conservative count.
3668 if (BTI0.Exact == getCouldNotCompute() ||
3669 BTI1.Exact == getCouldNotCompute())
3670 BECount = getCouldNotCompute();
3672 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3673 if (BTI0.Max == getCouldNotCompute())
3674 MaxBECount = BTI1.Max;
3675 else if (BTI1.Max == getCouldNotCompute())
3676 MaxBECount = BTI0.Max;
3678 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3680 // Both conditions must be true for the loop to exit.
3681 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3682 if (BTI0.Exact != getCouldNotCompute() &&
3683 BTI1.Exact != getCouldNotCompute())
3684 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3685 if (BTI0.Max != getCouldNotCompute() &&
3686 BTI1.Max != getCouldNotCompute())
3687 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3690 return BackedgeTakenInfo(BECount, MaxBECount);
3692 if (BO->getOpcode() == Instruction::Or) {
3693 // Recurse on the operands of the or.
3694 BackedgeTakenInfo BTI0 =
3695 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3696 BackedgeTakenInfo BTI1 =
3697 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3698 const SCEV *BECount = getCouldNotCompute();
3699 const SCEV *MaxBECount = getCouldNotCompute();
3700 if (L->contains(FBB)) {
3701 // Both conditions must be false for the loop to continue executing.
3702 // Choose the less conservative count.
3703 if (BTI0.Exact == getCouldNotCompute() ||
3704 BTI1.Exact == getCouldNotCompute())
3705 BECount = getCouldNotCompute();
3707 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3708 if (BTI0.Max == getCouldNotCompute())
3709 MaxBECount = BTI1.Max;
3710 else if (BTI1.Max == getCouldNotCompute())
3711 MaxBECount = BTI0.Max;
3713 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3715 // Both conditions must be false for the loop to exit.
3716 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3717 if (BTI0.Exact != getCouldNotCompute() &&
3718 BTI1.Exact != getCouldNotCompute())
3719 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3720 if (BTI0.Max != getCouldNotCompute() &&
3721 BTI1.Max != getCouldNotCompute())
3722 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3725 return BackedgeTakenInfo(BECount, MaxBECount);
3729 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3730 // Proceed to the next level to examine the icmp.
3731 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3732 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3734 // Check for a constant condition. These are normally stripped out by
3735 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3736 // preserve the CFG and is temporarily leaving constant conditions
3738 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3739 if (L->contains(FBB) == !CI->getZExtValue())
3740 // The backedge is always taken.
3741 return getCouldNotCompute();
3743 // The backedge is never taken.
3744 return getIntegerSCEV(0, CI->getType());
3747 // If it's not an integer or pointer comparison then compute it the hard way.
3748 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3751 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3752 /// backedge of the specified loop will execute if its exit condition
3753 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3754 ScalarEvolution::BackedgeTakenInfo
3755 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3760 // If the condition was exit on true, convert the condition to exit on false
3761 ICmpInst::Predicate Cond;
3762 if (!L->contains(FBB))
3763 Cond = ExitCond->getPredicate();
3765 Cond = ExitCond->getInversePredicate();
3767 // Handle common loops like: for (X = "string"; *X; ++X)
3768 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3769 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3770 BackedgeTakenInfo ItCnt =
3771 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3772 if (ItCnt.hasAnyInfo())
3776 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3777 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3779 // Try to evaluate any dependencies out of the loop.
3780 LHS = getSCEVAtScope(LHS, L);
3781 RHS = getSCEVAtScope(RHS, L);
3783 // At this point, we would like to compute how many iterations of the
3784 // loop the predicate will return true for these inputs.
3785 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3786 // If there is a loop-invariant, force it into the RHS.
3787 std::swap(LHS, RHS);
3788 Cond = ICmpInst::getSwappedPredicate(Cond);
3791 // If we have a comparison of a chrec against a constant, try to use value
3792 // ranges to answer this query.
3793 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3794 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3795 if (AddRec->getLoop() == L) {
3796 // Form the constant range.
3797 ConstantRange CompRange(
3798 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3800 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3801 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3805 case ICmpInst::ICMP_NE: { // while (X != Y)
3806 // Convert to: while (X-Y != 0)
3807 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3808 if (BTI.hasAnyInfo()) return BTI;
3811 case ICmpInst::ICMP_EQ: { // while (X == Y)
3812 // Convert to: while (X-Y == 0)
3813 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3814 if (BTI.hasAnyInfo()) return BTI;
3817 case ICmpInst::ICMP_SLT: {
3818 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3819 if (BTI.hasAnyInfo()) return BTI;
3822 case ICmpInst::ICMP_SGT: {
3823 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3824 getNotSCEV(RHS), L, true);
3825 if (BTI.hasAnyInfo()) return BTI;
3828 case ICmpInst::ICMP_ULT: {
3829 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3830 if (BTI.hasAnyInfo()) return BTI;
3833 case ICmpInst::ICMP_UGT: {
3834 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3835 getNotSCEV(RHS), L, false);
3836 if (BTI.hasAnyInfo()) return BTI;
3841 dbgs() << "ComputeBackedgeTakenCount ";
3842 if (ExitCond->getOperand(0)->getType()->isUnsigned())
3843 dbgs() << "[unsigned] ";
3844 dbgs() << *LHS << " "
3845 << Instruction::getOpcodeName(Instruction::ICmp)
3846 << " " << *RHS << "\n";
3851 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3854 static ConstantInt *
3855 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3856 ScalarEvolution &SE) {
3857 const SCEV *InVal = SE.getConstant(C);
3858 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
3859 assert(isa<SCEVConstant>(Val) &&
3860 "Evaluation of SCEV at constant didn't fold correctly?");
3861 return cast<SCEVConstant>(Val)->getValue();
3864 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
3865 /// and a GEP expression (missing the pointer index) indexing into it, return
3866 /// the addressed element of the initializer or null if the index expression is
3869 GetAddressedElementFromGlobal(GlobalVariable *GV,
3870 const std::vector<ConstantInt*> &Indices) {
3871 Constant *Init = GV->getInitializer();
3872 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3873 uint64_t Idx = Indices[i]->getZExtValue();
3874 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3875 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3876 Init = cast<Constant>(CS->getOperand(Idx));
3877 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3878 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3879 Init = cast<Constant>(CA->getOperand(Idx));
3880 } else if (isa<ConstantAggregateZero>(Init)) {
3881 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3882 assert(Idx < STy->getNumElements() && "Bad struct index!");
3883 Init = Constant::getNullValue(STy->getElementType(Idx));
3884 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3885 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3886 Init = Constant::getNullValue(ATy->getElementType());
3888 llvm_unreachable("Unknown constant aggregate type!");
3892 return 0; // Unknown initializer type
3898 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3899 /// 'icmp op load X, cst', try to see if we can compute the backedge
3900 /// execution count.
3901 ScalarEvolution::BackedgeTakenInfo
3902 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3906 ICmpInst::Predicate predicate) {
3907 if (LI->isVolatile()) return getCouldNotCompute();
3909 // Check to see if the loaded pointer is a getelementptr of a global.
3910 // TODO: Use SCEV instead of manually grubbing with GEPs.
3911 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
3912 if (!GEP) return getCouldNotCompute();
3914 // Make sure that it is really a constant global we are gepping, with an
3915 // initializer, and make sure the first IDX is really 0.
3916 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3917 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
3918 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3919 !cast<Constant>(GEP->getOperand(1))->isNullValue())
3920 return getCouldNotCompute();
3922 // Okay, we allow one non-constant index into the GEP instruction.
3924 std::vector<ConstantInt*> Indexes;
3925 unsigned VarIdxNum = 0;
3926 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3927 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3928 Indexes.push_back(CI);
3929 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
3930 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
3931 VarIdx = GEP->getOperand(i);
3933 Indexes.push_back(0);
3936 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3937 // Check to see if X is a loop variant variable value now.
3938 const SCEV *Idx = getSCEV(VarIdx);
3939 Idx = getSCEVAtScope(Idx, L);
3941 // We can only recognize very limited forms of loop index expressions, in
3942 // particular, only affine AddRec's like {C1,+,C2}.
3943 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
3944 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3945 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3946 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
3947 return getCouldNotCompute();
3949 unsigned MaxSteps = MaxBruteForceIterations;
3950 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3951 ConstantInt *ItCst = ConstantInt::get(
3952 cast<IntegerType>(IdxExpr->getType()), IterationNum);
3953 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
3955 // Form the GEP offset.
3956 Indexes[VarIdxNum] = Val;
3958 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3959 if (Result == 0) break; // Cannot compute!
3961 // Evaluate the condition for this iteration.
3962 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3963 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3964 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3966 dbgs() << "\n***\n*** Computed loop count " << *ItCst
3967 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3970 ++NumArrayLenItCounts;
3971 return getConstant(ItCst); // Found terminating iteration!
3974 return getCouldNotCompute();
3978 /// CanConstantFold - Return true if we can constant fold an instruction of the
3979 /// specified type, assuming that all operands were constants.
3980 static bool CanConstantFold(const Instruction *I) {
3981 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3982 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3985 if (const CallInst *CI = dyn_cast<CallInst>(I))
3986 if (const Function *F = CI->getCalledFunction())
3987 return canConstantFoldCallTo(F);
3991 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3992 /// in the loop that V is derived from. We allow arbitrary operations along the
3993 /// way, but the operands of an operation must either be constants or a value
3994 /// derived from a constant PHI. If this expression does not fit with these
3995 /// constraints, return null.
3996 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3997 // If this is not an instruction, or if this is an instruction outside of the
3998 // loop, it can't be derived from a loop PHI.
3999 Instruction *I = dyn_cast<Instruction>(V);
4000 if (I == 0 || !L->contains(I)) return 0;
4002 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4003 if (L->getHeader() == I->getParent())
4006 // We don't currently keep track of the control flow needed to evaluate
4007 // PHIs, so we cannot handle PHIs inside of loops.
4011 // If we won't be able to constant fold this expression even if the operands
4012 // are constants, return early.
4013 if (!CanConstantFold(I)) return 0;
4015 // Otherwise, we can evaluate this instruction if all of its operands are
4016 // constant or derived from a PHI node themselves.
4018 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4019 if (!(isa<Constant>(I->getOperand(Op)) ||
4020 isa<GlobalValue>(I->getOperand(Op)))) {
4021 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4022 if (P == 0) return 0; // Not evolving from PHI
4026 return 0; // Evolving from multiple different PHIs.
4029 // This is a expression evolving from a constant PHI!
4033 /// EvaluateExpression - Given an expression that passes the
4034 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4035 /// in the loop has the value PHIVal. If we can't fold this expression for some
4036 /// reason, return null.
4037 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4038 const TargetData *TD) {
4039 if (isa<PHINode>(V)) return PHIVal;
4040 if (Constant *C = dyn_cast<Constant>(V)) return C;
4041 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
4042 Instruction *I = cast<Instruction>(V);
4044 std::vector<Constant*> Operands;
4045 Operands.resize(I->getNumOperands());
4047 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4048 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4049 if (Operands[i] == 0) return 0;
4052 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4053 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4055 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4056 &Operands[0], Operands.size(), TD);
4059 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4060 /// in the header of its containing loop, we know the loop executes a
4061 /// constant number of times, and the PHI node is just a recurrence
4062 /// involving constants, fold it.
4064 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4067 std::map<PHINode*, Constant*>::iterator I =
4068 ConstantEvolutionLoopExitValue.find(PN);
4069 if (I != ConstantEvolutionLoopExitValue.end())
4072 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
4073 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4075 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4077 // Since the loop is canonicalized, the PHI node must have two entries. One
4078 // entry must be a constant (coming in from outside of the loop), and the
4079 // second must be derived from the same PHI.
4080 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4081 Constant *StartCST =
4082 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4084 return RetVal = 0; // Must be a constant.
4086 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4087 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4089 return RetVal = 0; // Not derived from same PHI.
4091 // Execute the loop symbolically to determine the exit value.
4092 if (BEs.getActiveBits() >= 32)
4093 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4095 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4096 unsigned IterationNum = 0;
4097 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4098 if (IterationNum == NumIterations)
4099 return RetVal = PHIVal; // Got exit value!
4101 // Compute the value of the PHI node for the next iteration.
4102 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4103 if (NextPHI == PHIVal)
4104 return RetVal = NextPHI; // Stopped evolving!
4106 return 0; // Couldn't evaluate!
4111 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4112 /// constant number of times (the condition evolves only from constants),
4113 /// try to evaluate a few iterations of the loop until we get the exit
4114 /// condition gets a value of ExitWhen (true or false). If we cannot
4115 /// evaluate the trip count of the loop, return getCouldNotCompute().
4117 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4120 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4121 if (PN == 0) return getCouldNotCompute();
4123 // Since the loop is canonicalized, the PHI node must have two entries. One
4124 // entry must be a constant (coming in from outside of the loop), and the
4125 // second must be derived from the same PHI.
4126 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4127 Constant *StartCST =
4128 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4129 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4131 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4132 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4133 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
4135 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4136 // the loop symbolically to determine when the condition gets a value of
4138 unsigned IterationNum = 0;
4139 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4140 for (Constant *PHIVal = StartCST;
4141 IterationNum != MaxIterations; ++IterationNum) {
4142 ConstantInt *CondVal =
4143 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4145 // Couldn't symbolically evaluate.
4146 if (!CondVal) return getCouldNotCompute();
4148 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4149 ++NumBruteForceTripCountsComputed;
4150 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4153 // Compute the value of the PHI node for the next iteration.
4154 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4155 if (NextPHI == 0 || NextPHI == PHIVal)
4156 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4160 // Too many iterations were needed to evaluate.
4161 return getCouldNotCompute();
4164 /// getSCEVAtScope - Return a SCEV expression for the specified value
4165 /// at the specified scope in the program. The L value specifies a loop
4166 /// nest to evaluate the expression at, where null is the top-level or a
4167 /// specified loop is immediately inside of the loop.
4169 /// This method can be used to compute the exit value for a variable defined
4170 /// in a loop by querying what the value will hold in the parent loop.
4172 /// In the case that a relevant loop exit value cannot be computed, the
4173 /// original value V is returned.
4174 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4175 // Check to see if we've folded this expression at this loop before.
4176 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4177 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4178 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4180 return Pair.first->second ? Pair.first->second : V;
4182 // Otherwise compute it.
4183 const SCEV *C = computeSCEVAtScope(V, L);
4184 ValuesAtScopes[V][L] = C;
4188 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4189 if (isa<SCEVConstant>(V)) return V;
4191 // If this instruction is evolved from a constant-evolving PHI, compute the
4192 // exit value from the loop without using SCEVs.
4193 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4194 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4195 const Loop *LI = (*this->LI)[I->getParent()];
4196 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4197 if (PHINode *PN = dyn_cast<PHINode>(I))
4198 if (PN->getParent() == LI->getHeader()) {
4199 // Okay, there is no closed form solution for the PHI node. Check
4200 // to see if the loop that contains it has a known backedge-taken
4201 // count. If so, we may be able to force computation of the exit
4203 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4204 if (const SCEVConstant *BTCC =
4205 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4206 // Okay, we know how many times the containing loop executes. If
4207 // this is a constant evolving PHI node, get the final value at
4208 // the specified iteration number.
4209 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4210 BTCC->getValue()->getValue(),
4212 if (RV) return getSCEV(RV);
4216 // Okay, this is an expression that we cannot symbolically evaluate
4217 // into a SCEV. Check to see if it's possible to symbolically evaluate
4218 // the arguments into constants, and if so, try to constant propagate the
4219 // result. This is particularly useful for computing loop exit values.
4220 if (CanConstantFold(I)) {
4221 std::vector<Constant*> Operands;
4222 Operands.reserve(I->getNumOperands());
4223 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4224 Value *Op = I->getOperand(i);
4225 if (Constant *C = dyn_cast<Constant>(Op)) {
4226 Operands.push_back(C);
4228 // If any of the operands is non-constant and if they are
4229 // non-integer and non-pointer, don't even try to analyze them
4230 // with scev techniques.
4231 if (!isSCEVable(Op->getType()))
4234 const SCEV *OpV = getSCEVAtScope(Op, L);
4235 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
4236 Constant *C = SC->getValue();
4237 if (C->getType() != Op->getType())
4238 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4242 Operands.push_back(C);
4243 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
4244 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4245 if (C->getType() != Op->getType())
4247 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4251 Operands.push_back(C);
4261 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4262 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4263 Operands[0], Operands[1], TD);
4265 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4266 &Operands[0], Operands.size(), TD);
4272 // This is some other type of SCEVUnknown, just return it.
4276 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4277 // Avoid performing the look-up in the common case where the specified
4278 // expression has no loop-variant portions.
4279 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4280 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4281 if (OpAtScope != Comm->getOperand(i)) {
4282 // Okay, at least one of these operands is loop variant but might be
4283 // foldable. Build a new instance of the folded commutative expression.
4284 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4285 Comm->op_begin()+i);
4286 NewOps.push_back(OpAtScope);
4288 for (++i; i != e; ++i) {
4289 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4290 NewOps.push_back(OpAtScope);
4292 if (isa<SCEVAddExpr>(Comm))
4293 return getAddExpr(NewOps);
4294 if (isa<SCEVMulExpr>(Comm))
4295 return getMulExpr(NewOps);
4296 if (isa<SCEVSMaxExpr>(Comm))
4297 return getSMaxExpr(NewOps);
4298 if (isa<SCEVUMaxExpr>(Comm))
4299 return getUMaxExpr(NewOps);
4300 llvm_unreachable("Unknown commutative SCEV type!");
4303 // If we got here, all operands are loop invariant.
4307 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4308 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4309 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4310 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4311 return Div; // must be loop invariant
4312 return getUDivExpr(LHS, RHS);
4315 // If this is a loop recurrence for a loop that does not contain L, then we
4316 // are dealing with the final value computed by the loop.
4317 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4318 if (!L || !AddRec->getLoop()->contains(L)) {
4319 // To evaluate this recurrence, we need to know how many times the AddRec
4320 // loop iterates. Compute this now.
4321 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4322 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4324 // Then, evaluate the AddRec.
4325 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4330 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4331 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4332 if (Op == Cast->getOperand())
4333 return Cast; // must be loop invariant
4334 return getZeroExtendExpr(Op, Cast->getType());
4337 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4338 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4339 if (Op == Cast->getOperand())
4340 return Cast; // must be loop invariant
4341 return getSignExtendExpr(Op, Cast->getType());
4344 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4345 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4346 if (Op == Cast->getOperand())
4347 return Cast; // must be loop invariant
4348 return getTruncateExpr(Op, Cast->getType());
4351 llvm_unreachable("Unknown SCEV type!");
4355 /// getSCEVAtScope - This is a convenience function which does
4356 /// getSCEVAtScope(getSCEV(V), L).
4357 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4358 return getSCEVAtScope(getSCEV(V), L);
4361 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4362 /// following equation:
4364 /// A * X = B (mod N)
4366 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4367 /// A and B isn't important.
4369 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4370 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4371 ScalarEvolution &SE) {
4372 uint32_t BW = A.getBitWidth();
4373 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4374 assert(A != 0 && "A must be non-zero.");
4378 // The gcd of A and N may have only one prime factor: 2. The number of
4379 // trailing zeros in A is its multiplicity
4380 uint32_t Mult2 = A.countTrailingZeros();
4383 // 2. Check if B is divisible by D.
4385 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4386 // is not less than multiplicity of this prime factor for D.
4387 if (B.countTrailingZeros() < Mult2)
4388 return SE.getCouldNotCompute();
4390 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4393 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4394 // bit width during computations.
4395 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4396 APInt Mod(BW + 1, 0);
4397 Mod.set(BW - Mult2); // Mod = N / D
4398 APInt I = AD.multiplicativeInverse(Mod);
4400 // 4. Compute the minimum unsigned root of the equation:
4401 // I * (B / D) mod (N / D)
4402 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4404 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4406 return SE.getConstant(Result.trunc(BW));
4409 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4410 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4411 /// might be the same) or two SCEVCouldNotCompute objects.
4413 static std::pair<const SCEV *,const SCEV *>
4414 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4415 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4416 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4417 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4418 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4420 // We currently can only solve this if the coefficients are constants.
4421 if (!LC || !MC || !NC) {
4422 const SCEV *CNC = SE.getCouldNotCompute();
4423 return std::make_pair(CNC, CNC);
4426 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4427 const APInt &L = LC->getValue()->getValue();
4428 const APInt &M = MC->getValue()->getValue();
4429 const APInt &N = NC->getValue()->getValue();
4430 APInt Two(BitWidth, 2);
4431 APInt Four(BitWidth, 4);
4434 using namespace APIntOps;
4436 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4437 // The B coefficient is M-N/2
4441 // The A coefficient is N/2
4442 APInt A(N.sdiv(Two));
4444 // Compute the B^2-4ac term.
4447 SqrtTerm -= Four * (A * C);
4449 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4450 // integer value or else APInt::sqrt() will assert.
4451 APInt SqrtVal(SqrtTerm.sqrt());
4453 // Compute the two solutions for the quadratic formula.
4454 // The divisions must be performed as signed divisions.
4456 APInt TwoA( A << 1 );
4457 if (TwoA.isMinValue()) {
4458 const SCEV *CNC = SE.getCouldNotCompute();
4459 return std::make_pair(CNC, CNC);
4462 LLVMContext &Context = SE.getContext();
4464 ConstantInt *Solution1 =
4465 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4466 ConstantInt *Solution2 =
4467 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4469 return std::make_pair(SE.getConstant(Solution1),
4470 SE.getConstant(Solution2));
4471 } // end APIntOps namespace
4474 /// HowFarToZero - Return the number of times a backedge comparing the specified
4475 /// value to zero will execute. If not computable, return CouldNotCompute.
4476 ScalarEvolution::BackedgeTakenInfo
4477 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4478 // If the value is a constant
4479 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4480 // If the value is already zero, the branch will execute zero times.
4481 if (C->getValue()->isZero()) return C;
4482 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4485 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4486 if (!AddRec || AddRec->getLoop() != L)
4487 return getCouldNotCompute();
4489 if (AddRec->isAffine()) {
4490 // If this is an affine expression, the execution count of this branch is
4491 // the minimum unsigned root of the following equation:
4493 // Start + Step*N = 0 (mod 2^BW)
4497 // Step*N = -Start (mod 2^BW)
4499 // where BW is the common bit width of Start and Step.
4501 // Get the initial value for the loop.
4502 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4503 L->getParentLoop());
4504 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4505 L->getParentLoop());
4507 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4508 // For now we handle only constant steps.
4510 // First, handle unitary steps.
4511 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4512 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4513 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4514 return Start; // N = Start (as unsigned)
4516 // Then, try to solve the above equation provided that Start is constant.
4517 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4518 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4519 -StartC->getValue()->getValue(),
4522 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4523 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4524 // the quadratic equation to solve it.
4525 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4527 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4528 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4531 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4532 << " sol#2: " << *R2 << "\n";
4534 // Pick the smallest positive root value.
4535 if (ConstantInt *CB =
4536 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4537 R1->getValue(), R2->getValue()))) {
4538 if (CB->getZExtValue() == false)
4539 std::swap(R1, R2); // R1 is the minimum root now.
4541 // We can only use this value if the chrec ends up with an exact zero
4542 // value at this index. When solving for "X*X != 5", for example, we
4543 // should not accept a root of 2.
4544 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4546 return R1; // We found a quadratic root!
4551 return getCouldNotCompute();
4554 /// HowFarToNonZero - Return the number of times a backedge checking the
4555 /// specified value for nonzero will execute. If not computable, return
4557 ScalarEvolution::BackedgeTakenInfo
4558 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4559 // Loops that look like: while (X == 0) are very strange indeed. We don't
4560 // handle them yet except for the trivial case. This could be expanded in the
4561 // future as needed.
4563 // If the value is a constant, check to see if it is known to be non-zero
4564 // already. If so, the backedge will execute zero times.
4565 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4566 if (!C->getValue()->isNullValue())
4567 return getIntegerSCEV(0, C->getType());
4568 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4571 // We could implement others, but I really doubt anyone writes loops like
4572 // this, and if they did, they would already be constant folded.
4573 return getCouldNotCompute();
4576 /// getLoopPredecessor - If the given loop's header has exactly one unique
4577 /// predecessor outside the loop, return it. Otherwise return null.
4579 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4580 BasicBlock *Header = L->getHeader();
4581 BasicBlock *Pred = 0;
4582 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4584 if (!L->contains(*PI)) {
4585 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4591 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4592 /// (which may not be an immediate predecessor) which has exactly one
4593 /// successor from which BB is reachable, or null if no such block is
4597 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4598 // If the block has a unique predecessor, then there is no path from the
4599 // predecessor to the block that does not go through the direct edge
4600 // from the predecessor to the block.
4601 if (BasicBlock *Pred = BB->getSinglePredecessor())
4604 // A loop's header is defined to be a block that dominates the loop.
4605 // If the header has a unique predecessor outside the loop, it must be
4606 // a block that has exactly one successor that can reach the loop.
4607 if (Loop *L = LI->getLoopFor(BB))
4608 return getLoopPredecessor(L);
4613 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4614 /// testing whether two expressions are equal, however for the purposes of
4615 /// looking for a condition guarding a loop, it can be useful to be a little
4616 /// more general, since a front-end may have replicated the controlling
4619 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4620 // Quick check to see if they are the same SCEV.
4621 if (A == B) return true;
4623 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4624 // two different instructions with the same value. Check for this case.
4625 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4626 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4627 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4628 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4629 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4632 // Otherwise assume they may have a different value.
4636 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4637 return getSignedRange(S).getSignedMax().isNegative();
4640 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4641 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4644 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4645 return !getSignedRange(S).getSignedMin().isNegative();
4648 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4649 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4652 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4653 return isKnownNegative(S) || isKnownPositive(S);
4656 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4657 const SCEV *LHS, const SCEV *RHS) {
4659 if (HasSameValue(LHS, RHS))
4660 return ICmpInst::isTrueWhenEqual(Pred);
4664 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4666 case ICmpInst::ICMP_SGT:
4667 Pred = ICmpInst::ICMP_SLT;
4668 std::swap(LHS, RHS);
4669 case ICmpInst::ICMP_SLT: {
4670 ConstantRange LHSRange = getSignedRange(LHS);
4671 ConstantRange RHSRange = getSignedRange(RHS);
4672 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4674 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4678 case ICmpInst::ICMP_SGE:
4679 Pred = ICmpInst::ICMP_SLE;
4680 std::swap(LHS, RHS);
4681 case ICmpInst::ICMP_SLE: {
4682 ConstantRange LHSRange = getSignedRange(LHS);
4683 ConstantRange RHSRange = getSignedRange(RHS);
4684 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4686 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4690 case ICmpInst::ICMP_UGT:
4691 Pred = ICmpInst::ICMP_ULT;
4692 std::swap(LHS, RHS);
4693 case ICmpInst::ICMP_ULT: {
4694 ConstantRange LHSRange = getUnsignedRange(LHS);
4695 ConstantRange RHSRange = getUnsignedRange(RHS);
4696 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4698 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4702 case ICmpInst::ICMP_UGE:
4703 Pred = ICmpInst::ICMP_ULE;
4704 std::swap(LHS, RHS);
4705 case ICmpInst::ICMP_ULE: {
4706 ConstantRange LHSRange = getUnsignedRange(LHS);
4707 ConstantRange RHSRange = getUnsignedRange(RHS);
4708 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4710 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4714 case ICmpInst::ICMP_NE: {
4715 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4717 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4720 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4721 if (isKnownNonZero(Diff))
4725 case ICmpInst::ICMP_EQ:
4726 // The check at the top of the function catches the case where
4727 // the values are known to be equal.
4733 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4734 /// protected by a conditional between LHS and RHS. This is used to
4735 /// to eliminate casts.
4737 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4738 ICmpInst::Predicate Pred,
4739 const SCEV *LHS, const SCEV *RHS) {
4740 // Interpret a null as meaning no loop, where there is obviously no guard
4741 // (interprocedural conditions notwithstanding).
4742 if (!L) return true;
4744 BasicBlock *Latch = L->getLoopLatch();
4748 BranchInst *LoopContinuePredicate =
4749 dyn_cast<BranchInst>(Latch->getTerminator());
4750 if (!LoopContinuePredicate ||
4751 LoopContinuePredicate->isUnconditional())
4754 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4755 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4758 /// isLoopGuardedByCond - Test whether entry to the loop is protected
4759 /// by a conditional between LHS and RHS. This is used to help avoid max
4760 /// expressions in loop trip counts, and to eliminate casts.
4762 ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4763 ICmpInst::Predicate Pred,
4764 const SCEV *LHS, const SCEV *RHS) {
4765 // Interpret a null as meaning no loop, where there is obviously no guard
4766 // (interprocedural conditions notwithstanding).
4767 if (!L) return false;
4769 BasicBlock *Predecessor = getLoopPredecessor(L);
4770 BasicBlock *PredecessorDest = L->getHeader();
4772 // Starting at the loop predecessor, climb up the predecessor chain, as long
4773 // as there are predecessors that can be found that have unique successors
4774 // leading to the original header.
4776 PredecessorDest = Predecessor,
4777 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
4779 BranchInst *LoopEntryPredicate =
4780 dyn_cast<BranchInst>(Predecessor->getTerminator());
4781 if (!LoopEntryPredicate ||
4782 LoopEntryPredicate->isUnconditional())
4785 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4786 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
4793 /// isImpliedCond - Test whether the condition described by Pred, LHS,
4794 /// and RHS is true whenever the given Cond value evaluates to true.
4795 bool ScalarEvolution::isImpliedCond(Value *CondValue,
4796 ICmpInst::Predicate Pred,
4797 const SCEV *LHS, const SCEV *RHS,
4799 // Recursively handle And and Or conditions.
4800 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4801 if (BO->getOpcode() == Instruction::And) {
4803 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4804 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4805 } else if (BO->getOpcode() == Instruction::Or) {
4807 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4808 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4812 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4813 if (!ICI) return false;
4815 // Bail if the ICmp's operands' types are wider than the needed type
4816 // before attempting to call getSCEV on them. This avoids infinite
4817 // recursion, since the analysis of widening casts can require loop
4818 // exit condition information for overflow checking, which would
4820 if (getTypeSizeInBits(LHS->getType()) <
4821 getTypeSizeInBits(ICI->getOperand(0)->getType()))
4824 // Now that we found a conditional branch that dominates the loop, check to
4825 // see if it is the comparison we are looking for.
4826 ICmpInst::Predicate FoundPred;
4828 FoundPred = ICI->getInversePredicate();
4830 FoundPred = ICI->getPredicate();
4832 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4833 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
4835 // Balance the types. The case where FoundLHS' type is wider than
4836 // LHS' type is checked for above.
4837 if (getTypeSizeInBits(LHS->getType()) >
4838 getTypeSizeInBits(FoundLHS->getType())) {
4839 if (CmpInst::isSigned(Pred)) {
4840 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4841 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4843 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4844 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4848 // Canonicalize the query to match the way instcombine will have
4849 // canonicalized the comparison.
4850 // First, put a constant operand on the right.
4851 if (isa<SCEVConstant>(LHS)) {
4852 std::swap(LHS, RHS);
4853 Pred = ICmpInst::getSwappedPredicate(Pred);
4855 // Then, canonicalize comparisons with boundary cases.
4856 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4857 const APInt &RA = RC->getValue()->getValue();
4859 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4860 case ICmpInst::ICMP_EQ:
4861 case ICmpInst::ICMP_NE:
4863 case ICmpInst::ICMP_UGE:
4864 if ((RA - 1).isMinValue()) {
4865 Pred = ICmpInst::ICMP_NE;
4866 RHS = getConstant(RA - 1);
4869 if (RA.isMaxValue()) {
4870 Pred = ICmpInst::ICMP_EQ;
4873 if (RA.isMinValue()) return true;
4875 case ICmpInst::ICMP_ULE:
4876 if ((RA + 1).isMaxValue()) {
4877 Pred = ICmpInst::ICMP_NE;
4878 RHS = getConstant(RA + 1);
4881 if (RA.isMinValue()) {
4882 Pred = ICmpInst::ICMP_EQ;
4885 if (RA.isMaxValue()) return true;
4887 case ICmpInst::ICMP_SGE:
4888 if ((RA - 1).isMinSignedValue()) {
4889 Pred = ICmpInst::ICMP_NE;
4890 RHS = getConstant(RA - 1);
4893 if (RA.isMaxSignedValue()) {
4894 Pred = ICmpInst::ICMP_EQ;
4897 if (RA.isMinSignedValue()) return true;
4899 case ICmpInst::ICMP_SLE:
4900 if ((RA + 1).isMaxSignedValue()) {
4901 Pred = ICmpInst::ICMP_NE;
4902 RHS = getConstant(RA + 1);
4905 if (RA.isMinSignedValue()) {
4906 Pred = ICmpInst::ICMP_EQ;
4909 if (RA.isMaxSignedValue()) return true;
4911 case ICmpInst::ICMP_UGT:
4912 if (RA.isMinValue()) {
4913 Pred = ICmpInst::ICMP_NE;
4916 if ((RA + 1).isMaxValue()) {
4917 Pred = ICmpInst::ICMP_EQ;
4918 RHS = getConstant(RA + 1);
4921 if (RA.isMaxValue()) return false;
4923 case ICmpInst::ICMP_ULT:
4924 if (RA.isMaxValue()) {
4925 Pred = ICmpInst::ICMP_NE;
4928 if ((RA - 1).isMinValue()) {
4929 Pred = ICmpInst::ICMP_EQ;
4930 RHS = getConstant(RA - 1);
4933 if (RA.isMinValue()) return false;
4935 case ICmpInst::ICMP_SGT:
4936 if (RA.isMinSignedValue()) {
4937 Pred = ICmpInst::ICMP_NE;
4940 if ((RA + 1).isMaxSignedValue()) {
4941 Pred = ICmpInst::ICMP_EQ;
4942 RHS = getConstant(RA + 1);
4945 if (RA.isMaxSignedValue()) return false;
4947 case ICmpInst::ICMP_SLT:
4948 if (RA.isMaxSignedValue()) {
4949 Pred = ICmpInst::ICMP_NE;
4952 if ((RA - 1).isMinSignedValue()) {
4953 Pred = ICmpInst::ICMP_EQ;
4954 RHS = getConstant(RA - 1);
4957 if (RA.isMinSignedValue()) return false;
4962 // Check to see if we can make the LHS or RHS match.
4963 if (LHS == FoundRHS || RHS == FoundLHS) {
4964 if (isa<SCEVConstant>(RHS)) {
4965 std::swap(FoundLHS, FoundRHS);
4966 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4968 std::swap(LHS, RHS);
4969 Pred = ICmpInst::getSwappedPredicate(Pred);
4973 // Check whether the found predicate is the same as the desired predicate.
4974 if (FoundPred == Pred)
4975 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4977 // Check whether swapping the found predicate makes it the same as the
4978 // desired predicate.
4979 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4980 if (isa<SCEVConstant>(RHS))
4981 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4983 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4984 RHS, LHS, FoundLHS, FoundRHS);
4987 // Check whether the actual condition is beyond sufficient.
4988 if (FoundPred == ICmpInst::ICMP_EQ)
4989 if (ICmpInst::isTrueWhenEqual(Pred))
4990 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4992 if (Pred == ICmpInst::ICMP_NE)
4993 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4994 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4997 // Otherwise assume the worst.
5001 /// isImpliedCondOperands - Test whether the condition described by Pred,
5002 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5003 /// and FoundRHS is true.
5004 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5005 const SCEV *LHS, const SCEV *RHS,
5006 const SCEV *FoundLHS,
5007 const SCEV *FoundRHS) {
5008 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5009 FoundLHS, FoundRHS) ||
5010 // ~x < ~y --> x > y
5011 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5012 getNotSCEV(FoundRHS),
5013 getNotSCEV(FoundLHS));
5016 /// isImpliedCondOperandsHelper - Test whether the condition described by
5017 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5018 /// FoundLHS, and FoundRHS is true.
5020 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5021 const SCEV *LHS, const SCEV *RHS,
5022 const SCEV *FoundLHS,
5023 const SCEV *FoundRHS) {
5025 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5026 case ICmpInst::ICMP_EQ:
5027 case ICmpInst::ICMP_NE:
5028 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5031 case ICmpInst::ICMP_SLT:
5032 case ICmpInst::ICMP_SLE:
5033 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5034 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5037 case ICmpInst::ICMP_SGT:
5038 case ICmpInst::ICMP_SGE:
5039 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5040 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5043 case ICmpInst::ICMP_ULT:
5044 case ICmpInst::ICMP_ULE:
5045 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5046 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5049 case ICmpInst::ICMP_UGT:
5050 case ICmpInst::ICMP_UGE:
5051 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5052 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5060 /// getBECount - Subtract the end and start values and divide by the step,
5061 /// rounding up, to get the number of times the backedge is executed. Return
5062 /// CouldNotCompute if an intermediate computation overflows.
5063 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5067 assert(!isKnownNegative(Step) &&
5068 "This code doesn't handle negative strides yet!");
5070 const Type *Ty = Start->getType();
5071 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
5072 const SCEV *Diff = getMinusSCEV(End, Start);
5073 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5075 // Add an adjustment to the difference between End and Start so that
5076 // the division will effectively round up.
5077 const SCEV *Add = getAddExpr(Diff, RoundUp);
5080 // Check Add for unsigned overflow.
5081 // TODO: More sophisticated things could be done here.
5082 const Type *WideTy = IntegerType::get(getContext(),
5083 getTypeSizeInBits(Ty) + 1);
5084 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5085 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5086 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5087 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5088 return getCouldNotCompute();
5091 return getUDivExpr(Add, Step);
5094 /// HowManyLessThans - Return the number of times a backedge containing the
5095 /// specified less-than comparison will execute. If not computable, return
5096 /// CouldNotCompute.
5097 ScalarEvolution::BackedgeTakenInfo
5098 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5099 const Loop *L, bool isSigned) {
5100 // Only handle: "ADDREC < LoopInvariant".
5101 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5103 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5104 if (!AddRec || AddRec->getLoop() != L)
5105 return getCouldNotCompute();
5107 // Check to see if we have a flag which makes analysis easy.
5108 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5109 AddRec->hasNoUnsignedWrap();
5111 if (AddRec->isAffine()) {
5112 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5113 const SCEV *Step = AddRec->getStepRecurrence(*this);
5116 return getCouldNotCompute();
5117 if (Step->isOne()) {
5118 // With unit stride, the iteration never steps past the limit value.
5119 } else if (isKnownPositive(Step)) {
5120 // Test whether a positive iteration can step past the limit
5121 // value and past the maximum value for its type in a single step.
5122 // Note that it's not sufficient to check NoWrap here, because even
5123 // though the value after a wrap is undefined, it's not undefined
5124 // behavior, so if wrap does occur, the loop could either terminate or
5125 // loop infinitely, but in either case, the loop is guaranteed to
5126 // iterate at least until the iteration where the wrapping occurs.
5127 const SCEV *One = getIntegerSCEV(1, Step->getType());
5129 APInt Max = APInt::getSignedMaxValue(BitWidth);
5130 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5131 .slt(getSignedRange(RHS).getSignedMax()))
5132 return getCouldNotCompute();
5134 APInt Max = APInt::getMaxValue(BitWidth);
5135 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5136 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5137 return getCouldNotCompute();
5140 // TODO: Handle negative strides here and below.
5141 return getCouldNotCompute();
5143 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5144 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5145 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5146 // treat m-n as signed nor unsigned due to overflow possibility.
5148 // First, we get the value of the LHS in the first iteration: n
5149 const SCEV *Start = AddRec->getOperand(0);
5151 // Determine the minimum constant start value.
5152 const SCEV *MinStart = getConstant(isSigned ?
5153 getSignedRange(Start).getSignedMin() :
5154 getUnsignedRange(Start).getUnsignedMin());
5156 // If we know that the condition is true in order to enter the loop,
5157 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5158 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5159 // the division must round up.
5160 const SCEV *End = RHS;
5161 if (!isLoopGuardedByCond(L,
5162 isSigned ? ICmpInst::ICMP_SLT :
5164 getMinusSCEV(Start, Step), RHS))
5165 End = isSigned ? getSMaxExpr(RHS, Start)
5166 : getUMaxExpr(RHS, Start);
5168 // Determine the maximum constant end value.
5169 const SCEV *MaxEnd = getConstant(isSigned ?
5170 getSignedRange(End).getSignedMax() :
5171 getUnsignedRange(End).getUnsignedMax());
5173 // If MaxEnd is within a step of the maximum integer value in its type,
5174 // adjust it down to the minimum value which would produce the same effect.
5175 // This allows the subsequent ceiling division of (N+(step-1))/step to
5176 // compute the correct value.
5177 const SCEV *StepMinusOne = getMinusSCEV(Step,
5178 getIntegerSCEV(1, Step->getType()));
5181 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5184 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5187 // Finally, we subtract these two values and divide, rounding up, to get
5188 // the number of times the backedge is executed.
5189 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5191 // The maximum backedge count is similar, except using the minimum start
5192 // value and the maximum end value.
5193 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5195 return BackedgeTakenInfo(BECount, MaxBECount);
5198 return getCouldNotCompute();
5201 /// getNumIterationsInRange - Return the number of iterations of this loop that
5202 /// produce values in the specified constant range. Another way of looking at
5203 /// this is that it returns the first iteration number where the value is not in
5204 /// the condition, thus computing the exit count. If the iteration count can't
5205 /// be computed, an instance of SCEVCouldNotCompute is returned.
5206 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5207 ScalarEvolution &SE) const {
5208 if (Range.isFullSet()) // Infinite loop.
5209 return SE.getCouldNotCompute();
5211 // If the start is a non-zero constant, shift the range to simplify things.
5212 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5213 if (!SC->getValue()->isZero()) {
5214 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5215 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
5216 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5217 if (const SCEVAddRecExpr *ShiftedAddRec =
5218 dyn_cast<SCEVAddRecExpr>(Shifted))
5219 return ShiftedAddRec->getNumIterationsInRange(
5220 Range.subtract(SC->getValue()->getValue()), SE);
5221 // This is strange and shouldn't happen.
5222 return SE.getCouldNotCompute();
5225 // The only time we can solve this is when we have all constant indices.
5226 // Otherwise, we cannot determine the overflow conditions.
5227 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5228 if (!isa<SCEVConstant>(getOperand(i)))
5229 return SE.getCouldNotCompute();
5232 // Okay at this point we know that all elements of the chrec are constants and
5233 // that the start element is zero.
5235 // First check to see if the range contains zero. If not, the first
5237 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5238 if (!Range.contains(APInt(BitWidth, 0)))
5239 return SE.getIntegerSCEV(0, getType());
5242 // If this is an affine expression then we have this situation:
5243 // Solve {0,+,A} in Range === Ax in Range
5245 // We know that zero is in the range. If A is positive then we know that
5246 // the upper value of the range must be the first possible exit value.
5247 // If A is negative then the lower of the range is the last possible loop
5248 // value. Also note that we already checked for a full range.
5249 APInt One(BitWidth,1);
5250 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5251 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5253 // The exit value should be (End+A)/A.
5254 APInt ExitVal = (End + A).udiv(A);
5255 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5257 // Evaluate at the exit value. If we really did fall out of the valid
5258 // range, then we computed our trip count, otherwise wrap around or other
5259 // things must have happened.
5260 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5261 if (Range.contains(Val->getValue()))
5262 return SE.getCouldNotCompute(); // Something strange happened
5264 // Ensure that the previous value is in the range. This is a sanity check.
5265 assert(Range.contains(
5266 EvaluateConstantChrecAtConstant(this,
5267 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5268 "Linear scev computation is off in a bad way!");
5269 return SE.getConstant(ExitValue);
5270 } else if (isQuadratic()) {
5271 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5272 // quadratic equation to solve it. To do this, we must frame our problem in
5273 // terms of figuring out when zero is crossed, instead of when
5274 // Range.getUpper() is crossed.
5275 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5276 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5277 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5279 // Next, solve the constructed addrec
5280 std::pair<const SCEV *,const SCEV *> Roots =
5281 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5282 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5283 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5285 // Pick the smallest positive root value.
5286 if (ConstantInt *CB =
5287 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5288 R1->getValue(), R2->getValue()))) {
5289 if (CB->getZExtValue() == false)
5290 std::swap(R1, R2); // R1 is the minimum root now.
5292 // Make sure the root is not off by one. The returned iteration should
5293 // not be in the range, but the previous one should be. When solving
5294 // for "X*X < 5", for example, we should not return a root of 2.
5295 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5298 if (Range.contains(R1Val->getValue())) {
5299 // The next iteration must be out of the range...
5300 ConstantInt *NextVal =
5301 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5303 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5304 if (!Range.contains(R1Val->getValue()))
5305 return SE.getConstant(NextVal);
5306 return SE.getCouldNotCompute(); // Something strange happened
5309 // If R1 was not in the range, then it is a good return value. Make
5310 // sure that R1-1 WAS in the range though, just in case.
5311 ConstantInt *NextVal =
5312 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5313 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5314 if (Range.contains(R1Val->getValue()))
5316 return SE.getCouldNotCompute(); // Something strange happened
5321 return SE.getCouldNotCompute();
5326 //===----------------------------------------------------------------------===//
5327 // SCEVCallbackVH Class Implementation
5328 //===----------------------------------------------------------------------===//
5330 void ScalarEvolution::SCEVCallbackVH::deleted() {
5331 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5332 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5333 SE->ConstantEvolutionLoopExitValue.erase(PN);
5334 SE->Scalars.erase(getValPtr());
5335 // this now dangles!
5338 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
5339 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5341 // Forget all the expressions associated with users of the old value,
5342 // so that future queries will recompute the expressions using the new
5344 SmallVector<User *, 16> Worklist;
5345 SmallPtrSet<User *, 8> Visited;
5346 Value *Old = getValPtr();
5347 bool DeleteOld = false;
5348 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5350 Worklist.push_back(*UI);
5351 while (!Worklist.empty()) {
5352 User *U = Worklist.pop_back_val();
5353 // Deleting the Old value will cause this to dangle. Postpone
5354 // that until everything else is done.
5359 if (!Visited.insert(U))
5361 if (PHINode *PN = dyn_cast<PHINode>(U))
5362 SE->ConstantEvolutionLoopExitValue.erase(PN);
5363 SE->Scalars.erase(U);
5364 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5366 Worklist.push_back(*UI);
5368 // Delete the Old value if it (indirectly) references itself.
5370 if (PHINode *PN = dyn_cast<PHINode>(Old))
5371 SE->ConstantEvolutionLoopExitValue.erase(PN);
5372 SE->Scalars.erase(Old);
5373 // this now dangles!
5378 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5379 : CallbackVH(V), SE(se) {}
5381 //===----------------------------------------------------------------------===//
5382 // ScalarEvolution Class Implementation
5383 //===----------------------------------------------------------------------===//
5385 ScalarEvolution::ScalarEvolution()
5386 : FunctionPass(&ID) {
5389 bool ScalarEvolution::runOnFunction(Function &F) {
5391 LI = &getAnalysis<LoopInfo>();
5392 TD = getAnalysisIfAvailable<TargetData>();
5393 DT = &getAnalysis<DominatorTree>();
5397 void ScalarEvolution::releaseMemory() {
5399 BackedgeTakenCounts.clear();
5400 ConstantEvolutionLoopExitValue.clear();
5401 ValuesAtScopes.clear();
5402 UniqueSCEVs.clear();
5403 SCEVAllocator.Reset();
5406 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5407 AU.setPreservesAll();
5408 AU.addRequiredTransitive<LoopInfo>();
5409 AU.addRequiredTransitive<DominatorTree>();
5412 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5413 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5416 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5418 // Print all inner loops first
5419 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5420 PrintLoopInfo(OS, SE, *I);
5423 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5426 SmallVector<BasicBlock *, 8> ExitBlocks;
5427 L->getExitBlocks(ExitBlocks);
5428 if (ExitBlocks.size() != 1)
5429 OS << "<multiple exits> ";
5431 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5432 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5434 OS << "Unpredictable backedge-taken count. ";
5439 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5442 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5443 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5445 OS << "Unpredictable max backedge-taken count. ";
5451 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5452 // ScalarEvolution's implementation of the print method is to print
5453 // out SCEV values of all instructions that are interesting. Doing
5454 // this potentially causes it to create new SCEV objects though,
5455 // which technically conflicts with the const qualifier. This isn't
5456 // observable from outside the class though, so casting away the
5457 // const isn't dangerous.
5458 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5460 OS << "Classifying expressions for: ";
5461 WriteAsOperand(OS, F, /*PrintType=*/false);
5463 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5464 if (isSCEVable(I->getType())) {
5467 const SCEV *SV = SE.getSCEV(&*I);
5470 const Loop *L = LI->getLoopFor((*I).getParent());
5472 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5479 OS << "\t\t" "Exits: ";
5480 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5481 if (!ExitValue->isLoopInvariant(L)) {
5482 OS << "<<Unknown>>";
5491 OS << "Determining loop execution counts for: ";
5492 WriteAsOperand(OS, F, /*PrintType=*/false);
5494 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5495 PrintLoopInfo(OS, &SE, *I);