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 INITIALIZE_PASS(ScalarEvolution, "scalar-evolution",
107 "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(FoldingSetNodeIDRef(), 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 = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
181 UniqueSCEVs.InsertNode(S, IP);
185 const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(getContext(), Val));
190 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
191 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
192 return getConstant(ConstantInt::get(ITy, V, isSigned));
195 const Type *SCEVConstant::getType() const { return V->getType(); }
197 void SCEVConstant::print(raw_ostream &OS) const {
198 WriteAsOperand(OS, V, false);
201 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
202 unsigned SCEVTy, const SCEV *op, const Type *ty)
203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
205 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
209 bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
213 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
214 const SCEV *op, const Type *ty)
215 : SCEVCastExpr(ID, scTruncate, op, ty) {
216 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
217 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
218 "Cannot truncate non-integer value!");
221 void SCEVTruncateExpr::print(raw_ostream &OS) const {
222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
225 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
226 const SCEV *op, const Type *ty)
227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
228 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
229 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
230 "Cannot zero extend non-integer value!");
233 void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
237 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
238 const SCEV *op, const Type *ty)
239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
240 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
241 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
242 "Cannot sign extend non-integer value!");
245 void SCEVSignExtendExpr::print(raw_ostream &OS) const {
246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
249 void SCEVCommutativeExpr::print(raw_ostream &OS) const {
250 const char *OpStr = getOperationStr();
252 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
254 if (llvm::next(I) != E)
260 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
268 bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
270 if (!getOperand(i)->properlyDominates(BB, DT))
276 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
277 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
280 bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
281 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
284 void SCEVUDivExpr::print(raw_ostream &OS) const {
285 OS << "(" << *LHS << " /u " << *RHS << ")";
288 const Type *SCEVUDivExpr::getType() const {
289 // In most cases the types of LHS and RHS will be the same, but in some
290 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
291 // depend on the type for correctness, but handling types carefully can
292 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
293 // a pointer type than the RHS, so use the RHS' type here.
294 return RHS->getType();
297 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
298 // Add recurrences are never invariant in the function-body (null loop).
302 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
303 if (QueryLoop->contains(L))
306 // This recurrence is variant w.r.t. QueryLoop if any of its operands
308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
309 if (!getOperand(i)->isLoopInvariant(QueryLoop))
312 // Otherwise it's loop-invariant.
317 SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
318 return DT->dominates(L->getHeader(), BB) &&
319 SCEVNAryExpr::dominates(BB, DT);
323 SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
324 // This uses a "dominates" query instead of "properly dominates" query because
325 // the instruction which produces the addrec's value is a PHI, and a PHI
326 // effectively properly dominates its entire containing block.
327 return DT->dominates(L->getHeader(), BB) &&
328 SCEVNAryExpr::properlyDominates(BB, DT);
331 void SCEVAddRecExpr::print(raw_ostream &OS) const {
332 OS << "{" << *Operands[0];
333 for (unsigned i = 1, e = NumOperands; i != e; ++i)
334 OS << ",+," << *Operands[i];
336 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
340 void SCEVUnknown::deleted() {
341 // Clear this SCEVUnknown from ValuesAtScopes.
342 SE->ValuesAtScopes.erase(this);
344 // Remove this SCEVUnknown from the uniquing map.
345 SE->UniqueSCEVs.RemoveNode(this);
347 // Release the value.
351 void SCEVUnknown::allUsesReplacedWith(Value *New) {
352 // Clear this SCEVUnknown from ValuesAtScopes.
353 SE->ValuesAtScopes.erase(this);
355 // Remove this SCEVUnknown from the uniquing map.
356 SE->UniqueSCEVs.RemoveNode(this);
358 // Update this SCEVUnknown to point to the new value. This is needed
359 // because there may still be outstanding SCEVs which still point to
364 bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
365 // All non-instruction values are loop invariant. All instructions are loop
366 // invariant if they are not contained in the specified loop.
367 // Instructions are never considered invariant in the function body
368 // (null loop) because they are defined within the "loop".
369 if (Instruction *I = dyn_cast<Instruction>(getValue()))
370 return L && !L->contains(I);
374 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
375 if (Instruction *I = dyn_cast<Instruction>(getValue()))
376 return DT->dominates(I->getParent(), BB);
380 bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
381 if (Instruction *I = dyn_cast<Instruction>(getValue()))
382 return DT->properlyDominates(I->getParent(), BB);
386 const Type *SCEVUnknown::getType() const {
387 return getValue()->getType();
390 bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
391 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
392 if (VCE->getOpcode() == Instruction::PtrToInt)
393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
394 if (CE->getOpcode() == Instruction::GetElementPtr &&
395 CE->getOperand(0)->isNullValue() &&
396 CE->getNumOperands() == 2)
397 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
399 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
407 bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getOperand(0)->isNullValue()) {
414 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
415 if (const StructType *STy = dyn_cast<StructType>(Ty))
416 if (!STy->isPacked() &&
417 CE->getNumOperands() == 3 &&
418 CE->getOperand(1)->isNullValue()) {
419 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
421 STy->getNumElements() == 2 &&
422 STy->getElementType(0)->isIntegerTy(1)) {
423 AllocTy = STy->getElementType(1);
432 bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
433 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
434 if (VCE->getOpcode() == Instruction::PtrToInt)
435 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
436 if (CE->getOpcode() == Instruction::GetElementPtr &&
437 CE->getNumOperands() == 3 &&
438 CE->getOperand(0)->isNullValue() &&
439 CE->getOperand(1)->isNullValue()) {
441 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
442 // Ignore vector types here so that ScalarEvolutionExpander doesn't
443 // emit getelementptrs that index into vectors.
444 if (Ty->isStructTy() || Ty->isArrayTy()) {
446 FieldNo = CE->getOperand(2);
454 void SCEVUnknown::print(raw_ostream &OS) const {
456 if (isSizeOf(AllocTy)) {
457 OS << "sizeof(" << *AllocTy << ")";
460 if (isAlignOf(AllocTy)) {
461 OS << "alignof(" << *AllocTy << ")";
467 if (isOffsetOf(CTy, FieldNo)) {
468 OS << "offsetof(" << *CTy << ", ";
469 WriteAsOperand(OS, FieldNo, false);
474 // Otherwise just print it normally.
475 WriteAsOperand(OS, getValue(), false);
478 //===----------------------------------------------------------------------===//
480 //===----------------------------------------------------------------------===//
482 static bool CompareTypes(const Type *A, const Type *B) {
483 if (A->getTypeID() != B->getTypeID())
484 return A->getTypeID() < B->getTypeID();
485 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
486 const IntegerType *BI = cast<IntegerType>(B);
487 return AI->getBitWidth() < BI->getBitWidth();
489 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
490 const PointerType *BI = cast<PointerType>(B);
491 return CompareTypes(AI->getElementType(), BI->getElementType());
493 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
494 const ArrayType *BI = cast<ArrayType>(B);
495 if (AI->getNumElements() != BI->getNumElements())
496 return AI->getNumElements() < BI->getNumElements();
497 return CompareTypes(AI->getElementType(), BI->getElementType());
499 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
500 const VectorType *BI = cast<VectorType>(B);
501 if (AI->getNumElements() != BI->getNumElements())
502 return AI->getNumElements() < BI->getNumElements();
503 return CompareTypes(AI->getElementType(), BI->getElementType());
505 if (const StructType *AI = dyn_cast<StructType>(A)) {
506 const StructType *BI = cast<StructType>(B);
507 if (AI->getNumElements() != BI->getNumElements())
508 return AI->getNumElements() < BI->getNumElements();
509 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
510 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
511 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
512 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
518 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
519 /// than the complexity of the RHS. This comparator is used to canonicalize
521 class SCEVComplexityCompare {
524 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
526 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
527 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
531 // Primarily, sort the SCEVs by their getSCEVType().
532 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
534 return LType < RType;
536 // Aside from the getSCEVType() ordering, the particular ordering
537 // isn't very important except that it's beneficial to be consistent,
538 // so that (a + b) and (b + a) don't end up as different expressions.
540 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
541 // not as complete as it could be.
542 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
543 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
545 // Order pointer values after integer values. This helps SCEVExpander
547 bool LIsPointer = LU->getType()->isPointerTy(),
548 RIsPointer = RU->getType()->isPointerTy();
549 if (LIsPointer != RIsPointer)
552 // Compare getValueID values.
553 unsigned LID = LU->getValue()->getValueID(),
554 RID = RU->getValue()->getValueID();
558 // Sort arguments by their position.
559 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
560 const Argument *RA = cast<Argument>(RU->getValue());
561 return LA->getArgNo() < RA->getArgNo();
564 // For instructions, compare their loop depth, and their opcode.
565 // This is pretty loose.
566 if (const Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
567 const Instruction *RV = cast<Instruction>(RU->getValue());
569 // Compare loop depths.
570 unsigned LDepth = LI->getLoopDepth(LV->getParent()),
571 RDepth = LI->getLoopDepth(RV->getParent());
572 if (LDepth != RDepth)
573 return LDepth < RDepth;
575 // Compare the number of operands.
576 unsigned LNumOps = LV->getNumOperands(),
577 RNumOps = RV->getNumOperands();
578 if (LNumOps != RNumOps)
579 return LNumOps < RNumOps;
585 // Compare constant values.
586 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
587 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
588 const ConstantInt *LCC = LC->getValue();
589 const ConstantInt *RCC = RC->getValue();
590 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
591 if (LBitWidth != RBitWidth)
592 return LBitWidth < RBitWidth;
593 return LCC->getValue().ult(RCC->getValue());
596 // Compare addrec loop depths.
597 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
598 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
599 unsigned LDepth = LA->getLoop()->getLoopDepth(),
600 RDepth = RA->getLoop()->getLoopDepth();
601 if (LDepth != RDepth)
602 return LDepth < RDepth;
605 // Lexicographically compare n-ary expressions.
606 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
607 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
608 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
609 for (unsigned i = 0; i != LNumOps; ++i) {
612 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
613 if (operator()(LOp, ROp))
615 if (operator()(ROp, LOp))
618 return LNumOps < RNumOps;
621 // Lexicographically compare udiv expressions.
622 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
623 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
624 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
625 *RL = RC->getLHS(), *RR = RC->getRHS();
626 if (operator()(LL, RL))
628 if (operator()(RL, LL))
630 if (operator()(LR, RR))
632 if (operator()(RR, LR))
637 // Compare cast expressions by operand.
638 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
639 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
640 return operator()(LC->getOperand(), RC->getOperand());
643 llvm_unreachable("Unknown SCEV kind!");
649 /// GroupByComplexity - Given a list of SCEV objects, order them by their
650 /// complexity, and group objects of the same complexity together by value.
651 /// When this routine is finished, we know that any duplicates in the vector are
652 /// consecutive and that complexity is monotonically increasing.
654 /// Note that we go take special precautions to ensure that we get deterministic
655 /// results from this routine. In other words, we don't want the results of
656 /// this to depend on where the addresses of various SCEV objects happened to
659 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
661 if (Ops.size() < 2) return; // Noop
662 if (Ops.size() == 2) {
663 // This is the common case, which also happens to be trivially simple.
665 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
666 std::swap(Ops[0], Ops[1]);
670 // Do the rough sort by complexity.
671 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
673 // Now that we are sorted by complexity, group elements of the same
674 // complexity. Note that this is, at worst, N^2, but the vector is likely to
675 // be extremely short in practice. Note that we take this approach because we
676 // do not want to depend on the addresses of the objects we are grouping.
677 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
678 const SCEV *S = Ops[i];
679 unsigned Complexity = S->getSCEVType();
681 // If there are any objects of the same complexity and same value as this
683 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
684 if (Ops[j] == S) { // Found a duplicate.
685 // Move it to immediately after i'th element.
686 std::swap(Ops[i+1], Ops[j]);
687 ++i; // no need to rescan it.
688 if (i == e-2) return; // Done!
696 //===----------------------------------------------------------------------===//
697 // Simple SCEV method implementations
698 //===----------------------------------------------------------------------===//
700 /// BinomialCoefficient - Compute BC(It, K). The result has width W.
702 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
704 const Type* ResultTy) {
705 // Handle the simplest case efficiently.
707 return SE.getTruncateOrZeroExtend(It, ResultTy);
709 // We are using the following formula for BC(It, K):
711 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
713 // Suppose, W is the bitwidth of the return value. We must be prepared for
714 // overflow. Hence, we must assure that the result of our computation is
715 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
716 // safe in modular arithmetic.
718 // However, this code doesn't use exactly that formula; the formula it uses
719 // is something like the following, where T is the number of factors of 2 in
720 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
723 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
725 // This formula is trivially equivalent to the previous formula. However,
726 // this formula can be implemented much more efficiently. The trick is that
727 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
728 // arithmetic. To do exact division in modular arithmetic, all we have
729 // to do is multiply by the inverse. Therefore, this step can be done at
732 // The next issue is how to safely do the division by 2^T. The way this
733 // is done is by doing the multiplication step at a width of at least W + T
734 // bits. This way, the bottom W+T bits of the product are accurate. Then,
735 // when we perform the division by 2^T (which is equivalent to a right shift
736 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
737 // truncated out after the division by 2^T.
739 // In comparison to just directly using the first formula, this technique
740 // is much more efficient; using the first formula requires W * K bits,
741 // but this formula less than W + K bits. Also, the first formula requires
742 // a division step, whereas this formula only requires multiplies and shifts.
744 // It doesn't matter whether the subtraction step is done in the calculation
745 // width or the input iteration count's width; if the subtraction overflows,
746 // the result must be zero anyway. We prefer here to do it in the width of
747 // the induction variable because it helps a lot for certain cases; CodeGen
748 // isn't smart enough to ignore the overflow, which leads to much less
749 // efficient code if the width of the subtraction is wider than the native
752 // (It's possible to not widen at all by pulling out factors of 2 before
753 // the multiplication; for example, K=2 can be calculated as
754 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
755 // extra arithmetic, so it's not an obvious win, and it gets
756 // much more complicated for K > 3.)
758 // Protection from insane SCEVs; this bound is conservative,
759 // but it probably doesn't matter.
761 return SE.getCouldNotCompute();
763 unsigned W = SE.getTypeSizeInBits(ResultTy);
765 // Calculate K! / 2^T and T; we divide out the factors of two before
766 // multiplying for calculating K! / 2^T to avoid overflow.
767 // Other overflow doesn't matter because we only care about the bottom
768 // W bits of the result.
769 APInt OddFactorial(W, 1);
771 for (unsigned i = 3; i <= K; ++i) {
773 unsigned TwoFactors = Mult.countTrailingZeros();
775 Mult = Mult.lshr(TwoFactors);
776 OddFactorial *= Mult;
779 // We need at least W + T bits for the multiplication step
780 unsigned CalculationBits = W + T;
782 // Calculate 2^T, at width T+W.
783 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
785 // Calculate the multiplicative inverse of K! / 2^T;
786 // this multiplication factor will perform the exact division by
788 APInt Mod = APInt::getSignedMinValue(W+1);
789 APInt MultiplyFactor = OddFactorial.zext(W+1);
790 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
791 MultiplyFactor = MultiplyFactor.trunc(W);
793 // Calculate the product, at width T+W
794 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
796 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
797 for (unsigned i = 1; i != K; ++i) {
798 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
799 Dividend = SE.getMulExpr(Dividend,
800 SE.getTruncateOrZeroExtend(S, CalculationTy));
804 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
806 // Truncate the result, and divide by K! / 2^T.
808 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
809 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
812 /// evaluateAtIteration - Return the value of this chain of recurrences at
813 /// the specified iteration number. We can evaluate this recurrence by
814 /// multiplying each element in the chain by the binomial coefficient
815 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
817 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
819 /// where BC(It, k) stands for binomial coefficient.
821 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
822 ScalarEvolution &SE) const {
823 const SCEV *Result = getStart();
824 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
825 // The computation is correct in the face of overflow provided that the
826 // multiplication is performed _after_ the evaluation of the binomial
828 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
829 if (isa<SCEVCouldNotCompute>(Coeff))
832 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
837 //===----------------------------------------------------------------------===//
838 // SCEV Expression folder implementations
839 //===----------------------------------------------------------------------===//
841 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
843 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
844 "This is not a truncating conversion!");
845 assert(isSCEVable(Ty) &&
846 "This is not a conversion to a SCEVable type!");
847 Ty = getEffectiveSCEVType(Ty);
850 ID.AddInteger(scTruncate);
854 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
856 // Fold if the operand is constant.
857 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
859 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
860 getEffectiveSCEVType(Ty))));
862 // trunc(trunc(x)) --> trunc(x)
863 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
864 return getTruncateExpr(ST->getOperand(), Ty);
866 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
867 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
868 return getTruncateOrSignExtend(SS->getOperand(), Ty);
870 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
871 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
872 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
874 // If the input value is a chrec scev, truncate the chrec's operands.
875 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
876 SmallVector<const SCEV *, 4> Operands;
877 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
878 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
879 return getAddRecExpr(Operands, AddRec->getLoop());
882 // As a special case, fold trunc(undef) to undef. We don't want to
883 // know too much about SCEVUnknowns, but this special case is handy
885 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
886 if (isa<UndefValue>(U->getValue()))
887 return getSCEV(UndefValue::get(Ty));
889 // The cast wasn't folded; create an explicit cast node. We can reuse
890 // the existing insert position since if we get here, we won't have
891 // made any changes which would invalidate it.
892 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
894 UniqueSCEVs.InsertNode(S, IP);
898 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
900 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
901 "This is not an extending conversion!");
902 assert(isSCEVable(Ty) &&
903 "This is not a conversion to a SCEVable type!");
904 Ty = getEffectiveSCEVType(Ty);
906 // Fold if the operand is constant.
907 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
909 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
910 getEffectiveSCEVType(Ty))));
912 // zext(zext(x)) --> zext(x)
913 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
914 return getZeroExtendExpr(SZ->getOperand(), Ty);
916 // Before doing any expensive analysis, check to see if we've already
917 // computed a SCEV for this Op and Ty.
919 ID.AddInteger(scZeroExtend);
923 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
925 // If the input value is a chrec scev, and we can prove that the value
926 // did not overflow the old, smaller, value, we can zero extend all of the
927 // operands (often constants). This allows analysis of something like
928 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
929 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
930 if (AR->isAffine()) {
931 const SCEV *Start = AR->getStart();
932 const SCEV *Step = AR->getStepRecurrence(*this);
933 unsigned BitWidth = getTypeSizeInBits(AR->getType());
934 const Loop *L = AR->getLoop();
936 // If we have special knowledge that this addrec won't overflow,
937 // we don't need to do any further analysis.
938 if (AR->hasNoUnsignedWrap())
939 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
940 getZeroExtendExpr(Step, Ty),
943 // Check whether the backedge-taken count is SCEVCouldNotCompute.
944 // Note that this serves two purposes: It filters out loops that are
945 // simply not analyzable, and it covers the case where this code is
946 // being called from within backedge-taken count analysis, such that
947 // attempting to ask for the backedge-taken count would likely result
948 // in infinite recursion. In the later case, the analysis code will
949 // cope with a conservative value, and it will take care to purge
950 // that value once it has finished.
951 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
952 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
953 // Manually compute the final value for AR, checking for
956 // Check whether the backedge-taken count can be losslessly casted to
957 // the addrec's type. The count is always unsigned.
958 const SCEV *CastedMaxBECount =
959 getTruncateOrZeroExtend(MaxBECount, Start->getType());
960 const SCEV *RecastedMaxBECount =
961 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
962 if (MaxBECount == RecastedMaxBECount) {
963 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
964 // Check whether Start+Step*MaxBECount has no unsigned overflow.
965 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
966 const SCEV *Add = getAddExpr(Start, ZMul);
967 const SCEV *OperandExtendedAdd =
968 getAddExpr(getZeroExtendExpr(Start, WideTy),
969 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
970 getZeroExtendExpr(Step, WideTy)));
971 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
972 // Return the expression with the addrec on the outside.
973 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
974 getZeroExtendExpr(Step, Ty),
977 // Similar to above, only this time treat the step value as signed.
978 // This covers loops that count down.
979 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
980 Add = getAddExpr(Start, SMul);
982 getAddExpr(getZeroExtendExpr(Start, WideTy),
983 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
984 getSignExtendExpr(Step, WideTy)));
985 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
986 // Return the expression with the addrec on the outside.
987 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
988 getSignExtendExpr(Step, Ty),
992 // If the backedge is guarded by a comparison with the pre-inc value
993 // the addrec is safe. Also, if the entry is guarded by a comparison
994 // with the start value and the backedge is guarded by a comparison
995 // with the post-inc value, the addrec is safe.
996 if (isKnownPositive(Step)) {
997 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
998 getUnsignedRange(Step).getUnsignedMax());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1000 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1002 AR->getPostIncExpr(*this), N)))
1003 // Return the expression with the addrec on the outside.
1004 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1005 getZeroExtendExpr(Step, Ty),
1007 } else if (isKnownNegative(Step)) {
1008 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1009 getSignedRange(Step).getSignedMin());
1010 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1011 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1012 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1013 AR->getPostIncExpr(*this), N)))
1014 // Return the expression with the addrec on the outside.
1015 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1016 getSignExtendExpr(Step, Ty),
1022 // The cast wasn't folded; create an explicit cast node.
1023 // Recompute the insert position, as it may have been invalidated.
1024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1025 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1027 UniqueSCEVs.InsertNode(S, IP);
1031 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1033 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1034 "This is not an extending conversion!");
1035 assert(isSCEVable(Ty) &&
1036 "This is not a conversion to a SCEVable type!");
1037 Ty = getEffectiveSCEVType(Ty);
1039 // Fold if the operand is constant.
1040 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1042 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1043 getEffectiveSCEVType(Ty))));
1045 // sext(sext(x)) --> sext(x)
1046 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1047 return getSignExtendExpr(SS->getOperand(), Ty);
1049 // Before doing any expensive analysis, check to see if we've already
1050 // computed a SCEV for this Op and Ty.
1051 FoldingSetNodeID ID;
1052 ID.AddInteger(scSignExtend);
1056 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1058 // If the input value is a chrec scev, and we can prove that the value
1059 // did not overflow the old, smaller, value, we can sign extend all of the
1060 // operands (often constants). This allows analysis of something like
1061 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1062 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1063 if (AR->isAffine()) {
1064 const SCEV *Start = AR->getStart();
1065 const SCEV *Step = AR->getStepRecurrence(*this);
1066 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1067 const Loop *L = AR->getLoop();
1069 // If we have special knowledge that this addrec won't overflow,
1070 // we don't need to do any further analysis.
1071 if (AR->hasNoSignedWrap())
1072 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1073 getSignExtendExpr(Step, Ty),
1076 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1077 // Note that this serves two purposes: It filters out loops that are
1078 // simply not analyzable, and it covers the case where this code is
1079 // being called from within backedge-taken count analysis, such that
1080 // attempting to ask for the backedge-taken count would likely result
1081 // in infinite recursion. In the later case, the analysis code will
1082 // cope with a conservative value, and it will take care to purge
1083 // that value once it has finished.
1084 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1085 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1086 // Manually compute the final value for AR, checking for
1089 // Check whether the backedge-taken count can be losslessly casted to
1090 // the addrec's type. The count is always unsigned.
1091 const SCEV *CastedMaxBECount =
1092 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1093 const SCEV *RecastedMaxBECount =
1094 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1095 if (MaxBECount == RecastedMaxBECount) {
1096 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1097 // Check whether Start+Step*MaxBECount has no signed overflow.
1098 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1099 const SCEV *Add = getAddExpr(Start, SMul);
1100 const SCEV *OperandExtendedAdd =
1101 getAddExpr(getSignExtendExpr(Start, WideTy),
1102 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1103 getSignExtendExpr(Step, WideTy)));
1104 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1105 // Return the expression with the addrec on the outside.
1106 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1107 getSignExtendExpr(Step, Ty),
1110 // Similar to above, only this time treat the step value as unsigned.
1111 // This covers loops that count up with an unsigned step.
1112 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
1113 Add = getAddExpr(Start, UMul);
1114 OperandExtendedAdd =
1115 getAddExpr(getSignExtendExpr(Start, WideTy),
1116 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1117 getZeroExtendExpr(Step, WideTy)));
1118 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
1119 // Return the expression with the addrec on the outside.
1120 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1121 getZeroExtendExpr(Step, Ty),
1125 // If the backedge is guarded by a comparison with the pre-inc value
1126 // the addrec is safe. Also, if the entry is guarded by a comparison
1127 // with the start value and the backedge is guarded by a comparison
1128 // with the post-inc value, the addrec is safe.
1129 if (isKnownPositive(Step)) {
1130 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1131 getSignedRange(Step).getSignedMax());
1132 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1133 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1134 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1135 AR->getPostIncExpr(*this), N)))
1136 // Return the expression with the addrec on the outside.
1137 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1138 getSignExtendExpr(Step, Ty),
1140 } else if (isKnownNegative(Step)) {
1141 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1142 getSignedRange(Step).getSignedMin());
1143 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1144 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1145 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1146 AR->getPostIncExpr(*this), N)))
1147 // Return the expression with the addrec on the outside.
1148 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1149 getSignExtendExpr(Step, Ty),
1155 // The cast wasn't folded; create an explicit cast node.
1156 // Recompute the insert position, as it may have been invalidated.
1157 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1158 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1160 UniqueSCEVs.InsertNode(S, IP);
1164 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1165 /// unspecified bits out to the given type.
1167 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1169 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1170 "This is not an extending conversion!");
1171 assert(isSCEVable(Ty) &&
1172 "This is not a conversion to a SCEVable type!");
1173 Ty = getEffectiveSCEVType(Ty);
1175 // Sign-extend negative constants.
1176 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1177 if (SC->getValue()->getValue().isNegative())
1178 return getSignExtendExpr(Op, Ty);
1180 // Peel off a truncate cast.
1181 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1182 const SCEV *NewOp = T->getOperand();
1183 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1184 return getAnyExtendExpr(NewOp, Ty);
1185 return getTruncateOrNoop(NewOp, Ty);
1188 // Next try a zext cast. If the cast is folded, use it.
1189 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1190 if (!isa<SCEVZeroExtendExpr>(ZExt))
1193 // Next try a sext cast. If the cast is folded, use it.
1194 const SCEV *SExt = getSignExtendExpr(Op, Ty);
1195 if (!isa<SCEVSignExtendExpr>(SExt))
1198 // Force the cast to be folded into the operands of an addrec.
1199 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1200 SmallVector<const SCEV *, 4> Ops;
1201 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1203 Ops.push_back(getAnyExtendExpr(*I, Ty));
1204 return getAddRecExpr(Ops, AR->getLoop());
1207 // As a special case, fold anyext(undef) to undef. We don't want to
1208 // know too much about SCEVUnknowns, but this special case is handy
1210 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1211 if (isa<UndefValue>(U->getValue()))
1212 return getSCEV(UndefValue::get(Ty));
1214 // If the expression is obviously signed, use the sext cast value.
1215 if (isa<SCEVSMaxExpr>(Op))
1218 // Absent any other information, use the zext cast value.
1222 /// CollectAddOperandsWithScales - Process the given Ops list, which is
1223 /// a list of operands to be added under the given scale, update the given
1224 /// map. This is a helper function for getAddRecExpr. As an example of
1225 /// what it does, given a sequence of operands that would form an add
1226 /// expression like this:
1228 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1230 /// where A and B are constants, update the map with these values:
1232 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1234 /// and add 13 + A*B*29 to AccumulatedConstant.
1235 /// This will allow getAddRecExpr to produce this:
1237 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1239 /// This form often exposes folding opportunities that are hidden in
1240 /// the original operand list.
1242 /// Return true iff it appears that any interesting folding opportunities
1243 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1244 /// the common case where no interesting opportunities are present, and
1245 /// is also used as a check to avoid infinite recursion.
1248 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1249 SmallVector<const SCEV *, 8> &NewOps,
1250 APInt &AccumulatedConstant,
1251 const SCEV *const *Ops, size_t NumOperands,
1253 ScalarEvolution &SE) {
1254 bool Interesting = false;
1256 // Iterate over the add operands. They are sorted, with constants first.
1258 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1260 // Pull a buried constant out to the outside.
1261 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1263 AccumulatedConstant += Scale * C->getValue()->getValue();
1266 // Next comes everything else. We're especially interested in multiplies
1267 // here, but they're in the middle, so just visit the rest with one loop.
1268 for (; i != NumOperands; ++i) {
1269 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1270 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1272 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1273 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1274 // A multiplication of a constant with another add; recurse.
1275 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
1277 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1278 Add->op_begin(), Add->getNumOperands(),
1281 // A multiplication of a constant with some other value. Update
1283 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1284 const SCEV *Key = SE.getMulExpr(MulOps);
1285 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1286 M.insert(std::make_pair(Key, NewScale));
1288 NewOps.push_back(Pair.first->first);
1290 Pair.first->second += NewScale;
1291 // The map already had an entry for this value, which may indicate
1292 // a folding opportunity.
1297 // An ordinary operand. Update the map.
1298 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
1299 M.insert(std::make_pair(Ops[i], Scale));
1301 NewOps.push_back(Pair.first->first);
1303 Pair.first->second += Scale;
1304 // The map already had an entry for this value, which may indicate
1305 // a folding opportunity.
1315 struct APIntCompare {
1316 bool operator()(const APInt &LHS, const APInt &RHS) const {
1317 return LHS.ult(RHS);
1322 /// getAddExpr - Get a canonical add expression, or something simpler if
1324 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1325 bool HasNUW, bool HasNSW) {
1326 assert(!Ops.empty() && "Cannot get empty add!");
1327 if (Ops.size() == 1) return Ops[0];
1329 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
1330 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1331 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
1332 "SCEVAddExpr operand types don't match!");
1335 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1336 if (!HasNUW && HasNSW) {
1338 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1339 if (!isKnownNonNegative(Ops[i])) {
1343 if (All) HasNUW = true;
1346 // Sort by complexity, this groups all similar expression types together.
1347 GroupByComplexity(Ops, LI);
1349 // If there are any constants, fold them together.
1351 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1353 assert(Idx < Ops.size());
1354 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1355 // We found two constants, fold them together!
1356 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1357 RHSC->getValue()->getValue());
1358 if (Ops.size() == 2) return Ops[0];
1359 Ops.erase(Ops.begin()+1); // Erase the folded element
1360 LHSC = cast<SCEVConstant>(Ops[0]);
1363 // If we are left with a constant zero being added, strip it off.
1364 if (LHSC->getValue()->isZero()) {
1365 Ops.erase(Ops.begin());
1369 if (Ops.size() == 1) return Ops[0];
1372 // Okay, check to see if the same value occurs in the operand list twice. If
1373 // so, merge them together into an multiply expression. Since we sorted the
1374 // list, these values are required to be adjacent.
1375 const Type *Ty = Ops[0]->getType();
1376 bool FoundMatch = false;
1377 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1378 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1379 // Found a match, merge the two values into a multiply, and add any
1380 // remaining values to the result.
1381 const SCEV *Two = getConstant(Ty, 2);
1382 const SCEV *Mul = getMulExpr(Ops[i], Two);
1383 if (Ops.size() == 2)
1386 Ops.erase(Ops.begin()+i+1);
1391 return getAddExpr(Ops, HasNUW, HasNSW);
1393 // Check for truncates. If all the operands are truncated from the same
1394 // type, see if factoring out the truncate would permit the result to be
1395 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1396 // if the contents of the resulting outer trunc fold to something simple.
1397 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1398 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1399 const Type *DstType = Trunc->getType();
1400 const Type *SrcType = Trunc->getOperand()->getType();
1401 SmallVector<const SCEV *, 8> LargeOps;
1403 // Check all the operands to see if they can be represented in the
1404 // source type of the truncate.
1405 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1406 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1407 if (T->getOperand()->getType() != SrcType) {
1411 LargeOps.push_back(T->getOperand());
1412 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1413 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
1414 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1415 SmallVector<const SCEV *, 8> LargeMulOps;
1416 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1417 if (const SCEVTruncateExpr *T =
1418 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1419 if (T->getOperand()->getType() != SrcType) {
1423 LargeMulOps.push_back(T->getOperand());
1424 } else if (const SCEVConstant *C =
1425 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1426 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
1433 LargeOps.push_back(getMulExpr(LargeMulOps));
1440 // Evaluate the expression in the larger type.
1441 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
1442 // If it folds to something simple, use it. Otherwise, don't.
1443 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1444 return getTruncateExpr(Fold, DstType);
1448 // Skip past any other cast SCEVs.
1449 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1452 // If there are add operands they would be next.
1453 if (Idx < Ops.size()) {
1454 bool DeletedAdd = false;
1455 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
1456 // If we have an add, expand the add operands onto the end of the operands
1458 Ops.erase(Ops.begin()+Idx);
1459 Ops.append(Add->op_begin(), Add->op_end());
1463 // If we deleted at least one add, we added operands to the end of the list,
1464 // and they are not necessarily sorted. Recurse to resort and resimplify
1465 // any operands we just acquired.
1467 return getAddExpr(Ops);
1470 // Skip over the add expression until we get to a multiply.
1471 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1474 // Check to see if there are any folding opportunities present with
1475 // operands multiplied by constant values.
1476 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1477 uint64_t BitWidth = getTypeSizeInBits(Ty);
1478 DenseMap<const SCEV *, APInt> M;
1479 SmallVector<const SCEV *, 8> NewOps;
1480 APInt AccumulatedConstant(BitWidth, 0);
1481 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1482 Ops.data(), Ops.size(),
1483 APInt(BitWidth, 1), *this)) {
1484 // Some interesting folding opportunity is present, so its worthwhile to
1485 // re-generate the operands list. Group the operands by constant scale,
1486 // to avoid multiplying by the same constant scale multiple times.
1487 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1488 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
1489 E = NewOps.end(); I != E; ++I)
1490 MulOpLists[M.find(*I)->second].push_back(*I);
1491 // Re-generate the operands list.
1493 if (AccumulatedConstant != 0)
1494 Ops.push_back(getConstant(AccumulatedConstant));
1495 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1496 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1498 Ops.push_back(getMulExpr(getConstant(I->first),
1499 getAddExpr(I->second)));
1501 return getConstant(Ty, 0);
1502 if (Ops.size() == 1)
1504 return getAddExpr(Ops);
1508 // If we are adding something to a multiply expression, make sure the
1509 // something is not already an operand of the multiply. If so, merge it into
1511 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
1512 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
1513 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
1514 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
1515 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1516 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
1517 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1518 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
1519 if (Mul->getNumOperands() != 2) {
1520 // If the multiply has more than two operands, we must get the
1522 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
1523 MulOps.erase(MulOps.begin()+MulOp);
1524 InnerMul = getMulExpr(MulOps);
1526 const SCEV *One = getConstant(Ty, 1);
1527 const SCEV *AddOne = getAddExpr(InnerMul, One);
1528 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
1529 if (Ops.size() == 2) return OuterMul;
1531 Ops.erase(Ops.begin()+AddOp);
1532 Ops.erase(Ops.begin()+Idx-1);
1534 Ops.erase(Ops.begin()+Idx);
1535 Ops.erase(Ops.begin()+AddOp-1);
1537 Ops.push_back(OuterMul);
1538 return getAddExpr(Ops);
1541 // Check this multiply against other multiplies being added together.
1542 for (unsigned OtherMulIdx = Idx+1;
1543 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1545 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
1546 // If MulOp occurs in OtherMul, we can fold the two multiplies
1548 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1549 OMulOp != e; ++OMulOp)
1550 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1551 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1552 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
1553 if (Mul->getNumOperands() != 2) {
1554 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1556 MulOps.erase(MulOps.begin()+MulOp);
1557 InnerMul1 = getMulExpr(MulOps);
1559 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1560 if (OtherMul->getNumOperands() != 2) {
1561 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1562 OtherMul->op_end());
1563 MulOps.erase(MulOps.begin()+OMulOp);
1564 InnerMul2 = getMulExpr(MulOps);
1566 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1567 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
1568 if (Ops.size() == 2) return OuterMul;
1569 Ops.erase(Ops.begin()+Idx);
1570 Ops.erase(Ops.begin()+OtherMulIdx-1);
1571 Ops.push_back(OuterMul);
1572 return getAddExpr(Ops);
1578 // If there are any add recurrences in the operands list, see if any other
1579 // added values are loop invariant. If so, we can fold them into the
1581 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1584 // Scan over all recurrences, trying to fold loop invariants into them.
1585 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1586 // Scan all of the other operands to this add and add them to the vector if
1587 // they are loop invariant w.r.t. the recurrence.
1588 SmallVector<const SCEV *, 8> LIOps;
1589 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1590 const Loop *AddRecLoop = AddRec->getLoop();
1591 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1592 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
1593 LIOps.push_back(Ops[i]);
1594 Ops.erase(Ops.begin()+i);
1598 // If we found some loop invariants, fold them into the recurrence.
1599 if (!LIOps.empty()) {
1600 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
1601 LIOps.push_back(AddRec->getStart());
1603 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1605 AddRecOps[0] = getAddExpr(LIOps);
1607 // Build the new addrec. Propagate the NUW and NSW flags if both the
1608 // outer add and the inner addrec are guaranteed to have no overflow.
1609 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1610 HasNUW && AddRec->hasNoUnsignedWrap(),
1611 HasNSW && AddRec->hasNoSignedWrap());
1613 // If all of the other operands were loop invariant, we are done.
1614 if (Ops.size() == 1) return NewRec;
1616 // Otherwise, add the folded AddRec by the non-liv parts.
1617 for (unsigned i = 0;; ++i)
1618 if (Ops[i] == AddRec) {
1622 return getAddExpr(Ops);
1625 // Okay, if there weren't any loop invariants to be folded, check to see if
1626 // there are multiple AddRec's with the same loop induction variable being
1627 // added together. If so, we can fold them.
1628 for (unsigned OtherIdx = Idx+1;
1629 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1630 if (OtherIdx != Idx) {
1631 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1632 if (AddRecLoop == OtherAddRec->getLoop()) {
1633 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1634 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1636 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1637 if (i >= NewOps.size()) {
1638 NewOps.append(OtherAddRec->op_begin()+i,
1639 OtherAddRec->op_end());
1642 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
1644 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
1646 if (Ops.size() == 2) return NewAddRec;
1648 Ops.erase(Ops.begin()+Idx);
1649 Ops.erase(Ops.begin()+OtherIdx-1);
1650 Ops.push_back(NewAddRec);
1651 return getAddExpr(Ops);
1655 // Otherwise couldn't fold anything into this recurrence. Move onto the
1659 // Okay, it looks like we really DO need an add expr. Check to see if we
1660 // already have one, otherwise create a new one.
1661 FoldingSetNodeID ID;
1662 ID.AddInteger(scAddExpr);
1663 ID.AddInteger(Ops.size());
1664 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1665 ID.AddPointer(Ops[i]);
1668 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1670 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1671 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1672 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1674 UniqueSCEVs.InsertNode(S, IP);
1676 if (HasNUW) S->setHasNoUnsignedWrap(true);
1677 if (HasNSW) S->setHasNoSignedWrap(true);
1681 /// getMulExpr - Get a canonical multiply expression, or something simpler if
1683 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1684 bool HasNUW, bool HasNSW) {
1685 assert(!Ops.empty() && "Cannot get empty mul!");
1686 if (Ops.size() == 1) return Ops[0];
1688 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1689 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1690 getEffectiveSCEVType(Ops[0]->getType()) &&
1691 "SCEVMulExpr operand types don't match!");
1694 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1695 if (!HasNUW && HasNSW) {
1697 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1698 if (!isKnownNonNegative(Ops[i])) {
1702 if (All) HasNUW = true;
1705 // Sort by complexity, this groups all similar expression types together.
1706 GroupByComplexity(Ops, LI);
1708 // If there are any constants, fold them together.
1710 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1712 // C1*(C2+V) -> C1*C2 + C1*V
1713 if (Ops.size() == 2)
1714 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1715 if (Add->getNumOperands() == 2 &&
1716 isa<SCEVConstant>(Add->getOperand(0)))
1717 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1718 getMulExpr(LHSC, Add->getOperand(1)));
1721 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1722 // We found two constants, fold them together!
1723 ConstantInt *Fold = ConstantInt::get(getContext(),
1724 LHSC->getValue()->getValue() *
1725 RHSC->getValue()->getValue());
1726 Ops[0] = getConstant(Fold);
1727 Ops.erase(Ops.begin()+1); // Erase the folded element
1728 if (Ops.size() == 1) return Ops[0];
1729 LHSC = cast<SCEVConstant>(Ops[0]);
1732 // If we are left with a constant one being multiplied, strip it off.
1733 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1734 Ops.erase(Ops.begin());
1736 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1737 // If we have a multiply of zero, it will always be zero.
1739 } else if (Ops[0]->isAllOnesValue()) {
1740 // If we have a mul by -1 of an add, try distributing the -1 among the
1742 if (Ops.size() == 2)
1743 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1744 SmallVector<const SCEV *, 4> NewOps;
1745 bool AnyFolded = false;
1746 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1748 const SCEV *Mul = getMulExpr(Ops[0], *I);
1749 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1750 NewOps.push_back(Mul);
1753 return getAddExpr(NewOps);
1757 if (Ops.size() == 1)
1761 // Skip over the add expression until we get to a multiply.
1762 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1765 // If there are mul operands inline them all into this expression.
1766 if (Idx < Ops.size()) {
1767 bool DeletedMul = false;
1768 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1769 // If we have an mul, expand the mul operands onto the end of the operands
1771 Ops.erase(Ops.begin()+Idx);
1772 Ops.append(Mul->op_begin(), Mul->op_end());
1776 // If we deleted at least one mul, we added operands to the end of the list,
1777 // and they are not necessarily sorted. Recurse to resort and resimplify
1778 // any operands we just acquired.
1780 return getMulExpr(Ops);
1783 // If there are any add recurrences in the operands list, see if any other
1784 // added values are loop invariant. If so, we can fold them into the
1786 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1789 // Scan over all recurrences, trying to fold loop invariants into them.
1790 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1791 // Scan all of the other operands to this mul and add them to the vector if
1792 // they are loop invariant w.r.t. the recurrence.
1793 SmallVector<const SCEV *, 8> LIOps;
1794 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1795 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1796 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1797 LIOps.push_back(Ops[i]);
1798 Ops.erase(Ops.begin()+i);
1802 // If we found some loop invariants, fold them into the recurrence.
1803 if (!LIOps.empty()) {
1804 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
1805 SmallVector<const SCEV *, 4> NewOps;
1806 NewOps.reserve(AddRec->getNumOperands());
1807 const SCEV *Scale = getMulExpr(LIOps);
1808 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1809 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1811 // Build the new addrec. Propagate the NUW and NSW flags if both the
1812 // outer mul and the inner addrec are guaranteed to have no overflow.
1813 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1814 HasNUW && AddRec->hasNoUnsignedWrap(),
1815 HasNSW && AddRec->hasNoSignedWrap());
1817 // If all of the other operands were loop invariant, we are done.
1818 if (Ops.size() == 1) return NewRec;
1820 // Otherwise, multiply the folded AddRec by the non-liv parts.
1821 for (unsigned i = 0;; ++i)
1822 if (Ops[i] == AddRec) {
1826 return getMulExpr(Ops);
1829 // Okay, if there weren't any loop invariants to be folded, check to see if
1830 // there are multiple AddRec's with the same loop induction variable being
1831 // multiplied together. If so, we can fold them.
1832 for (unsigned OtherIdx = Idx+1;
1833 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1834 if (OtherIdx != Idx) {
1835 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1836 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1837 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1838 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1839 const SCEV *NewStart = getMulExpr(F->getStart(),
1841 const SCEV *B = F->getStepRecurrence(*this);
1842 const SCEV *D = G->getStepRecurrence(*this);
1843 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1846 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1848 if (Ops.size() == 2) return NewAddRec;
1850 Ops.erase(Ops.begin()+Idx);
1851 Ops.erase(Ops.begin()+OtherIdx-1);
1852 Ops.push_back(NewAddRec);
1853 return getMulExpr(Ops);
1857 // Otherwise couldn't fold anything into this recurrence. Move onto the
1861 // Okay, it looks like we really DO need an mul expr. Check to see if we
1862 // already have one, otherwise create a new one.
1863 FoldingSetNodeID ID;
1864 ID.AddInteger(scMulExpr);
1865 ID.AddInteger(Ops.size());
1866 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1867 ID.AddPointer(Ops[i]);
1870 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1872 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1873 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
1874 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1876 UniqueSCEVs.InsertNode(S, IP);
1878 if (HasNUW) S->setHasNoUnsignedWrap(true);
1879 if (HasNSW) S->setHasNoSignedWrap(true);
1883 /// getUDivExpr - Get a canonical unsigned division expression, or something
1884 /// simpler if possible.
1885 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1887 assert(getEffectiveSCEVType(LHS->getType()) ==
1888 getEffectiveSCEVType(RHS->getType()) &&
1889 "SCEVUDivExpr operand types don't match!");
1891 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1892 if (RHSC->getValue()->equalsInt(1))
1893 return LHS; // X udiv 1 --> x
1894 // If the denominator is zero, the result of the udiv is undefined. Don't
1895 // try to analyze it, because the resolution chosen here may differ from
1896 // the resolution chosen in other parts of the compiler.
1897 if (!RHSC->getValue()->isZero()) {
1898 // Determine if the division can be folded into the operands of
1900 // TODO: Generalize this to non-constants by using known-bits information.
1901 const Type *Ty = LHS->getType();
1902 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1903 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
1904 // For non-power-of-two values, effectively round the value up to the
1905 // nearest power of two.
1906 if (!RHSC->getValue()->getValue().isPowerOf2())
1908 const IntegerType *ExtTy =
1909 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1910 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1911 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1912 if (const SCEVConstant *Step =
1913 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1914 if (!Step->getValue()->getValue()
1915 .urem(RHSC->getValue()->getValue()) &&
1916 getZeroExtendExpr(AR, ExtTy) ==
1917 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1918 getZeroExtendExpr(Step, ExtTy),
1920 SmallVector<const SCEV *, 4> Operands;
1921 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1922 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1923 return getAddRecExpr(Operands, AR->getLoop());
1925 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1926 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1927 SmallVector<const SCEV *, 4> Operands;
1928 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1929 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1930 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1931 // Find an operand that's safely divisible.
1932 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1933 const SCEV *Op = M->getOperand(i);
1934 const SCEV *Div = getUDivExpr(Op, RHSC);
1935 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1936 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1939 return getMulExpr(Operands);
1943 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1944 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1945 SmallVector<const SCEV *, 4> Operands;
1946 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1947 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1948 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1950 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1951 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1952 if (isa<SCEVUDivExpr>(Op) ||
1953 getMulExpr(Op, RHS) != A->getOperand(i))
1955 Operands.push_back(Op);
1957 if (Operands.size() == A->getNumOperands())
1958 return getAddExpr(Operands);
1962 // Fold if both operands are constant.
1963 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1964 Constant *LHSCV = LHSC->getValue();
1965 Constant *RHSCV = RHSC->getValue();
1966 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1972 FoldingSetNodeID ID;
1973 ID.AddInteger(scUDivExpr);
1977 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1978 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1980 UniqueSCEVs.InsertNode(S, IP);
1985 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
1986 /// Simplify the expression as much as possible.
1987 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1988 const SCEV *Step, const Loop *L,
1989 bool HasNUW, bool HasNSW) {
1990 SmallVector<const SCEV *, 4> Operands;
1991 Operands.push_back(Start);
1992 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1993 if (StepChrec->getLoop() == L) {
1994 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
1995 return getAddRecExpr(Operands, L);
1998 Operands.push_back(Step);
1999 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
2002 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
2003 /// Simplify the expression as much as possible.
2005 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2007 bool HasNUW, bool HasNSW) {
2008 if (Operands.size() == 1) return Operands[0];
2010 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2011 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
2012 getEffectiveSCEVType(Operands[0]->getType()) &&
2013 "SCEVAddRecExpr operand types don't match!");
2016 if (Operands.back()->isZero()) {
2017 Operands.pop_back();
2018 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
2021 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2022 // use that information to infer NUW and NSW flags. However, computing a
2023 // BE count requires calling getAddRecExpr, so we may not yet have a
2024 // meaningful BE count at this point (and if we don't, we'd be stuck
2025 // with a SCEVCouldNotCompute as the cached BE count).
2027 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2028 if (!HasNUW && HasNSW) {
2030 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2031 if (!isKnownNonNegative(Operands[i])) {
2035 if (All) HasNUW = true;
2038 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2039 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2040 const Loop *NestedLoop = NestedAR->getLoop();
2041 if (L->contains(NestedLoop->getHeader()) ?
2042 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2043 (!NestedLoop->contains(L->getHeader()) &&
2044 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
2045 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
2046 NestedAR->op_end());
2047 Operands[0] = NestedAR->getStart();
2048 // AddRecs require their operands be loop-invariant with respect to their
2049 // loops. Don't perform this transformation if it would break this
2051 bool AllInvariant = true;
2052 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2053 if (!Operands[i]->isLoopInvariant(L)) {
2054 AllInvariant = false;
2058 NestedOperands[0] = getAddRecExpr(Operands, L);
2059 AllInvariant = true;
2060 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2061 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2062 AllInvariant = false;
2066 // Ok, both add recurrences are valid after the transformation.
2067 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
2069 // Reset Operands to its original state.
2070 Operands[0] = NestedAR;
2074 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2075 // already have one, otherwise create a new one.
2076 FoldingSetNodeID ID;
2077 ID.AddInteger(scAddRecExpr);
2078 ID.AddInteger(Operands.size());
2079 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2080 ID.AddPointer(Operands[i]);
2084 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2086 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2087 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
2088 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2089 O, Operands.size(), L);
2090 UniqueSCEVs.InsertNode(S, IP);
2092 if (HasNUW) S->setHasNoUnsignedWrap(true);
2093 if (HasNSW) S->setHasNoSignedWrap(true);
2097 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2099 SmallVector<const SCEV *, 2> Ops;
2102 return getSMaxExpr(Ops);
2106 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2107 assert(!Ops.empty() && "Cannot get empty smax!");
2108 if (Ops.size() == 1) return Ops[0];
2110 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2111 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2112 getEffectiveSCEVType(Ops[0]->getType()) &&
2113 "SCEVSMaxExpr operand types don't match!");
2116 // Sort by complexity, this groups all similar expression types together.
2117 GroupByComplexity(Ops, LI);
2119 // If there are any constants, fold them together.
2121 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2123 assert(Idx < Ops.size());
2124 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2125 // We found two constants, fold them together!
2126 ConstantInt *Fold = ConstantInt::get(getContext(),
2127 APIntOps::smax(LHSC->getValue()->getValue(),
2128 RHSC->getValue()->getValue()));
2129 Ops[0] = getConstant(Fold);
2130 Ops.erase(Ops.begin()+1); // Erase the folded element
2131 if (Ops.size() == 1) return Ops[0];
2132 LHSC = cast<SCEVConstant>(Ops[0]);
2135 // If we are left with a constant minimum-int, strip it off.
2136 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2137 Ops.erase(Ops.begin());
2139 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2140 // If we have an smax with a constant maximum-int, it will always be
2145 if (Ops.size() == 1) return Ops[0];
2148 // Find the first SMax
2149 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2152 // Check to see if one of the operands is an SMax. If so, expand its operands
2153 // onto our operand list, and recurse to simplify.
2154 if (Idx < Ops.size()) {
2155 bool DeletedSMax = false;
2156 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
2157 Ops.erase(Ops.begin()+Idx);
2158 Ops.append(SMax->op_begin(), SMax->op_end());
2163 return getSMaxExpr(Ops);
2166 // Okay, check to see if the same value occurs in the operand list twice. If
2167 // so, delete one. Since we sorted the list, these values are required to
2169 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2170 // X smax Y smax Y --> X smax Y
2171 // X smax Y --> X, if X is always greater than Y
2172 if (Ops[i] == Ops[i+1] ||
2173 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2174 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2176 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
2177 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2181 if (Ops.size() == 1) return Ops[0];
2183 assert(!Ops.empty() && "Reduced smax down to nothing!");
2185 // Okay, it looks like we really DO need an smax expr. Check to see if we
2186 // already have one, otherwise create a new one.
2187 FoldingSetNodeID ID;
2188 ID.AddInteger(scSMaxExpr);
2189 ID.AddInteger(Ops.size());
2190 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2191 ID.AddPointer(Ops[i]);
2193 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2194 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2195 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2196 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2198 UniqueSCEVs.InsertNode(S, IP);
2202 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2204 SmallVector<const SCEV *, 2> Ops;
2207 return getUMaxExpr(Ops);
2211 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
2212 assert(!Ops.empty() && "Cannot get empty umax!");
2213 if (Ops.size() == 1) return Ops[0];
2215 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2216 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2217 getEffectiveSCEVType(Ops[0]->getType()) &&
2218 "SCEVUMaxExpr operand types don't match!");
2221 // Sort by complexity, this groups all similar expression types together.
2222 GroupByComplexity(Ops, LI);
2224 // If there are any constants, fold them together.
2226 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2228 assert(Idx < Ops.size());
2229 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2230 // We found two constants, fold them together!
2231 ConstantInt *Fold = ConstantInt::get(getContext(),
2232 APIntOps::umax(LHSC->getValue()->getValue(),
2233 RHSC->getValue()->getValue()));
2234 Ops[0] = getConstant(Fold);
2235 Ops.erase(Ops.begin()+1); // Erase the folded element
2236 if (Ops.size() == 1) return Ops[0];
2237 LHSC = cast<SCEVConstant>(Ops[0]);
2240 // If we are left with a constant minimum-int, strip it off.
2241 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2242 Ops.erase(Ops.begin());
2244 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2245 // If we have an umax with a constant maximum-int, it will always be
2250 if (Ops.size() == 1) return Ops[0];
2253 // Find the first UMax
2254 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2257 // Check to see if one of the operands is a UMax. If so, expand its operands
2258 // onto our operand list, and recurse to simplify.
2259 if (Idx < Ops.size()) {
2260 bool DeletedUMax = false;
2261 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
2262 Ops.erase(Ops.begin()+Idx);
2263 Ops.append(UMax->op_begin(), UMax->op_end());
2268 return getUMaxExpr(Ops);
2271 // Okay, check to see if the same value occurs in the operand list twice. If
2272 // so, delete one. Since we sorted the list, these values are required to
2274 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2275 // X umax Y umax Y --> X umax Y
2276 // X umax Y --> X, if X is always greater than Y
2277 if (Ops[i] == Ops[i+1] ||
2278 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2279 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2281 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
2282 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2286 if (Ops.size() == 1) return Ops[0];
2288 assert(!Ops.empty() && "Reduced umax down to nothing!");
2290 // Okay, it looks like we really DO need a umax expr. Check to see if we
2291 // already have one, otherwise create a new one.
2292 FoldingSetNodeID ID;
2293 ID.AddInteger(scUMaxExpr);
2294 ID.AddInteger(Ops.size());
2295 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2296 ID.AddPointer(Ops[i]);
2298 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2299 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2300 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2301 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2303 UniqueSCEVs.InsertNode(S, IP);
2307 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2309 // ~smax(~x, ~y) == smin(x, y).
2310 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2313 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2315 // ~umax(~x, ~y) == umin(x, y)
2316 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2319 const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2320 // If we have TargetData, we can bypass creating a target-independent
2321 // constant expression and then folding it back into a ConstantInt.
2322 // This is just a compile-time optimization.
2324 return getConstant(TD->getIntPtrType(getContext()),
2325 TD->getTypeAllocSize(AllocTy));
2327 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2329 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2331 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2332 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2335 const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2336 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2337 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2338 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2340 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2341 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2344 const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2346 // If we have TargetData, we can bypass creating a target-independent
2347 // constant expression and then folding it back into a ConstantInt.
2348 // This is just a compile-time optimization.
2350 return getConstant(TD->getIntPtrType(getContext()),
2351 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2353 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2354 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2355 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2357 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2358 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2361 const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2362 Constant *FieldNo) {
2363 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
2364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2365 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2367 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
2368 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2371 const SCEV *ScalarEvolution::getUnknown(Value *V) {
2372 // Don't attempt to do anything other than create a SCEVUnknown object
2373 // here. createSCEV only calls getUnknown after checking for all other
2374 // interesting possibilities, and any other code that calls getUnknown
2375 // is doing so in order to hide a value from SCEV canonicalization.
2377 FoldingSetNodeID ID;
2378 ID.AddInteger(scUnknown);
2381 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2382 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2383 "Stale SCEVUnknown in uniquing map!");
2386 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2388 FirstUnknown = cast<SCEVUnknown>(S);
2389 UniqueSCEVs.InsertNode(S, IP);
2393 //===----------------------------------------------------------------------===//
2394 // Basic SCEV Analysis and PHI Idiom Recognition Code
2397 /// isSCEVable - Test if values of the given type are analyzable within
2398 /// the SCEV framework. This primarily includes integer types, and it
2399 /// can optionally include pointer types if the ScalarEvolution class
2400 /// has access to target-specific information.
2401 bool ScalarEvolution::isSCEVable(const Type *Ty) const {
2402 // Integers and pointers are always SCEVable.
2403 return Ty->isIntegerTy() || Ty->isPointerTy();
2406 /// getTypeSizeInBits - Return the size in bits of the specified type,
2407 /// for which isSCEVable must return true.
2408 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
2409 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2411 // If we have a TargetData, use it!
2413 return TD->getTypeSizeInBits(Ty);
2415 // Integer types have fixed sizes.
2416 if (Ty->isIntegerTy())
2417 return Ty->getPrimitiveSizeInBits();
2419 // The only other support type is pointer. Without TargetData, conservatively
2420 // assume pointers are 64-bit.
2421 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
2425 /// getEffectiveSCEVType - Return a type with the same bitwidth as
2426 /// the given type and which represents how SCEV will treat the given
2427 /// type, for which isSCEVable must return true. For pointer types,
2428 /// this is the pointer-sized integer type.
2429 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
2430 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2432 if (Ty->isIntegerTy())
2435 // The only other support type is pointer.
2436 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
2437 if (TD) return TD->getIntPtrType(getContext());
2439 // Without TargetData, conservatively assume pointers are 64-bit.
2440 return Type::getInt64Ty(getContext());
2443 const SCEV *ScalarEvolution::getCouldNotCompute() {
2444 return &CouldNotCompute;
2447 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2448 /// expression and create a new one.
2449 const SCEV *ScalarEvolution::getSCEV(Value *V) {
2450 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
2452 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
2453 if (I != Scalars.end()) return I->second;
2454 const SCEV *S = createSCEV(V);
2455 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
2459 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2461 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
2462 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2464 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
2466 const Type *Ty = V->getType();
2467 Ty = getEffectiveSCEVType(Ty);
2468 return getMulExpr(V,
2469 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
2472 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
2473 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
2474 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
2476 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
2478 const Type *Ty = V->getType();
2479 Ty = getEffectiveSCEVType(Ty);
2480 const SCEV *AllOnes =
2481 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
2482 return getMinusSCEV(AllOnes, V);
2485 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2487 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2489 // Fast path: X - X --> 0.
2491 return getConstant(LHS->getType(), 0);
2494 return getAddExpr(LHS, getNegativeSCEV(RHS));
2497 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2498 /// input value to the specified type. If the type must be extended, it is zero
2501 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
2503 const Type *SrcTy = V->getType();
2504 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2505 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2506 "Cannot truncate or zero extend with non-integer arguments!");
2507 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2508 return V; // No conversion
2509 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2510 return getTruncateExpr(V, Ty);
2511 return getZeroExtendExpr(V, Ty);
2514 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2515 /// input value to the specified type. If the type must be extended, it is sign
2518 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
2520 const Type *SrcTy = V->getType();
2521 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2522 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2523 "Cannot truncate or zero extend with non-integer arguments!");
2524 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2525 return V; // No conversion
2526 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
2527 return getTruncateExpr(V, Ty);
2528 return getSignExtendExpr(V, Ty);
2531 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2532 /// input value to the specified type. If the type must be extended, it is zero
2533 /// extended. The conversion must not be narrowing.
2535 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
2536 const Type *SrcTy = V->getType();
2537 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2538 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2539 "Cannot noop or zero extend with non-integer arguments!");
2540 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2541 "getNoopOrZeroExtend cannot truncate!");
2542 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2543 return V; // No conversion
2544 return getZeroExtendExpr(V, Ty);
2547 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2548 /// input value to the specified type. If the type must be extended, it is sign
2549 /// extended. The conversion must not be narrowing.
2551 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
2552 const Type *SrcTy = V->getType();
2553 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2554 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2555 "Cannot noop or sign extend with non-integer arguments!");
2556 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2557 "getNoopOrSignExtend cannot truncate!");
2558 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2559 return V; // No conversion
2560 return getSignExtendExpr(V, Ty);
2563 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2564 /// the input value to the specified type. If the type must be extended,
2565 /// it is extended with unspecified bits. The conversion must not be
2568 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
2569 const Type *SrcTy = V->getType();
2570 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2571 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2572 "Cannot noop or any extend with non-integer arguments!");
2573 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2574 "getNoopOrAnyExtend cannot truncate!");
2575 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2576 return V; // No conversion
2577 return getAnyExtendExpr(V, Ty);
2580 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2581 /// input value to the specified type. The conversion must not be widening.
2583 ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
2584 const Type *SrcTy = V->getType();
2585 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2586 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
2587 "Cannot truncate or noop with non-integer arguments!");
2588 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2589 "getTruncateOrNoop cannot extend!");
2590 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2591 return V; // No conversion
2592 return getTruncateExpr(V, Ty);
2595 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2596 /// the types using zero-extension, and then perform a umax operation
2598 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2600 const SCEV *PromotedLHS = LHS;
2601 const SCEV *PromotedRHS = RHS;
2603 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2604 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2606 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2608 return getUMaxExpr(PromotedLHS, PromotedRHS);
2611 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
2612 /// the types using zero-extension, and then perform a umin operation
2614 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2616 const SCEV *PromotedLHS = LHS;
2617 const SCEV *PromotedRHS = RHS;
2619 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2620 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2622 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2624 return getUMinExpr(PromotedLHS, PromotedRHS);
2627 /// PushDefUseChildren - Push users of the given Instruction
2628 /// onto the given Worklist.
2630 PushDefUseChildren(Instruction *I,
2631 SmallVectorImpl<Instruction *> &Worklist) {
2632 // Push the def-use children onto the Worklist stack.
2633 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2635 Worklist.push_back(cast<Instruction>(*UI));
2638 /// ForgetSymbolicValue - This looks up computed SCEV values for all
2639 /// instructions that depend on the given instruction and removes them from
2640 /// the Scalars map if they reference SymName. This is used during PHI
2643 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
2644 SmallVector<Instruction *, 16> Worklist;
2645 PushDefUseChildren(PN, Worklist);
2647 SmallPtrSet<Instruction *, 8> Visited;
2649 while (!Worklist.empty()) {
2650 Instruction *I = Worklist.pop_back_val();
2651 if (!Visited.insert(I)) continue;
2653 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
2654 Scalars.find(static_cast<Value *>(I));
2655 if (It != Scalars.end()) {
2656 // Short-circuit the def-use traversal if the symbolic name
2657 // ceases to appear in expressions.
2658 if (It->second != SymName && !It->second->hasOperand(SymName))
2661 // SCEVUnknown for a PHI either means that it has an unrecognized
2662 // structure, it's a PHI that's in the progress of being computed
2663 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2664 // additional loop trip count information isn't going to change anything.
2665 // In the second case, createNodeForPHI will perform the necessary
2666 // updates on its own when it gets to that point. In the third, we do
2667 // want to forget the SCEVUnknown.
2668 if (!isa<PHINode>(I) ||
2669 !isa<SCEVUnknown>(It->second) ||
2670 (I != PN && It->second == SymName)) {
2671 ValuesAtScopes.erase(It->second);
2676 PushDefUseChildren(I, Worklist);
2680 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2681 /// a loop header, making it a potential recurrence, or it doesn't.
2683 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
2684 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2685 if (L->getHeader() == PN->getParent()) {
2686 // The loop may have multiple entrances or multiple exits; we can analyze
2687 // this phi as an addrec if it has a unique entry value and a unique
2689 Value *BEValueV = 0, *StartValueV = 0;
2690 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2691 Value *V = PN->getIncomingValue(i);
2692 if (L->contains(PN->getIncomingBlock(i))) {
2695 } else if (BEValueV != V) {
2699 } else if (!StartValueV) {
2701 } else if (StartValueV != V) {
2706 if (BEValueV && StartValueV) {
2707 // While we are analyzing this PHI node, handle its value symbolically.
2708 const SCEV *SymbolicName = getUnknown(PN);
2709 assert(Scalars.find(PN) == Scalars.end() &&
2710 "PHI node already processed?");
2711 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
2713 // Using this symbolic name for the PHI, analyze the value coming around
2715 const SCEV *BEValue = getSCEV(BEValueV);
2717 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2718 // has a special value for the first iteration of the loop.
2720 // If the value coming around the backedge is an add with the symbolic
2721 // value we just inserted, then we found a simple induction variable!
2722 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
2723 // If there is a single occurrence of the symbolic value, replace it
2724 // with a recurrence.
2725 unsigned FoundIndex = Add->getNumOperands();
2726 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2727 if (Add->getOperand(i) == SymbolicName)
2728 if (FoundIndex == e) {
2733 if (FoundIndex != Add->getNumOperands()) {
2734 // Create an add with everything but the specified operand.
2735 SmallVector<const SCEV *, 8> Ops;
2736 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2737 if (i != FoundIndex)
2738 Ops.push_back(Add->getOperand(i));
2739 const SCEV *Accum = getAddExpr(Ops);
2741 // This is not a valid addrec if the step amount is varying each
2742 // loop iteration, but is not itself an addrec in this loop.
2743 if (Accum->isLoopInvariant(L) ||
2744 (isa<SCEVAddRecExpr>(Accum) &&
2745 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2746 bool HasNUW = false;
2747 bool HasNSW = false;
2749 // If the increment doesn't overflow, then neither the addrec nor
2750 // the post-increment will overflow.
2751 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2752 if (OBO->hasNoUnsignedWrap())
2754 if (OBO->hasNoSignedWrap())
2758 const SCEV *StartVal = getSCEV(StartValueV);
2759 const SCEV *PHISCEV =
2760 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
2762 // Since the no-wrap flags are on the increment, they apply to the
2763 // post-incremented value as well.
2764 if (Accum->isLoopInvariant(L))
2765 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2766 Accum, L, HasNUW, HasNSW);
2768 // Okay, for the entire analysis of this edge we assumed the PHI
2769 // to be symbolic. We now need to go back and purge all of the
2770 // entries for the scalars that use the symbolic expression.
2771 ForgetSymbolicName(PN, SymbolicName);
2772 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2776 } else if (const SCEVAddRecExpr *AddRec =
2777 dyn_cast<SCEVAddRecExpr>(BEValue)) {
2778 // Otherwise, this could be a loop like this:
2779 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2780 // In this case, j = {1,+,1} and BEValue is j.
2781 // Because the other in-value of i (0) fits the evolution of BEValue
2782 // i really is an addrec evolution.
2783 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2784 const SCEV *StartVal = getSCEV(StartValueV);
2786 // If StartVal = j.start - j.stride, we can use StartVal as the
2787 // initial step of the addrec evolution.
2788 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
2789 AddRec->getOperand(1))) {
2790 const SCEV *PHISCEV =
2791 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
2793 // Okay, for the entire analysis of this edge we assumed the PHI
2794 // to be symbolic. We now need to go back and purge all of the
2795 // entries for the scalars that use the symbolic expression.
2796 ForgetSymbolicName(PN, SymbolicName);
2797 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
2805 // If the PHI has a single incoming value, follow that value, unless the
2806 // PHI's incoming blocks are in a different loop, in which case doing so
2807 // risks breaking LCSSA form. Instcombine would normally zap these, but
2808 // it doesn't have DominatorTree information, so it may miss cases.
2809 if (Value *V = PN->hasConstantValue(DT)) {
2810 bool AllSameLoop = true;
2811 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2812 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2813 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2814 AllSameLoop = false;
2821 // If it's not a loop phi, we can't handle it yet.
2822 return getUnknown(PN);
2825 /// createNodeForGEP - Expand GEP instructions into add and multiply
2826 /// operations. This allows them to be analyzed by regular SCEV code.
2828 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
2830 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2831 // Add expression, because the Instruction may be guarded by control flow
2832 // and the no-overflow bits may not be valid for the expression in any
2835 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
2836 Value *Base = GEP->getOperand(0);
2837 // Don't attempt to analyze GEPs over unsized objects.
2838 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2839 return getUnknown(GEP);
2840 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
2841 gep_type_iterator GTI = gep_type_begin(GEP);
2842 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
2846 // Compute the (potentially symbolic) offset in bytes for this index.
2847 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2848 // For a struct, add the member offset.
2849 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2850 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2852 // Add the field offset to the running total offset.
2853 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2855 // For an array, add the element offset, explicitly scaled.
2856 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2857 const SCEV *IndexS = getSCEV(Index);
2858 // Getelementptr indices are signed.
2859 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2861 // Multiply the index by the element size to compute the element offset.
2862 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
2864 // Add the element offset to the running total offset.
2865 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2869 // Get the SCEV for the GEP base.
2870 const SCEV *BaseS = getSCEV(Base);
2872 // Add the total offset from all the GEP indices to the base.
2873 return getAddExpr(BaseS, TotalOffset);
2876 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2877 /// guaranteed to end in (at every loop iteration). It is, at the same time,
2878 /// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2879 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
2881 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
2882 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2883 return C->getValue()->getValue().countTrailingZeros();
2885 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
2886 return std::min(GetMinTrailingZeros(T->getOperand()),
2887 (uint32_t)getTypeSizeInBits(T->getType()));
2889 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
2890 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2891 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2892 getTypeSizeInBits(E->getType()) : OpRes;
2895 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
2896 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2897 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2898 getTypeSizeInBits(E->getType()) : OpRes;
2901 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2902 // The result is the min of all operands results.
2903 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2904 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2905 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2909 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
2910 // The result is the sum of all operands results.
2911 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2912 uint32_t BitWidth = getTypeSizeInBits(M->getType());
2913 for (unsigned i = 1, e = M->getNumOperands();
2914 SumOpRes != BitWidth && i != e; ++i)
2915 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
2920 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
2921 // The result is the min of all operands results.
2922 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
2923 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
2924 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
2928 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
2929 // The result is the min of all operands results.
2930 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2931 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2932 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2936 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
2937 // The result is the min of all operands results.
2938 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
2939 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
2940 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
2944 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2945 // For a SCEVUnknown, ask ValueTracking.
2946 unsigned BitWidth = getTypeSizeInBits(U->getType());
2947 APInt Mask = APInt::getAllOnesValue(BitWidth);
2948 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2949 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2950 return Zeros.countTrailingOnes();
2957 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2960 ScalarEvolution::getUnsignedRange(const SCEV *S) {
2962 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2963 return ConstantRange(C->getValue()->getValue());
2965 unsigned BitWidth = getTypeSizeInBits(S->getType());
2966 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2968 // If the value has known zeros, the maximum unsigned value will have those
2969 // known zeros as well.
2970 uint32_t TZ = GetMinTrailingZeros(S);
2972 ConservativeResult =
2973 ConstantRange(APInt::getMinValue(BitWidth),
2974 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2976 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2977 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2978 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2979 X = X.add(getUnsignedRange(Add->getOperand(i)));
2980 return ConservativeResult.intersectWith(X);
2983 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2984 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2985 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2986 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2987 return ConservativeResult.intersectWith(X);
2990 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2991 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2992 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2993 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2994 return ConservativeResult.intersectWith(X);
2997 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2998 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2999 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3000 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
3001 return ConservativeResult.intersectWith(X);
3004 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3005 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3006 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
3007 return ConservativeResult.intersectWith(X.udiv(Y));
3010 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3011 ConstantRange X = getUnsignedRange(ZExt->getOperand());
3012 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3015 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3016 ConstantRange X = getUnsignedRange(SExt->getOperand());
3017 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3020 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3021 ConstantRange X = getUnsignedRange(Trunc->getOperand());
3022 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3025 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3026 // If there's no unsigned wrap, the value will never be less than its
3028 if (AddRec->hasNoUnsignedWrap())
3029 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
3030 if (!C->getValue()->isZero())
3031 ConservativeResult =
3032 ConservativeResult.intersectWith(
3033 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
3035 // TODO: non-affine addrec
3036 if (AddRec->isAffine()) {
3037 const Type *Ty = AddRec->getType();
3038 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3039 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3040 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3041 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3043 const SCEV *Start = AddRec->getStart();
3044 const SCEV *Step = AddRec->getStepRecurrence(*this);
3046 ConstantRange StartRange = getUnsignedRange(Start);
3047 ConstantRange StepRange = getSignedRange(Step);
3048 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3049 ConstantRange EndRange =
3050 StartRange.add(MaxBECountRange.multiply(StepRange));
3052 // Check for overflow. This must be done with ConstantRange arithmetic
3053 // because we could be called from within the ScalarEvolution overflow
3055 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3056 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3057 ConstantRange ExtMaxBECountRange =
3058 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3059 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3060 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3062 return ConservativeResult;
3064 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3065 EndRange.getUnsignedMin());
3066 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3067 EndRange.getUnsignedMax());
3068 if (Min.isMinValue() && Max.isMaxValue())
3069 return ConservativeResult;
3070 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3074 return ConservativeResult;
3077 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3078 // For a SCEVUnknown, ask ValueTracking.
3079 APInt Mask = APInt::getAllOnesValue(BitWidth);
3080 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3081 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
3082 if (Ones == ~Zeros + 1)
3083 return ConservativeResult;
3084 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
3087 return ConservativeResult;
3090 /// getSignedRange - Determine the signed range for a particular SCEV.
3093 ScalarEvolution::getSignedRange(const SCEV *S) {
3095 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3096 return ConstantRange(C->getValue()->getValue());
3098 unsigned BitWidth = getTypeSizeInBits(S->getType());
3099 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3101 // If the value has known zeros, the maximum signed value will have those
3102 // known zeros as well.
3103 uint32_t TZ = GetMinTrailingZeros(S);
3105 ConservativeResult =
3106 ConstantRange(APInt::getSignedMinValue(BitWidth),
3107 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3109 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3110 ConstantRange X = getSignedRange(Add->getOperand(0));
3111 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3112 X = X.add(getSignedRange(Add->getOperand(i)));
3113 return ConservativeResult.intersectWith(X);
3116 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3117 ConstantRange X = getSignedRange(Mul->getOperand(0));
3118 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3119 X = X.multiply(getSignedRange(Mul->getOperand(i)));
3120 return ConservativeResult.intersectWith(X);
3123 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3124 ConstantRange X = getSignedRange(SMax->getOperand(0));
3125 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3126 X = X.smax(getSignedRange(SMax->getOperand(i)));
3127 return ConservativeResult.intersectWith(X);
3130 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3131 ConstantRange X = getSignedRange(UMax->getOperand(0));
3132 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3133 X = X.umax(getSignedRange(UMax->getOperand(i)));
3134 return ConservativeResult.intersectWith(X);
3137 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3138 ConstantRange X = getSignedRange(UDiv->getLHS());
3139 ConstantRange Y = getSignedRange(UDiv->getRHS());
3140 return ConservativeResult.intersectWith(X.udiv(Y));
3143 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3144 ConstantRange X = getSignedRange(ZExt->getOperand());
3145 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
3148 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3149 ConstantRange X = getSignedRange(SExt->getOperand());
3150 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
3153 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3154 ConstantRange X = getSignedRange(Trunc->getOperand());
3155 return ConservativeResult.intersectWith(X.truncate(BitWidth));
3158 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
3159 // If there's no signed wrap, and all the operands have the same sign or
3160 // zero, the value won't ever change sign.
3161 if (AddRec->hasNoSignedWrap()) {
3162 bool AllNonNeg = true;
3163 bool AllNonPos = true;
3164 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3165 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3166 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3169 ConservativeResult = ConservativeResult.intersectWith(
3170 ConstantRange(APInt(BitWidth, 0),
3171 APInt::getSignedMinValue(BitWidth)));
3173 ConservativeResult = ConservativeResult.intersectWith(
3174 ConstantRange(APInt::getSignedMinValue(BitWidth),
3175 APInt(BitWidth, 1)));
3178 // TODO: non-affine addrec
3179 if (AddRec->isAffine()) {
3180 const Type *Ty = AddRec->getType();
3181 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
3182 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3183 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
3184 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3186 const SCEV *Start = AddRec->getStart();
3187 const SCEV *Step = AddRec->getStepRecurrence(*this);
3189 ConstantRange StartRange = getSignedRange(Start);
3190 ConstantRange StepRange = getSignedRange(Step);
3191 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3192 ConstantRange EndRange =
3193 StartRange.add(MaxBECountRange.multiply(StepRange));
3195 // Check for overflow. This must be done with ConstantRange arithmetic
3196 // because we could be called from within the ScalarEvolution overflow
3198 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3199 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3200 ConstantRange ExtMaxBECountRange =
3201 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3202 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3203 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3205 return ConservativeResult;
3207 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3208 EndRange.getSignedMin());
3209 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3210 EndRange.getSignedMax());
3211 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
3212 return ConservativeResult;
3213 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
3217 return ConservativeResult;
3220 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3221 // For a SCEVUnknown, ask ValueTracking.
3222 if (!U->getValue()->getType()->isIntegerTy() && !TD)
3223 return ConservativeResult;
3224 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3226 return ConservativeResult;
3227 return ConservativeResult.intersectWith(
3228 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
3229 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
3232 return ConservativeResult;
3235 /// createSCEV - We know that there is no SCEV for the specified value.
3236 /// Analyze the expression.
3238 const SCEV *ScalarEvolution::createSCEV(Value *V) {
3239 if (!isSCEVable(V->getType()))
3240 return getUnknown(V);
3242 unsigned Opcode = Instruction::UserOp1;
3243 if (Instruction *I = dyn_cast<Instruction>(V)) {
3244 Opcode = I->getOpcode();
3246 // Don't attempt to analyze instructions in blocks that aren't
3247 // reachable. Such instructions don't matter, and they aren't required
3248 // to obey basic rules for definitions dominating uses which this
3249 // analysis depends on.
3250 if (!DT->isReachableFromEntry(I->getParent()))
3251 return getUnknown(V);
3252 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3253 Opcode = CE->getOpcode();
3254 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3255 return getConstant(CI);
3256 else if (isa<ConstantPointerNull>(V))
3257 return getConstant(V->getType(), 0);
3258 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3259 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
3261 return getUnknown(V);
3263 Operator *U = cast<Operator>(V);
3265 case Instruction::Add:
3266 return getAddExpr(getSCEV(U->getOperand(0)),
3267 getSCEV(U->getOperand(1)));
3268 case Instruction::Mul:
3269 return getMulExpr(getSCEV(U->getOperand(0)),
3270 getSCEV(U->getOperand(1)));
3271 case Instruction::UDiv:
3272 return getUDivExpr(getSCEV(U->getOperand(0)),
3273 getSCEV(U->getOperand(1)));
3274 case Instruction::Sub:
3275 return getMinusSCEV(getSCEV(U->getOperand(0)),
3276 getSCEV(U->getOperand(1)));
3277 case Instruction::And:
3278 // For an expression like x&255 that merely masks off the high bits,
3279 // use zext(trunc(x)) as the SCEV expression.
3280 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3281 if (CI->isNullValue())
3282 return getSCEV(U->getOperand(1));
3283 if (CI->isAllOnesValue())
3284 return getSCEV(U->getOperand(0));
3285 const APInt &A = CI->getValue();
3287 // Instcombine's ShrinkDemandedConstant may strip bits out of
3288 // constants, obscuring what would otherwise be a low-bits mask.
3289 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3290 // knew about to reconstruct a low-bits mask value.
3291 unsigned LZ = A.countLeadingZeros();
3292 unsigned BitWidth = A.getBitWidth();
3293 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3294 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3295 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3297 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3299 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
3301 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
3302 IntegerType::get(getContext(), BitWidth - LZ)),
3307 case Instruction::Or:
3308 // If the RHS of the Or is a constant, we may have something like:
3309 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3310 // optimizations will transparently handle this case.
3312 // In order for this transformation to be safe, the LHS must be of the
3313 // form X*(2^n) and the Or constant must be less than 2^n.
3314 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3315 const SCEV *LHS = getSCEV(U->getOperand(0));
3316 const APInt &CIVal = CI->getValue();
3317 if (GetMinTrailingZeros(LHS) >=
3318 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3319 // Build a plain add SCEV.
3320 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3321 // If the LHS of the add was an addrec and it has no-wrap flags,
3322 // transfer the no-wrap flags, since an or won't introduce a wrap.
3323 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3324 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3325 if (OldAR->hasNoUnsignedWrap())
3326 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3327 if (OldAR->hasNoSignedWrap())
3328 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3334 case Instruction::Xor:
3335 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
3336 // If the RHS of the xor is a signbit, then this is just an add.
3337 // Instcombine turns add of signbit into xor as a strength reduction step.
3338 if (CI->getValue().isSignBit())
3339 return getAddExpr(getSCEV(U->getOperand(0)),
3340 getSCEV(U->getOperand(1)));
3342 // If the RHS of xor is -1, then this is a not operation.
3343 if (CI->isAllOnesValue())
3344 return getNotSCEV(getSCEV(U->getOperand(0)));
3346 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3347 // This is a variant of the check for xor with -1, and it handles
3348 // the case where instcombine has trimmed non-demanded bits out
3349 // of an xor with -1.
3350 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3351 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3352 if (BO->getOpcode() == Instruction::And &&
3353 LCI->getValue() == CI->getValue())
3354 if (const SCEVZeroExtendExpr *Z =
3355 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
3356 const Type *UTy = U->getType();
3357 const SCEV *Z0 = Z->getOperand();
3358 const Type *Z0Ty = Z0->getType();
3359 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3361 // If C is a low-bits mask, the zero extend is serving to
3362 // mask off the high bits. Complement the operand and
3363 // re-apply the zext.
3364 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3365 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3367 // If C is a single bit, it may be in the sign-bit position
3368 // before the zero-extend. In this case, represent the xor
3369 // using an add, which is equivalent, and re-apply the zext.
3370 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3371 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3373 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3379 case Instruction::Shl:
3380 // Turn shift left of a constant amount into a multiply.
3381 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3382 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3384 // If the shift count is not less than the bitwidth, the result of
3385 // the shift is undefined. Don't try to analyze it, because the
3386 // resolution chosen here may differ from the resolution chosen in
3387 // other parts of the compiler.
3388 if (SA->getValue().uge(BitWidth))
3391 Constant *X = ConstantInt::get(getContext(),
3392 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3393 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3397 case Instruction::LShr:
3398 // Turn logical shift right of a constant into a unsigned divide.
3399 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3400 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
3402 // If the shift count is not less than the bitwidth, the result of
3403 // the shift is undefined. Don't try to analyze it, because the
3404 // resolution chosen here may differ from the resolution chosen in
3405 // other parts of the compiler.
3406 if (SA->getValue().uge(BitWidth))
3409 Constant *X = ConstantInt::get(getContext(),
3410 APInt(BitWidth, 1).shl(SA->getZExtValue()));
3411 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
3415 case Instruction::AShr:
3416 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3417 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3418 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
3419 if (L->getOpcode() == Instruction::Shl &&
3420 L->getOperand(1) == U->getOperand(1)) {
3421 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3423 // If the shift count is not less than the bitwidth, the result of
3424 // the shift is undefined. Don't try to analyze it, because the
3425 // resolution chosen here may differ from the resolution chosen in
3426 // other parts of the compiler.
3427 if (CI->getValue().uge(BitWidth))
3430 uint64_t Amt = BitWidth - CI->getZExtValue();
3431 if (Amt == BitWidth)
3432 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3434 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
3435 IntegerType::get(getContext(),
3441 case Instruction::Trunc:
3442 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
3444 case Instruction::ZExt:
3445 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3447 case Instruction::SExt:
3448 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
3450 case Instruction::BitCast:
3451 // BitCasts are no-op casts so we just eliminate the cast.
3452 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
3453 return getSCEV(U->getOperand(0));
3456 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3457 // lead to pointer expressions which cannot safely be expanded to GEPs,
3458 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3459 // simplifying integer expressions.
3461 case Instruction::GetElementPtr:
3462 return createNodeForGEP(cast<GEPOperator>(U));
3464 case Instruction::PHI:
3465 return createNodeForPHI(cast<PHINode>(U));
3467 case Instruction::Select:
3468 // This could be a smax or umax that was lowered earlier.
3469 // Try to recover it.
3470 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3471 Value *LHS = ICI->getOperand(0);
3472 Value *RHS = ICI->getOperand(1);
3473 switch (ICI->getPredicate()) {
3474 case ICmpInst::ICMP_SLT:
3475 case ICmpInst::ICMP_SLE:
3476 std::swap(LHS, RHS);
3478 case ICmpInst::ICMP_SGT:
3479 case ICmpInst::ICMP_SGE:
3480 // a >s b ? a+x : b+x -> smax(a, b)+x
3481 // a >s b ? b+x : a+x -> smin(a, b)+x
3482 if (LHS->getType() == U->getType()) {
3483 const SCEV *LS = getSCEV(LHS);
3484 const SCEV *RS = getSCEV(RHS);
3485 const SCEV *LA = getSCEV(U->getOperand(1));
3486 const SCEV *RA = getSCEV(U->getOperand(2));
3487 const SCEV *LDiff = getMinusSCEV(LA, LS);
3488 const SCEV *RDiff = getMinusSCEV(RA, RS);
3490 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3491 LDiff = getMinusSCEV(LA, RS);
3492 RDiff = getMinusSCEV(RA, LS);
3494 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3497 case ICmpInst::ICMP_ULT:
3498 case ICmpInst::ICMP_ULE:
3499 std::swap(LHS, RHS);
3501 case ICmpInst::ICMP_UGT:
3502 case ICmpInst::ICMP_UGE:
3503 // a >u b ? a+x : b+x -> umax(a, b)+x
3504 // a >u b ? b+x : a+x -> umin(a, b)+x
3505 if (LHS->getType() == U->getType()) {
3506 const SCEV *LS = getSCEV(LHS);
3507 const SCEV *RS = getSCEV(RHS);
3508 const SCEV *LA = getSCEV(U->getOperand(1));
3509 const SCEV *RA = getSCEV(U->getOperand(2));
3510 const SCEV *LDiff = getMinusSCEV(LA, LS);
3511 const SCEV *RDiff = getMinusSCEV(RA, RS);
3513 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3514 LDiff = getMinusSCEV(LA, RS);
3515 RDiff = getMinusSCEV(RA, LS);
3517 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3520 case ICmpInst::ICMP_NE:
3521 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3522 if (LHS->getType() == U->getType() &&
3523 isa<ConstantInt>(RHS) &&
3524 cast<ConstantInt>(RHS)->isZero()) {
3525 const SCEV *One = getConstant(LHS->getType(), 1);
3526 const SCEV *LS = getSCEV(LHS);
3527 const SCEV *LA = getSCEV(U->getOperand(1));
3528 const SCEV *RA = getSCEV(U->getOperand(2));
3529 const SCEV *LDiff = getMinusSCEV(LA, LS);
3530 const SCEV *RDiff = getMinusSCEV(RA, One);
3532 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3535 case ICmpInst::ICMP_EQ:
3536 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3537 if (LHS->getType() == U->getType() &&
3538 isa<ConstantInt>(RHS) &&
3539 cast<ConstantInt>(RHS)->isZero()) {
3540 const SCEV *One = getConstant(LHS->getType(), 1);
3541 const SCEV *LS = getSCEV(LHS);
3542 const SCEV *LA = getSCEV(U->getOperand(1));
3543 const SCEV *RA = getSCEV(U->getOperand(2));
3544 const SCEV *LDiff = getMinusSCEV(LA, One);
3545 const SCEV *RDiff = getMinusSCEV(RA, LS);
3547 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3555 default: // We cannot analyze this expression.
3559 return getUnknown(V);
3564 //===----------------------------------------------------------------------===//
3565 // Iteration Count Computation Code
3568 /// getBackedgeTakenCount - If the specified loop has a predictable
3569 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3570 /// object. The backedge-taken count is the number of times the loop header
3571 /// will be branched to from within the loop. This is one less than the
3572 /// trip count of the loop, since it doesn't count the first iteration,
3573 /// when the header is branched to from outside the loop.
3575 /// Note that it is not valid to call this method on a loop without a
3576 /// loop-invariant backedge-taken count (see
3577 /// hasLoopInvariantBackedgeTakenCount).
3579 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
3580 return getBackedgeTakenInfo(L).Exact;
3583 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3584 /// return the least SCEV value that is known never to be less than the
3585 /// actual backedge taken count.
3586 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
3587 return getBackedgeTakenInfo(L).Max;
3590 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
3591 /// onto the given Worklist.
3593 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3594 BasicBlock *Header = L->getHeader();
3596 // Push all Loop-header PHIs onto the Worklist stack.
3597 for (BasicBlock::iterator I = Header->begin();
3598 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3599 Worklist.push_back(PN);
3602 const ScalarEvolution::BackedgeTakenInfo &
3603 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
3604 // Initially insert a CouldNotCompute for this loop. If the insertion
3605 // succeeds, proceed to actually compute a backedge-taken count and
3606 // update the value. The temporary CouldNotCompute value tells SCEV
3607 // code elsewhere that it shouldn't attempt to request a new
3608 // backedge-taken count, which could result in infinite recursion.
3609 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
3610 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3612 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3613 if (BECount.Exact != getCouldNotCompute()) {
3614 assert(BECount.Exact->isLoopInvariant(L) &&
3615 BECount.Max->isLoopInvariant(L) &&
3616 "Computed backedge-taken count isn't loop invariant for loop!");
3617 ++NumTripCountsComputed;
3619 // Update the value in the map.
3620 Pair.first->second = BECount;
3622 if (BECount.Max != getCouldNotCompute())
3623 // Update the value in the map.
3624 Pair.first->second = BECount;
3625 if (isa<PHINode>(L->getHeader()->begin()))
3626 // Only count loops that have phi nodes as not being computable.
3627 ++NumTripCountsNotComputed;
3630 // Now that we know more about the trip count for this loop, forget any
3631 // existing SCEV values for PHI nodes in this loop since they are only
3632 // conservative estimates made without the benefit of trip count
3633 // information. This is similar to the code in forgetLoop, except that
3634 // it handles SCEVUnknown PHI nodes specially.
3635 if (BECount.hasAnyInfo()) {
3636 SmallVector<Instruction *, 16> Worklist;
3637 PushLoopPHIs(L, Worklist);
3639 SmallPtrSet<Instruction *, 8> Visited;
3640 while (!Worklist.empty()) {
3641 Instruction *I = Worklist.pop_back_val();
3642 if (!Visited.insert(I)) continue;
3644 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3645 Scalars.find(static_cast<Value *>(I));
3646 if (It != Scalars.end()) {
3647 // SCEVUnknown for a PHI either means that it has an unrecognized
3648 // structure, or it's a PHI that's in the progress of being computed
3649 // by createNodeForPHI. In the former case, additional loop trip
3650 // count information isn't going to change anything. In the later
3651 // case, createNodeForPHI will perform the necessary updates on its
3652 // own when it gets to that point.
3653 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3654 ValuesAtScopes.erase(It->second);
3657 if (PHINode *PN = dyn_cast<PHINode>(I))
3658 ConstantEvolutionLoopExitValue.erase(PN);
3661 PushDefUseChildren(I, Worklist);
3665 return Pair.first->second;
3668 /// forgetLoop - This method should be called by the client when it has
3669 /// changed a loop in a way that may effect ScalarEvolution's ability to
3670 /// compute a trip count, or if the loop is deleted.
3671 void ScalarEvolution::forgetLoop(const Loop *L) {
3672 // Drop any stored trip count value.
3673 BackedgeTakenCounts.erase(L);
3675 // Drop information about expressions based on loop-header PHIs.
3676 SmallVector<Instruction *, 16> Worklist;
3677 PushLoopPHIs(L, Worklist);
3679 SmallPtrSet<Instruction *, 8> Visited;
3680 while (!Worklist.empty()) {
3681 Instruction *I = Worklist.pop_back_val();
3682 if (!Visited.insert(I)) continue;
3684 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3685 Scalars.find(static_cast<Value *>(I));
3686 if (It != Scalars.end()) {
3687 ValuesAtScopes.erase(It->second);
3689 if (PHINode *PN = dyn_cast<PHINode>(I))
3690 ConstantEvolutionLoopExitValue.erase(PN);
3693 PushDefUseChildren(I, Worklist);
3697 /// forgetValue - This method should be called by the client when it has
3698 /// changed a value in a way that may effect its value, or which may
3699 /// disconnect it from a def-use chain linking it to a loop.
3700 void ScalarEvolution::forgetValue(Value *V) {
3701 Instruction *I = dyn_cast<Instruction>(V);
3704 // Drop information about expressions based on loop-header PHIs.
3705 SmallVector<Instruction *, 16> Worklist;
3706 Worklist.push_back(I);
3708 SmallPtrSet<Instruction *, 8> Visited;
3709 while (!Worklist.empty()) {
3710 I = Worklist.pop_back_val();
3711 if (!Visited.insert(I)) continue;
3713 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3714 Scalars.find(static_cast<Value *>(I));
3715 if (It != Scalars.end()) {
3716 ValuesAtScopes.erase(It->second);
3718 if (PHINode *PN = dyn_cast<PHINode>(I))
3719 ConstantEvolutionLoopExitValue.erase(PN);
3722 PushDefUseChildren(I, Worklist);
3726 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
3727 /// of the specified loop will execute.
3728 ScalarEvolution::BackedgeTakenInfo
3729 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
3730 SmallVector<BasicBlock *, 8> ExitingBlocks;
3731 L->getExitingBlocks(ExitingBlocks);
3733 // Examine all exits and pick the most conservative values.
3734 const SCEV *BECount = getCouldNotCompute();
3735 const SCEV *MaxBECount = getCouldNotCompute();
3736 bool CouldNotComputeBECount = false;
3737 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3738 BackedgeTakenInfo NewBTI =
3739 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
3741 if (NewBTI.Exact == getCouldNotCompute()) {
3742 // We couldn't compute an exact value for this exit, so
3743 // we won't be able to compute an exact value for the loop.
3744 CouldNotComputeBECount = true;
3745 BECount = getCouldNotCompute();
3746 } else if (!CouldNotComputeBECount) {
3747 if (BECount == getCouldNotCompute())
3748 BECount = NewBTI.Exact;
3750 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
3752 if (MaxBECount == getCouldNotCompute())
3753 MaxBECount = NewBTI.Max;
3754 else if (NewBTI.Max != getCouldNotCompute())
3755 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
3758 return BackedgeTakenInfo(BECount, MaxBECount);
3761 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3762 /// of the specified loop will execute if it exits via the specified block.
3763 ScalarEvolution::BackedgeTakenInfo
3764 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3765 BasicBlock *ExitingBlock) {
3767 // Okay, we've chosen an exiting block. See what condition causes us to
3768 // exit at this block.
3770 // FIXME: we should be able to handle switch instructions (with a single exit)
3771 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
3772 if (ExitBr == 0) return getCouldNotCompute();
3773 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
3775 // At this point, we know we have a conditional branch that determines whether
3776 // the loop is exited. However, we don't know if the branch is executed each
3777 // time through the loop. If not, then the execution count of the branch will
3778 // not be equal to the trip count of the loop.
3780 // Currently we check for this by checking to see if the Exit branch goes to
3781 // the loop header. If so, we know it will always execute the same number of
3782 // times as the loop. We also handle the case where the exit block *is* the
3783 // loop header. This is common for un-rotated loops.
3785 // If both of those tests fail, walk up the unique predecessor chain to the
3786 // header, stopping if there is an edge that doesn't exit the loop. If the
3787 // header is reached, the execution count of the branch will be equal to the
3788 // trip count of the loop.
3790 // More extensive analysis could be done to handle more cases here.
3792 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3793 ExitBr->getSuccessor(1) != L->getHeader() &&
3794 ExitBr->getParent() != L->getHeader()) {
3795 // The simple checks failed, try climbing the unique predecessor chain
3796 // up to the header.
3798 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3799 BasicBlock *Pred = BB->getUniquePredecessor();
3801 return getCouldNotCompute();
3802 TerminatorInst *PredTerm = Pred->getTerminator();
3803 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3804 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3807 // If the predecessor has a successor that isn't BB and isn't
3808 // outside the loop, assume the worst.
3809 if (L->contains(PredSucc))
3810 return getCouldNotCompute();
3812 if (Pred == L->getHeader()) {
3819 return getCouldNotCompute();
3822 // Proceed to the next level to examine the exit condition expression.
3823 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3824 ExitBr->getSuccessor(0),
3825 ExitBr->getSuccessor(1));
3828 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3829 /// backedge of the specified loop will execute if its exit condition
3830 /// were a conditional branch of ExitCond, TBB, and FBB.
3831 ScalarEvolution::BackedgeTakenInfo
3832 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3836 // Check if the controlling expression for this loop is an And or Or.
3837 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3838 if (BO->getOpcode() == Instruction::And) {
3839 // Recurse on the operands of the and.
3840 BackedgeTakenInfo BTI0 =
3841 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3842 BackedgeTakenInfo BTI1 =
3843 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3844 const SCEV *BECount = getCouldNotCompute();
3845 const SCEV *MaxBECount = getCouldNotCompute();
3846 if (L->contains(TBB)) {
3847 // Both conditions must be true for the loop to continue executing.
3848 // Choose the less conservative count.
3849 if (BTI0.Exact == getCouldNotCompute() ||
3850 BTI1.Exact == getCouldNotCompute())
3851 BECount = getCouldNotCompute();
3853 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3854 if (BTI0.Max == getCouldNotCompute())
3855 MaxBECount = BTI1.Max;
3856 else if (BTI1.Max == getCouldNotCompute())
3857 MaxBECount = BTI0.Max;
3859 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3861 // Both conditions must be true at the same time for the loop to exit.
3862 // For now, be conservative.
3863 assert(L->contains(FBB) && "Loop block has no successor in loop!");
3864 if (BTI0.Max == BTI1.Max)
3865 MaxBECount = BTI0.Max;
3866 if (BTI0.Exact == BTI1.Exact)
3867 BECount = BTI0.Exact;
3870 return BackedgeTakenInfo(BECount, MaxBECount);
3872 if (BO->getOpcode() == Instruction::Or) {
3873 // Recurse on the operands of the or.
3874 BackedgeTakenInfo BTI0 =
3875 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3876 BackedgeTakenInfo BTI1 =
3877 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
3878 const SCEV *BECount = getCouldNotCompute();
3879 const SCEV *MaxBECount = getCouldNotCompute();
3880 if (L->contains(FBB)) {
3881 // Both conditions must be false for the loop to continue executing.
3882 // Choose the less conservative count.
3883 if (BTI0.Exact == getCouldNotCompute() ||
3884 BTI1.Exact == getCouldNotCompute())
3885 BECount = getCouldNotCompute();
3887 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
3888 if (BTI0.Max == getCouldNotCompute())
3889 MaxBECount = BTI1.Max;
3890 else if (BTI1.Max == getCouldNotCompute())
3891 MaxBECount = BTI0.Max;
3893 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
3895 // Both conditions must be false at the same time for the loop to exit.
3896 // For now, be conservative.
3897 assert(L->contains(TBB) && "Loop block has no successor in loop!");
3898 if (BTI0.Max == BTI1.Max)
3899 MaxBECount = BTI0.Max;
3900 if (BTI0.Exact == BTI1.Exact)
3901 BECount = BTI0.Exact;
3904 return BackedgeTakenInfo(BECount, MaxBECount);
3908 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3909 // Proceed to the next level to examine the icmp.
3910 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3911 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
3913 // Check for a constant condition. These are normally stripped out by
3914 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3915 // preserve the CFG and is temporarily leaving constant conditions
3917 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3918 if (L->contains(FBB) == !CI->getZExtValue())
3919 // The backedge is always taken.
3920 return getCouldNotCompute();
3922 // The backedge is never taken.
3923 return getConstant(CI->getType(), 0);
3926 // If it's not an integer or pointer comparison then compute it the hard way.
3927 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3930 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3931 /// backedge of the specified loop will execute if its exit condition
3932 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3933 ScalarEvolution::BackedgeTakenInfo
3934 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3939 // If the condition was exit on true, convert the condition to exit on false
3940 ICmpInst::Predicate Cond;
3941 if (!L->contains(FBB))
3942 Cond = ExitCond->getPredicate();
3944 Cond = ExitCond->getInversePredicate();
3946 // Handle common loops like: for (X = "string"; *X; ++X)
3947 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3948 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3949 BackedgeTakenInfo ItCnt =
3950 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
3951 if (ItCnt.hasAnyInfo())
3955 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3956 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
3958 // Try to evaluate any dependencies out of the loop.
3959 LHS = getSCEVAtScope(LHS, L);
3960 RHS = getSCEVAtScope(RHS, L);
3962 // At this point, we would like to compute how many iterations of the
3963 // loop the predicate will return true for these inputs.
3964 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3965 // If there is a loop-invariant, force it into the RHS.
3966 std::swap(LHS, RHS);
3967 Cond = ICmpInst::getSwappedPredicate(Cond);
3970 // Simplify the operands before analyzing them.
3971 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3973 // If we have a comparison of a chrec against a constant, try to use value
3974 // ranges to answer this query.
3975 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3976 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
3977 if (AddRec->getLoop() == L) {
3978 // Form the constant range.
3979 ConstantRange CompRange(
3980 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
3982 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3983 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
3987 case ICmpInst::ICMP_NE: { // while (X != Y)
3988 // Convert to: while (X-Y != 0)
3989 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3990 if (BTI.hasAnyInfo()) return BTI;
3993 case ICmpInst::ICMP_EQ: { // while (X == Y)
3994 // Convert to: while (X-Y == 0)
3995 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3996 if (BTI.hasAnyInfo()) return BTI;
3999 case ICmpInst::ICMP_SLT: {
4000 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4001 if (BTI.hasAnyInfo()) return BTI;
4004 case ICmpInst::ICMP_SGT: {
4005 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4006 getNotSCEV(RHS), L, true);
4007 if (BTI.hasAnyInfo()) return BTI;
4010 case ICmpInst::ICMP_ULT: {
4011 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4012 if (BTI.hasAnyInfo()) return BTI;
4015 case ICmpInst::ICMP_UGT: {
4016 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4017 getNotSCEV(RHS), L, false);
4018 if (BTI.hasAnyInfo()) return BTI;
4023 dbgs() << "ComputeBackedgeTakenCount ";
4024 if (ExitCond->getOperand(0)->getType()->isUnsigned())
4025 dbgs() << "[unsigned] ";
4026 dbgs() << *LHS << " "
4027 << Instruction::getOpcodeName(Instruction::ICmp)
4028 << " " << *RHS << "\n";
4033 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
4036 static ConstantInt *
4037 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4038 ScalarEvolution &SE) {
4039 const SCEV *InVal = SE.getConstant(C);
4040 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
4041 assert(isa<SCEVConstant>(Val) &&
4042 "Evaluation of SCEV at constant didn't fold correctly?");
4043 return cast<SCEVConstant>(Val)->getValue();
4046 /// GetAddressedElementFromGlobal - Given a global variable with an initializer
4047 /// and a GEP expression (missing the pointer index) indexing into it, return
4048 /// the addressed element of the initializer or null if the index expression is
4051 GetAddressedElementFromGlobal(GlobalVariable *GV,
4052 const std::vector<ConstantInt*> &Indices) {
4053 Constant *Init = GV->getInitializer();
4054 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
4055 uint64_t Idx = Indices[i]->getZExtValue();
4056 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4057 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4058 Init = cast<Constant>(CS->getOperand(Idx));
4059 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4060 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4061 Init = cast<Constant>(CA->getOperand(Idx));
4062 } else if (isa<ConstantAggregateZero>(Init)) {
4063 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4064 assert(Idx < STy->getNumElements() && "Bad struct index!");
4065 Init = Constant::getNullValue(STy->getElementType(Idx));
4066 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4067 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
4068 Init = Constant::getNullValue(ATy->getElementType());
4070 llvm_unreachable("Unknown constant aggregate type!");
4074 return 0; // Unknown initializer type
4080 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4081 /// 'icmp op load X, cst', try to see if we can compute the backedge
4082 /// execution count.
4083 ScalarEvolution::BackedgeTakenInfo
4084 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4088 ICmpInst::Predicate predicate) {
4089 if (LI->isVolatile()) return getCouldNotCompute();
4091 // Check to see if the loaded pointer is a getelementptr of a global.
4092 // TODO: Use SCEV instead of manually grubbing with GEPs.
4093 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
4094 if (!GEP) return getCouldNotCompute();
4096 // Make sure that it is really a constant global we are gepping, with an
4097 // initializer, and make sure the first IDX is really 0.
4098 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
4099 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
4100 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4101 !cast<Constant>(GEP->getOperand(1))->isNullValue())
4102 return getCouldNotCompute();
4104 // Okay, we allow one non-constant index into the GEP instruction.
4106 std::vector<ConstantInt*> Indexes;
4107 unsigned VarIdxNum = 0;
4108 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4109 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4110 Indexes.push_back(CI);
4111 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
4112 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
4113 VarIdx = GEP->getOperand(i);
4115 Indexes.push_back(0);
4118 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4119 // Check to see if X is a loop variant variable value now.
4120 const SCEV *Idx = getSCEV(VarIdx);
4121 Idx = getSCEVAtScope(Idx, L);
4123 // We can only recognize very limited forms of loop index expressions, in
4124 // particular, only affine AddRec's like {C1,+,C2}.
4125 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
4126 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4127 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4128 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
4129 return getCouldNotCompute();
4131 unsigned MaxSteps = MaxBruteForceIterations;
4132 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
4133 ConstantInt *ItCst = ConstantInt::get(
4134 cast<IntegerType>(IdxExpr->getType()), IterationNum);
4135 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
4137 // Form the GEP offset.
4138 Indexes[VarIdxNum] = Val;
4140 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
4141 if (Result == 0) break; // Cannot compute!
4143 // Evaluate the condition for this iteration.
4144 Result = ConstantExpr::getICmp(predicate, Result, RHS);
4145 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
4146 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
4148 dbgs() << "\n***\n*** Computed loop count " << *ItCst
4149 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4152 ++NumArrayLenItCounts;
4153 return getConstant(ItCst); // Found terminating iteration!
4156 return getCouldNotCompute();
4160 /// CanConstantFold - Return true if we can constant fold an instruction of the
4161 /// specified type, assuming that all operands were constants.
4162 static bool CanConstantFold(const Instruction *I) {
4163 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
4164 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4167 if (const CallInst *CI = dyn_cast<CallInst>(I))
4168 if (const Function *F = CI->getCalledFunction())
4169 return canConstantFoldCallTo(F);
4173 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4174 /// in the loop that V is derived from. We allow arbitrary operations along the
4175 /// way, but the operands of an operation must either be constants or a value
4176 /// derived from a constant PHI. If this expression does not fit with these
4177 /// constraints, return null.
4178 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4179 // If this is not an instruction, or if this is an instruction outside of the
4180 // loop, it can't be derived from a loop PHI.
4181 Instruction *I = dyn_cast<Instruction>(V);
4182 if (I == 0 || !L->contains(I)) return 0;
4184 if (PHINode *PN = dyn_cast<PHINode>(I)) {
4185 if (L->getHeader() == I->getParent())
4188 // We don't currently keep track of the control flow needed to evaluate
4189 // PHIs, so we cannot handle PHIs inside of loops.
4193 // If we won't be able to constant fold this expression even if the operands
4194 // are constants, return early.
4195 if (!CanConstantFold(I)) return 0;
4197 // Otherwise, we can evaluate this instruction if all of its operands are
4198 // constant or derived from a PHI node themselves.
4200 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4201 if (!isa<Constant>(I->getOperand(Op))) {
4202 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4203 if (P == 0) return 0; // Not evolving from PHI
4207 return 0; // Evolving from multiple different PHIs.
4210 // This is a expression evolving from a constant PHI!
4214 /// EvaluateExpression - Given an expression that passes the
4215 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4216 /// in the loop has the value PHIVal. If we can't fold this expression for some
4217 /// reason, return null.
4218 static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4219 const TargetData *TD) {
4220 if (isa<PHINode>(V)) return PHIVal;
4221 if (Constant *C = dyn_cast<Constant>(V)) return C;
4222 Instruction *I = cast<Instruction>(V);
4224 std::vector<Constant*> Operands(I->getNumOperands());
4226 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4227 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
4228 if (Operands[i] == 0) return 0;
4231 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4232 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
4234 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4235 &Operands[0], Operands.size(), TD);
4238 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4239 /// in the header of its containing loop, we know the loop executes a
4240 /// constant number of times, and the PHI node is just a recurrence
4241 /// involving constants, fold it.
4243 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
4246 std::map<PHINode*, Constant*>::iterator I =
4247 ConstantEvolutionLoopExitValue.find(PN);
4248 if (I != ConstantEvolutionLoopExitValue.end())
4251 if (BEs.ugt(MaxBruteForceIterations))
4252 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4254 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4256 // Since the loop is canonicalized, the PHI node must have two entries. One
4257 // entry must be a constant (coming in from outside of the loop), and the
4258 // second must be derived from the same PHI.
4259 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4260 Constant *StartCST =
4261 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4263 return RetVal = 0; // Must be a constant.
4265 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4266 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4267 !isa<Constant>(BEValue))
4268 return RetVal = 0; // Not derived from same PHI.
4270 // Execute the loop symbolically to determine the exit value.
4271 if (BEs.getActiveBits() >= 32)
4272 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
4274 unsigned NumIterations = BEs.getZExtValue(); // must be in range
4275 unsigned IterationNum = 0;
4276 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4277 if (IterationNum == NumIterations)
4278 return RetVal = PHIVal; // Got exit value!
4280 // Compute the value of the PHI node for the next iteration.
4281 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4282 if (NextPHI == PHIVal)
4283 return RetVal = NextPHI; // Stopped evolving!
4285 return 0; // Couldn't evaluate!
4290 /// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
4291 /// constant number of times (the condition evolves only from constants),
4292 /// try to evaluate a few iterations of the loop until we get the exit
4293 /// condition gets a value of ExitWhen (true or false). If we cannot
4294 /// evaluate the trip count of the loop, return getCouldNotCompute().
4296 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4299 PHINode *PN = getConstantEvolvingPHI(Cond, L);
4300 if (PN == 0) return getCouldNotCompute();
4302 // If the loop is canonicalized, the PHI will have exactly two entries.
4303 // That's the only form we support here.
4304 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4306 // One entry must be a constant (coming in from outside of the loop), and the
4307 // second must be derived from the same PHI.
4308 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4309 Constant *StartCST =
4310 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4311 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
4313 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4314 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4315 !isa<Constant>(BEValue))
4316 return getCouldNotCompute(); // Not derived from same PHI.
4318 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4319 // the loop symbolically to determine when the condition gets a value of
4321 unsigned IterationNum = 0;
4322 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4323 for (Constant *PHIVal = StartCST;
4324 IterationNum != MaxIterations; ++IterationNum) {
4325 ConstantInt *CondVal =
4326 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
4328 // Couldn't symbolically evaluate.
4329 if (!CondVal) return getCouldNotCompute();
4331 if (CondVal->getValue() == uint64_t(ExitWhen)) {
4332 ++NumBruteForceTripCountsComputed;
4333 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
4336 // Compute the value of the PHI node for the next iteration.
4337 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
4338 if (NextPHI == 0 || NextPHI == PHIVal)
4339 return getCouldNotCompute();// Couldn't evaluate or not making progress...
4343 // Too many iterations were needed to evaluate.
4344 return getCouldNotCompute();
4347 /// getSCEVAtScope - Return a SCEV expression for the specified value
4348 /// at the specified scope in the program. The L value specifies a loop
4349 /// nest to evaluate the expression at, where null is the top-level or a
4350 /// specified loop is immediately inside of the loop.
4352 /// This method can be used to compute the exit value for a variable defined
4353 /// in a loop by querying what the value will hold in the parent loop.
4355 /// In the case that a relevant loop exit value cannot be computed, the
4356 /// original value V is returned.
4357 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
4358 // Check to see if we've folded this expression at this loop before.
4359 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4360 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4361 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4363 return Pair.first->second ? Pair.first->second : V;
4365 // Otherwise compute it.
4366 const SCEV *C = computeSCEVAtScope(V, L);
4367 ValuesAtScopes[V][L] = C;
4371 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
4372 if (isa<SCEVConstant>(V)) return V;
4374 // If this instruction is evolved from a constant-evolving PHI, compute the
4375 // exit value from the loop without using SCEVs.
4376 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
4377 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
4378 const Loop *LI = (*this->LI)[I->getParent()];
4379 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4380 if (PHINode *PN = dyn_cast<PHINode>(I))
4381 if (PN->getParent() == LI->getHeader()) {
4382 // Okay, there is no closed form solution for the PHI node. Check
4383 // to see if the loop that contains it has a known backedge-taken
4384 // count. If so, we may be able to force computation of the exit
4386 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
4387 if (const SCEVConstant *BTCC =
4388 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
4389 // Okay, we know how many times the containing loop executes. If
4390 // this is a constant evolving PHI node, get the final value at
4391 // the specified iteration number.
4392 Constant *RV = getConstantEvolutionLoopExitValue(PN,
4393 BTCC->getValue()->getValue(),
4395 if (RV) return getSCEV(RV);
4399 // Okay, this is an expression that we cannot symbolically evaluate
4400 // into a SCEV. Check to see if it's possible to symbolically evaluate
4401 // the arguments into constants, and if so, try to constant propagate the
4402 // result. This is particularly useful for computing loop exit values.
4403 if (CanConstantFold(I)) {
4404 SmallVector<Constant *, 4> Operands;
4405 bool MadeImprovement = false;
4406 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4407 Value *Op = I->getOperand(i);
4408 if (Constant *C = dyn_cast<Constant>(Op)) {
4409 Operands.push_back(C);
4413 // If any of the operands is non-constant and if they are
4414 // non-integer and non-pointer, don't even try to analyze them
4415 // with scev techniques.
4416 if (!isSCEVable(Op->getType()))
4419 const SCEV *OrigV = getSCEV(Op);
4420 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4421 MadeImprovement |= OrigV != OpV;
4424 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4426 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4427 C = dyn_cast<Constant>(SU->getValue());
4429 if (C->getType() != Op->getType())
4430 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4434 Operands.push_back(C);
4437 // Check to see if getSCEVAtScope actually made an improvement.
4438 if (MadeImprovement) {
4440 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4441 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4442 Operands[0], Operands[1], TD);
4444 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4445 &Operands[0], Operands.size(), TD);
4452 // This is some other type of SCEVUnknown, just return it.
4456 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
4457 // Avoid performing the look-up in the common case where the specified
4458 // expression has no loop-variant portions.
4459 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
4460 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4461 if (OpAtScope != Comm->getOperand(i)) {
4462 // Okay, at least one of these operands is loop variant but might be
4463 // foldable. Build a new instance of the folded commutative expression.
4464 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4465 Comm->op_begin()+i);
4466 NewOps.push_back(OpAtScope);
4468 for (++i; i != e; ++i) {
4469 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
4470 NewOps.push_back(OpAtScope);
4472 if (isa<SCEVAddExpr>(Comm))
4473 return getAddExpr(NewOps);
4474 if (isa<SCEVMulExpr>(Comm))
4475 return getMulExpr(NewOps);
4476 if (isa<SCEVSMaxExpr>(Comm))
4477 return getSMaxExpr(NewOps);
4478 if (isa<SCEVUMaxExpr>(Comm))
4479 return getUMaxExpr(NewOps);
4480 llvm_unreachable("Unknown commutative SCEV type!");
4483 // If we got here, all operands are loop invariant.
4487 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
4488 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4489 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
4490 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4491 return Div; // must be loop invariant
4492 return getUDivExpr(LHS, RHS);
4495 // If this is a loop recurrence for a loop that does not contain L, then we
4496 // are dealing with the final value computed by the loop.
4497 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4498 // First, attempt to evaluate each operand.
4499 // Avoid performing the look-up in the common case where the specified
4500 // expression has no loop-variant portions.
4501 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4502 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4503 if (OpAtScope == AddRec->getOperand(i))
4506 // Okay, at least one of these operands is loop variant but might be
4507 // foldable. Build a new instance of the folded commutative expression.
4508 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4509 AddRec->op_begin()+i);
4510 NewOps.push_back(OpAtScope);
4511 for (++i; i != e; ++i)
4512 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4514 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4518 // If the scope is outside the addrec's loop, evaluate it by using the
4519 // loop exit value of the addrec.
4520 if (!AddRec->getLoop()->contains(L)) {
4521 // To evaluate this recurrence, we need to know how many times the AddRec
4522 // loop iterates. Compute this now.
4523 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
4524 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
4526 // Then, evaluate the AddRec.
4527 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
4533 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
4534 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4535 if (Op == Cast->getOperand())
4536 return Cast; // must be loop invariant
4537 return getZeroExtendExpr(Op, Cast->getType());
4540 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
4541 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4542 if (Op == Cast->getOperand())
4543 return Cast; // must be loop invariant
4544 return getSignExtendExpr(Op, Cast->getType());
4547 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
4548 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
4549 if (Op == Cast->getOperand())
4550 return Cast; // must be loop invariant
4551 return getTruncateExpr(Op, Cast->getType());
4554 llvm_unreachable("Unknown SCEV type!");
4558 /// getSCEVAtScope - This is a convenience function which does
4559 /// getSCEVAtScope(getSCEV(V), L).
4560 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
4561 return getSCEVAtScope(getSCEV(V), L);
4564 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4565 /// following equation:
4567 /// A * X = B (mod N)
4569 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4570 /// A and B isn't important.
4572 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
4573 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
4574 ScalarEvolution &SE) {
4575 uint32_t BW = A.getBitWidth();
4576 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4577 assert(A != 0 && "A must be non-zero.");
4581 // The gcd of A and N may have only one prime factor: 2. The number of
4582 // trailing zeros in A is its multiplicity
4583 uint32_t Mult2 = A.countTrailingZeros();
4586 // 2. Check if B is divisible by D.
4588 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4589 // is not less than multiplicity of this prime factor for D.
4590 if (B.countTrailingZeros() < Mult2)
4591 return SE.getCouldNotCompute();
4593 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4596 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4597 // bit width during computations.
4598 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4599 APInt Mod(BW + 1, 0);
4600 Mod.set(BW - Mult2); // Mod = N / D
4601 APInt I = AD.multiplicativeInverse(Mod);
4603 // 4. Compute the minimum unsigned root of the equation:
4604 // I * (B / D) mod (N / D)
4605 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4607 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4609 return SE.getConstant(Result.trunc(BW));
4612 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4613 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4614 /// might be the same) or two SCEVCouldNotCompute objects.
4616 static std::pair<const SCEV *,const SCEV *>
4617 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
4618 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
4619 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4620 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4621 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
4623 // We currently can only solve this if the coefficients are constants.
4624 if (!LC || !MC || !NC) {
4625 const SCEV *CNC = SE.getCouldNotCompute();
4626 return std::make_pair(CNC, CNC);
4629 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4630 const APInt &L = LC->getValue()->getValue();
4631 const APInt &M = MC->getValue()->getValue();
4632 const APInt &N = NC->getValue()->getValue();
4633 APInt Two(BitWidth, 2);
4634 APInt Four(BitWidth, 4);
4637 using namespace APIntOps;
4639 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4640 // The B coefficient is M-N/2
4644 // The A coefficient is N/2
4645 APInt A(N.sdiv(Two));
4647 // Compute the B^2-4ac term.
4650 SqrtTerm -= Four * (A * C);
4652 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4653 // integer value or else APInt::sqrt() will assert.
4654 APInt SqrtVal(SqrtTerm.sqrt());
4656 // Compute the two solutions for the quadratic formula.
4657 // The divisions must be performed as signed divisions.
4659 APInt TwoA( A << 1 );
4660 if (TwoA.isMinValue()) {
4661 const SCEV *CNC = SE.getCouldNotCompute();
4662 return std::make_pair(CNC, CNC);
4665 LLVMContext &Context = SE.getContext();
4667 ConstantInt *Solution1 =
4668 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
4669 ConstantInt *Solution2 =
4670 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
4672 return std::make_pair(SE.getConstant(Solution1),
4673 SE.getConstant(Solution2));
4674 } // end APIntOps namespace
4677 /// HowFarToZero - Return the number of times a backedge comparing the specified
4678 /// value to zero will execute. If not computable, return CouldNotCompute.
4679 ScalarEvolution::BackedgeTakenInfo
4680 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
4681 // If the value is a constant
4682 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4683 // If the value is already zero, the branch will execute zero times.
4684 if (C->getValue()->isZero()) return C;
4685 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4688 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
4689 if (!AddRec || AddRec->getLoop() != L)
4690 return getCouldNotCompute();
4692 if (AddRec->isAffine()) {
4693 // If this is an affine expression, the execution count of this branch is
4694 // the minimum unsigned root of the following equation:
4696 // Start + Step*N = 0 (mod 2^BW)
4700 // Step*N = -Start (mod 2^BW)
4702 // where BW is the common bit width of Start and Step.
4704 // Get the initial value for the loop.
4705 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4706 L->getParentLoop());
4707 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4708 L->getParentLoop());
4710 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
4711 // For now we handle only constant steps.
4713 // First, handle unitary steps.
4714 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
4715 return getNegativeSCEV(Start); // N = -Start (as unsigned)
4716 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4717 return Start; // N = Start (as unsigned)
4719 // Then, try to solve the above equation provided that Start is constant.
4720 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
4721 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
4722 -StartC->getValue()->getValue(),
4725 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
4726 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4727 // the quadratic equation to solve it.
4728 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
4730 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4731 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
4734 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
4735 << " sol#2: " << *R2 << "\n";
4737 // Pick the smallest positive root value.
4738 if (ConstantInt *CB =
4739 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4740 R1->getValue(), R2->getValue()))) {
4741 if (CB->getZExtValue() == false)
4742 std::swap(R1, R2); // R1 is the minimum root now.
4744 // We can only use this value if the chrec ends up with an exact zero
4745 // value at this index. When solving for "X*X != 5", for example, we
4746 // should not accept a root of 2.
4747 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
4749 return R1; // We found a quadratic root!
4754 return getCouldNotCompute();
4757 /// HowFarToNonZero - Return the number of times a backedge checking the
4758 /// specified value for nonzero will execute. If not computable, return
4760 ScalarEvolution::BackedgeTakenInfo
4761 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
4762 // Loops that look like: while (X == 0) are very strange indeed. We don't
4763 // handle them yet except for the trivial case. This could be expanded in the
4764 // future as needed.
4766 // If the value is a constant, check to see if it is known to be non-zero
4767 // already. If so, the backedge will execute zero times.
4768 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
4769 if (!C->getValue()->isNullValue())
4770 return getConstant(C->getType(), 0);
4771 return getCouldNotCompute(); // Otherwise it will loop infinitely.
4774 // We could implement others, but I really doubt anyone writes loops like
4775 // this, and if they did, they would already be constant folded.
4776 return getCouldNotCompute();
4779 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4780 /// (which may not be an immediate predecessor) which has exactly one
4781 /// successor from which BB is reachable, or null if no such block is
4784 std::pair<BasicBlock *, BasicBlock *>
4785 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
4786 // If the block has a unique predecessor, then there is no path from the
4787 // predecessor to the block that does not go through the direct edge
4788 // from the predecessor to the block.
4789 if (BasicBlock *Pred = BB->getSinglePredecessor())
4790 return std::make_pair(Pred, BB);
4792 // A loop's header is defined to be a block that dominates the loop.
4793 // If the header has a unique predecessor outside the loop, it must be
4794 // a block that has exactly one successor that can reach the loop.
4795 if (Loop *L = LI->getLoopFor(BB))
4796 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
4798 return std::pair<BasicBlock *, BasicBlock *>();
4801 /// HasSameValue - SCEV structural equivalence is usually sufficient for
4802 /// testing whether two expressions are equal, however for the purposes of
4803 /// looking for a condition guarding a loop, it can be useful to be a little
4804 /// more general, since a front-end may have replicated the controlling
4807 static bool HasSameValue(const SCEV *A, const SCEV *B) {
4808 // Quick check to see if they are the same SCEV.
4809 if (A == B) return true;
4811 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4812 // two different instructions with the same value. Check for this case.
4813 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4814 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4815 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4816 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4817 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
4820 // Otherwise assume they may have a different value.
4824 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4825 /// predicate Pred. Return true iff any changes were made.
4827 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4828 const SCEV *&LHS, const SCEV *&RHS) {
4829 bool Changed = false;
4831 // Canonicalize a constant to the right side.
4832 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4833 // Check for both operands constant.
4834 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4835 if (ConstantExpr::getICmp(Pred,
4837 RHSC->getValue())->isNullValue())
4838 goto trivially_false;
4840 goto trivially_true;
4842 // Otherwise swap the operands to put the constant on the right.
4843 std::swap(LHS, RHS);
4844 Pred = ICmpInst::getSwappedPredicate(Pred);
4848 // If we're comparing an addrec with a value which is loop-invariant in the
4849 // addrec's loop, put the addrec on the left. Also make a dominance check,
4850 // as both operands could be addrecs loop-invariant in each other's loop.
4851 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4852 const Loop *L = AR->getLoop();
4853 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
4854 std::swap(LHS, RHS);
4855 Pred = ICmpInst::getSwappedPredicate(Pred);
4860 // If there's a constant operand, canonicalize comparisons with boundary
4861 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4862 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4863 const APInt &RA = RC->getValue()->getValue();
4865 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4866 case ICmpInst::ICMP_EQ:
4867 case ICmpInst::ICMP_NE:
4869 case ICmpInst::ICMP_UGE:
4870 if ((RA - 1).isMinValue()) {
4871 Pred = ICmpInst::ICMP_NE;
4872 RHS = getConstant(RA - 1);
4876 if (RA.isMaxValue()) {
4877 Pred = ICmpInst::ICMP_EQ;
4881 if (RA.isMinValue()) goto trivially_true;
4883 Pred = ICmpInst::ICMP_UGT;
4884 RHS = getConstant(RA - 1);
4887 case ICmpInst::ICMP_ULE:
4888 if ((RA + 1).isMaxValue()) {
4889 Pred = ICmpInst::ICMP_NE;
4890 RHS = getConstant(RA + 1);
4894 if (RA.isMinValue()) {
4895 Pred = ICmpInst::ICMP_EQ;
4899 if (RA.isMaxValue()) goto trivially_true;
4901 Pred = ICmpInst::ICMP_ULT;
4902 RHS = getConstant(RA + 1);
4905 case ICmpInst::ICMP_SGE:
4906 if ((RA - 1).isMinSignedValue()) {
4907 Pred = ICmpInst::ICMP_NE;
4908 RHS = getConstant(RA - 1);
4912 if (RA.isMaxSignedValue()) {
4913 Pred = ICmpInst::ICMP_EQ;
4917 if (RA.isMinSignedValue()) goto trivially_true;
4919 Pred = ICmpInst::ICMP_SGT;
4920 RHS = getConstant(RA - 1);
4923 case ICmpInst::ICMP_SLE:
4924 if ((RA + 1).isMaxSignedValue()) {
4925 Pred = ICmpInst::ICMP_NE;
4926 RHS = getConstant(RA + 1);
4930 if (RA.isMinSignedValue()) {
4931 Pred = ICmpInst::ICMP_EQ;
4935 if (RA.isMaxSignedValue()) goto trivially_true;
4937 Pred = ICmpInst::ICMP_SLT;
4938 RHS = getConstant(RA + 1);
4941 case ICmpInst::ICMP_UGT:
4942 if (RA.isMinValue()) {
4943 Pred = ICmpInst::ICMP_NE;
4947 if ((RA + 1).isMaxValue()) {
4948 Pred = ICmpInst::ICMP_EQ;
4949 RHS = getConstant(RA + 1);
4953 if (RA.isMaxValue()) goto trivially_false;
4955 case ICmpInst::ICMP_ULT:
4956 if (RA.isMaxValue()) {
4957 Pred = ICmpInst::ICMP_NE;
4961 if ((RA - 1).isMinValue()) {
4962 Pred = ICmpInst::ICMP_EQ;
4963 RHS = getConstant(RA - 1);
4967 if (RA.isMinValue()) goto trivially_false;
4969 case ICmpInst::ICMP_SGT:
4970 if (RA.isMinSignedValue()) {
4971 Pred = ICmpInst::ICMP_NE;
4975 if ((RA + 1).isMaxSignedValue()) {
4976 Pred = ICmpInst::ICMP_EQ;
4977 RHS = getConstant(RA + 1);
4981 if (RA.isMaxSignedValue()) goto trivially_false;
4983 case ICmpInst::ICMP_SLT:
4984 if (RA.isMaxSignedValue()) {
4985 Pred = ICmpInst::ICMP_NE;
4989 if ((RA - 1).isMinSignedValue()) {
4990 Pred = ICmpInst::ICMP_EQ;
4991 RHS = getConstant(RA - 1);
4995 if (RA.isMinSignedValue()) goto trivially_false;
5000 // Check for obvious equality.
5001 if (HasSameValue(LHS, RHS)) {
5002 if (ICmpInst::isTrueWhenEqual(Pred))
5003 goto trivially_true;
5004 if (ICmpInst::isFalseWhenEqual(Pred))
5005 goto trivially_false;
5008 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5009 // adding or subtracting 1 from one of the operands.
5011 case ICmpInst::ICMP_SLE:
5012 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5013 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5014 /*HasNUW=*/false, /*HasNSW=*/true);
5015 Pred = ICmpInst::ICMP_SLT;
5017 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
5018 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5019 /*HasNUW=*/false, /*HasNSW=*/true);
5020 Pred = ICmpInst::ICMP_SLT;
5024 case ICmpInst::ICMP_SGE:
5025 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
5026 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5027 /*HasNUW=*/false, /*HasNSW=*/true);
5028 Pred = ICmpInst::ICMP_SGT;
5030 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5031 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5032 /*HasNUW=*/false, /*HasNSW=*/true);
5033 Pred = ICmpInst::ICMP_SGT;
5037 case ICmpInst::ICMP_ULE:
5038 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
5039 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5040 /*HasNUW=*/true, /*HasNSW=*/false);
5041 Pred = ICmpInst::ICMP_ULT;
5043 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
5044 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
5045 /*HasNUW=*/true, /*HasNSW=*/false);
5046 Pred = ICmpInst::ICMP_ULT;
5050 case ICmpInst::ICMP_UGE:
5051 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
5052 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
5053 /*HasNUW=*/true, /*HasNSW=*/false);
5054 Pred = ICmpInst::ICMP_UGT;
5056 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
5057 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5058 /*HasNUW=*/true, /*HasNSW=*/false);
5059 Pred = ICmpInst::ICMP_UGT;
5067 // TODO: More simplifications are possible here.
5073 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5074 Pred = ICmpInst::ICMP_EQ;
5079 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5080 Pred = ICmpInst::ICMP_NE;
5084 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5085 return getSignedRange(S).getSignedMax().isNegative();
5088 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5089 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5092 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5093 return !getSignedRange(S).getSignedMin().isNegative();
5096 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5097 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5100 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5101 return isKnownNegative(S) || isKnownPositive(S);
5104 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5105 const SCEV *LHS, const SCEV *RHS) {
5106 // Canonicalize the inputs first.
5107 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5109 // If LHS or RHS is an addrec, check to see if the condition is true in
5110 // every iteration of the loop.
5111 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5112 if (isLoopEntryGuardedByCond(
5113 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5114 isLoopBackedgeGuardedByCond(
5115 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
5117 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5118 if (isLoopEntryGuardedByCond(
5119 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5120 isLoopBackedgeGuardedByCond(
5121 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
5124 // Otherwise see what can be done with known constant ranges.
5125 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5129 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5130 const SCEV *LHS, const SCEV *RHS) {
5131 if (HasSameValue(LHS, RHS))
5132 return ICmpInst::isTrueWhenEqual(Pred);
5134 // This code is split out from isKnownPredicate because it is called from
5135 // within isLoopEntryGuardedByCond.
5138 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5140 case ICmpInst::ICMP_SGT:
5141 Pred = ICmpInst::ICMP_SLT;
5142 std::swap(LHS, RHS);
5143 case ICmpInst::ICMP_SLT: {
5144 ConstantRange LHSRange = getSignedRange(LHS);
5145 ConstantRange RHSRange = getSignedRange(RHS);
5146 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5148 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5152 case ICmpInst::ICMP_SGE:
5153 Pred = ICmpInst::ICMP_SLE;
5154 std::swap(LHS, RHS);
5155 case ICmpInst::ICMP_SLE: {
5156 ConstantRange LHSRange = getSignedRange(LHS);
5157 ConstantRange RHSRange = getSignedRange(RHS);
5158 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5160 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5164 case ICmpInst::ICMP_UGT:
5165 Pred = ICmpInst::ICMP_ULT;
5166 std::swap(LHS, RHS);
5167 case ICmpInst::ICMP_ULT: {
5168 ConstantRange LHSRange = getUnsignedRange(LHS);
5169 ConstantRange RHSRange = getUnsignedRange(RHS);
5170 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5172 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5176 case ICmpInst::ICMP_UGE:
5177 Pred = ICmpInst::ICMP_ULE;
5178 std::swap(LHS, RHS);
5179 case ICmpInst::ICMP_ULE: {
5180 ConstantRange LHSRange = getUnsignedRange(LHS);
5181 ConstantRange RHSRange = getUnsignedRange(RHS);
5182 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5184 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5188 case ICmpInst::ICMP_NE: {
5189 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5191 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5194 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5195 if (isKnownNonZero(Diff))
5199 case ICmpInst::ICMP_EQ:
5200 // The check at the top of the function catches the case where
5201 // the values are known to be equal.
5207 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5208 /// protected by a conditional between LHS and RHS. This is used to
5209 /// to eliminate casts.
5211 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5212 ICmpInst::Predicate Pred,
5213 const SCEV *LHS, const SCEV *RHS) {
5214 // Interpret a null as meaning no loop, where there is obviously no guard
5215 // (interprocedural conditions notwithstanding).
5216 if (!L) return true;
5218 BasicBlock *Latch = L->getLoopLatch();
5222 BranchInst *LoopContinuePredicate =
5223 dyn_cast<BranchInst>(Latch->getTerminator());
5224 if (!LoopContinuePredicate ||
5225 LoopContinuePredicate->isUnconditional())
5228 return isImpliedCond(Pred, LHS, RHS,
5229 LoopContinuePredicate->getCondition(),
5230 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
5233 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
5234 /// by a conditional between LHS and RHS. This is used to help avoid max
5235 /// expressions in loop trip counts, and to eliminate casts.
5237 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5238 ICmpInst::Predicate Pred,
5239 const SCEV *LHS, const SCEV *RHS) {
5240 // Interpret a null as meaning no loop, where there is obviously no guard
5241 // (interprocedural conditions notwithstanding).
5242 if (!L) return false;
5244 // Starting at the loop predecessor, climb up the predecessor chain, as long
5245 // as there are predecessors that can be found that have unique successors
5246 // leading to the original header.
5247 for (std::pair<BasicBlock *, BasicBlock *>
5248 Pair(L->getLoopPredecessor(), L->getHeader());
5250 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
5252 BranchInst *LoopEntryPredicate =
5253 dyn_cast<BranchInst>(Pair.first->getTerminator());
5254 if (!LoopEntryPredicate ||
5255 LoopEntryPredicate->isUnconditional())
5258 if (isImpliedCond(Pred, LHS, RHS,
5259 LoopEntryPredicate->getCondition(),
5260 LoopEntryPredicate->getSuccessor(0) != Pair.second))
5267 /// isImpliedCond - Test whether the condition described by Pred, LHS,
5268 /// and RHS is true whenever the given Cond value evaluates to true.
5269 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
5270 const SCEV *LHS, const SCEV *RHS,
5271 Value *FoundCondValue,
5273 // Recursively handle And and Or conditions.
5274 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
5275 if (BO->getOpcode() == Instruction::And) {
5277 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5278 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5279 } else if (BO->getOpcode() == Instruction::Or) {
5281 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5282 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
5286 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
5287 if (!ICI) return false;
5289 // Bail if the ICmp's operands' types are wider than the needed type
5290 // before attempting to call getSCEV on them. This avoids infinite
5291 // recursion, since the analysis of widening casts can require loop
5292 // exit condition information for overflow checking, which would
5294 if (getTypeSizeInBits(LHS->getType()) <
5295 getTypeSizeInBits(ICI->getOperand(0)->getType()))
5298 // Now that we found a conditional branch that dominates the loop, check to
5299 // see if it is the comparison we are looking for.
5300 ICmpInst::Predicate FoundPred;
5302 FoundPred = ICI->getInversePredicate();
5304 FoundPred = ICI->getPredicate();
5306 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5307 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
5309 // Balance the types. The case where FoundLHS' type is wider than
5310 // LHS' type is checked for above.
5311 if (getTypeSizeInBits(LHS->getType()) >
5312 getTypeSizeInBits(FoundLHS->getType())) {
5313 if (CmpInst::isSigned(Pred)) {
5314 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5315 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5317 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5318 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5322 // Canonicalize the query to match the way instcombine will have
5323 // canonicalized the comparison.
5324 if (SimplifyICmpOperands(Pred, LHS, RHS))
5326 return CmpInst::isTrueWhenEqual(Pred);
5327 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5328 if (FoundLHS == FoundRHS)
5329 return CmpInst::isFalseWhenEqual(Pred);
5331 // Check to see if we can make the LHS or RHS match.
5332 if (LHS == FoundRHS || RHS == FoundLHS) {
5333 if (isa<SCEVConstant>(RHS)) {
5334 std::swap(FoundLHS, FoundRHS);
5335 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5337 std::swap(LHS, RHS);
5338 Pred = ICmpInst::getSwappedPredicate(Pred);
5342 // Check whether the found predicate is the same as the desired predicate.
5343 if (FoundPred == Pred)
5344 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5346 // Check whether swapping the found predicate makes it the same as the
5347 // desired predicate.
5348 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5349 if (isa<SCEVConstant>(RHS))
5350 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5352 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5353 RHS, LHS, FoundLHS, FoundRHS);
5356 // Check whether the actual condition is beyond sufficient.
5357 if (FoundPred == ICmpInst::ICMP_EQ)
5358 if (ICmpInst::isTrueWhenEqual(Pred))
5359 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5361 if (Pred == ICmpInst::ICMP_NE)
5362 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5363 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5366 // Otherwise assume the worst.
5370 /// isImpliedCondOperands - Test whether the condition described by Pred,
5371 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
5372 /// and FoundRHS is true.
5373 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5374 const SCEV *LHS, const SCEV *RHS,
5375 const SCEV *FoundLHS,
5376 const SCEV *FoundRHS) {
5377 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5378 FoundLHS, FoundRHS) ||
5379 // ~x < ~y --> x > y
5380 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5381 getNotSCEV(FoundRHS),
5382 getNotSCEV(FoundLHS));
5385 /// isImpliedCondOperandsHelper - Test whether the condition described by
5386 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
5387 /// FoundLHS, and FoundRHS is true.
5389 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5390 const SCEV *LHS, const SCEV *RHS,
5391 const SCEV *FoundLHS,
5392 const SCEV *FoundRHS) {
5394 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5395 case ICmpInst::ICMP_EQ:
5396 case ICmpInst::ICMP_NE:
5397 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5400 case ICmpInst::ICMP_SLT:
5401 case ICmpInst::ICMP_SLE:
5402 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5403 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
5406 case ICmpInst::ICMP_SGT:
5407 case ICmpInst::ICMP_SGE:
5408 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5409 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
5412 case ICmpInst::ICMP_ULT:
5413 case ICmpInst::ICMP_ULE:
5414 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5415 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
5418 case ICmpInst::ICMP_UGT:
5419 case ICmpInst::ICMP_UGE:
5420 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5421 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
5429 /// getBECount - Subtract the end and start values and divide by the step,
5430 /// rounding up, to get the number of times the backedge is executed. Return
5431 /// CouldNotCompute if an intermediate computation overflows.
5432 const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
5436 assert(!isKnownNegative(Step) &&
5437 "This code doesn't handle negative strides yet!");
5439 const Type *Ty = Start->getType();
5440 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
5441 const SCEV *Diff = getMinusSCEV(End, Start);
5442 const SCEV *RoundUp = getAddExpr(Step, NegOne);
5444 // Add an adjustment to the difference between End and Start so that
5445 // the division will effectively round up.
5446 const SCEV *Add = getAddExpr(Diff, RoundUp);
5449 // Check Add for unsigned overflow.
5450 // TODO: More sophisticated things could be done here.
5451 const Type *WideTy = IntegerType::get(getContext(),
5452 getTypeSizeInBits(Ty) + 1);
5453 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5454 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5455 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5456 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5457 return getCouldNotCompute();
5460 return getUDivExpr(Add, Step);
5463 /// HowManyLessThans - Return the number of times a backedge containing the
5464 /// specified less-than comparison will execute. If not computable, return
5465 /// CouldNotCompute.
5466 ScalarEvolution::BackedgeTakenInfo
5467 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5468 const Loop *L, bool isSigned) {
5469 // Only handle: "ADDREC < LoopInvariant".
5470 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
5472 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
5473 if (!AddRec || AddRec->getLoop() != L)
5474 return getCouldNotCompute();
5476 // Check to see if we have a flag which makes analysis easy.
5477 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5478 AddRec->hasNoUnsignedWrap();
5480 if (AddRec->isAffine()) {
5481 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
5482 const SCEV *Step = AddRec->getStepRecurrence(*this);
5485 return getCouldNotCompute();
5486 if (Step->isOne()) {
5487 // With unit stride, the iteration never steps past the limit value.
5488 } else if (isKnownPositive(Step)) {
5489 // Test whether a positive iteration can step past the limit
5490 // value and past the maximum value for its type in a single step.
5491 // Note that it's not sufficient to check NoWrap here, because even
5492 // though the value after a wrap is undefined, it's not undefined
5493 // behavior, so if wrap does occur, the loop could either terminate or
5494 // loop infinitely, but in either case, the loop is guaranteed to
5495 // iterate at least until the iteration where the wrapping occurs.
5496 const SCEV *One = getConstant(Step->getType(), 1);
5498 APInt Max = APInt::getSignedMaxValue(BitWidth);
5499 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5500 .slt(getSignedRange(RHS).getSignedMax()))
5501 return getCouldNotCompute();
5503 APInt Max = APInt::getMaxValue(BitWidth);
5504 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5505 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5506 return getCouldNotCompute();
5509 // TODO: Handle negative strides here and below.
5510 return getCouldNotCompute();
5512 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5513 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5514 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
5515 // treat m-n as signed nor unsigned due to overflow possibility.
5517 // First, we get the value of the LHS in the first iteration: n
5518 const SCEV *Start = AddRec->getOperand(0);
5520 // Determine the minimum constant start value.
5521 const SCEV *MinStart = getConstant(isSigned ?
5522 getSignedRange(Start).getSignedMin() :
5523 getUnsignedRange(Start).getUnsignedMin());
5525 // If we know that the condition is true in order to enter the loop,
5526 // then we know that it will run exactly (m-n)/s times. Otherwise, we
5527 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5528 // the division must round up.
5529 const SCEV *End = RHS;
5530 if (!isLoopEntryGuardedByCond(L,
5531 isSigned ? ICmpInst::ICMP_SLT :
5533 getMinusSCEV(Start, Step), RHS))
5534 End = isSigned ? getSMaxExpr(RHS, Start)
5535 : getUMaxExpr(RHS, Start);
5537 // Determine the maximum constant end value.
5538 const SCEV *MaxEnd = getConstant(isSigned ?
5539 getSignedRange(End).getSignedMax() :
5540 getUnsignedRange(End).getUnsignedMax());
5542 // If MaxEnd is within a step of the maximum integer value in its type,
5543 // adjust it down to the minimum value which would produce the same effect.
5544 // This allows the subsequent ceiling division of (N+(step-1))/step to
5545 // compute the correct value.
5546 const SCEV *StepMinusOne = getMinusSCEV(Step,
5547 getConstant(Step->getType(), 1));
5550 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5553 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5556 // Finally, we subtract these two values and divide, rounding up, to get
5557 // the number of times the backedge is executed.
5558 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
5560 // The maximum backedge count is similar, except using the minimum start
5561 // value and the maximum end value.
5562 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
5564 return BackedgeTakenInfo(BECount, MaxBECount);
5567 return getCouldNotCompute();
5570 /// getNumIterationsInRange - Return the number of iterations of this loop that
5571 /// produce values in the specified constant range. Another way of looking at
5572 /// this is that it returns the first iteration number where the value is not in
5573 /// the condition, thus computing the exit count. If the iteration count can't
5574 /// be computed, an instance of SCEVCouldNotCompute is returned.
5575 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
5576 ScalarEvolution &SE) const {
5577 if (Range.isFullSet()) // Infinite loop.
5578 return SE.getCouldNotCompute();
5580 // If the start is a non-zero constant, shift the range to simplify things.
5581 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
5582 if (!SC->getValue()->isZero()) {
5583 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
5584 Operands[0] = SE.getConstant(SC->getType(), 0);
5585 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
5586 if (const SCEVAddRecExpr *ShiftedAddRec =
5587 dyn_cast<SCEVAddRecExpr>(Shifted))
5588 return ShiftedAddRec->getNumIterationsInRange(
5589 Range.subtract(SC->getValue()->getValue()), SE);
5590 // This is strange and shouldn't happen.
5591 return SE.getCouldNotCompute();
5594 // The only time we can solve this is when we have all constant indices.
5595 // Otherwise, we cannot determine the overflow conditions.
5596 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5597 if (!isa<SCEVConstant>(getOperand(i)))
5598 return SE.getCouldNotCompute();
5601 // Okay at this point we know that all elements of the chrec are constants and
5602 // that the start element is zero.
5604 // First check to see if the range contains zero. If not, the first
5606 unsigned BitWidth = SE.getTypeSizeInBits(getType());
5607 if (!Range.contains(APInt(BitWidth, 0)))
5608 return SE.getConstant(getType(), 0);
5611 // If this is an affine expression then we have this situation:
5612 // Solve {0,+,A} in Range === Ax in Range
5614 // We know that zero is in the range. If A is positive then we know that
5615 // the upper value of the range must be the first possible exit value.
5616 // If A is negative then the lower of the range is the last possible loop
5617 // value. Also note that we already checked for a full range.
5618 APInt One(BitWidth,1);
5619 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5620 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
5622 // The exit value should be (End+A)/A.
5623 APInt ExitVal = (End + A).udiv(A);
5624 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
5626 // Evaluate at the exit value. If we really did fall out of the valid
5627 // range, then we computed our trip count, otherwise wrap around or other
5628 // things must have happened.
5629 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
5630 if (Range.contains(Val->getValue()))
5631 return SE.getCouldNotCompute(); // Something strange happened
5633 // Ensure that the previous value is in the range. This is a sanity check.
5634 assert(Range.contains(
5635 EvaluateConstantChrecAtConstant(this,
5636 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
5637 "Linear scev computation is off in a bad way!");
5638 return SE.getConstant(ExitValue);
5639 } else if (isQuadratic()) {
5640 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5641 // quadratic equation to solve it. To do this, we must frame our problem in
5642 // terms of figuring out when zero is crossed, instead of when
5643 // Range.getUpper() is crossed.
5644 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
5645 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
5646 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
5648 // Next, solve the constructed addrec
5649 std::pair<const SCEV *,const SCEV *> Roots =
5650 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
5651 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5652 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
5654 // Pick the smallest positive root value.
5655 if (ConstantInt *CB =
5656 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
5657 R1->getValue(), R2->getValue()))) {
5658 if (CB->getZExtValue() == false)
5659 std::swap(R1, R2); // R1 is the minimum root now.
5661 // Make sure the root is not off by one. The returned iteration should
5662 // not be in the range, but the previous one should be. When solving
5663 // for "X*X < 5", for example, we should not return a root of 2.
5664 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
5667 if (Range.contains(R1Val->getValue())) {
5668 // The next iteration must be out of the range...
5669 ConstantInt *NextVal =
5670 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
5672 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5673 if (!Range.contains(R1Val->getValue()))
5674 return SE.getConstant(NextVal);
5675 return SE.getCouldNotCompute(); // Something strange happened
5678 // If R1 was not in the range, then it is a good return value. Make
5679 // sure that R1-1 WAS in the range though, just in case.
5680 ConstantInt *NextVal =
5681 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
5682 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
5683 if (Range.contains(R1Val->getValue()))
5685 return SE.getCouldNotCompute(); // Something strange happened
5690 return SE.getCouldNotCompute();
5695 //===----------------------------------------------------------------------===//
5696 // SCEVCallbackVH Class Implementation
5697 //===----------------------------------------------------------------------===//
5699 void ScalarEvolution::SCEVCallbackVH::deleted() {
5700 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5701 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5702 SE->ConstantEvolutionLoopExitValue.erase(PN);
5703 SE->Scalars.erase(getValPtr());
5704 // this now dangles!
5707 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
5708 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
5710 // Forget all the expressions associated with users of the old value,
5711 // so that future queries will recompute the expressions using the new
5713 Value *Old = getValPtr();
5714 SmallVector<User *, 16> Worklist;
5715 SmallPtrSet<User *, 8> Visited;
5716 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5718 Worklist.push_back(*UI);
5719 while (!Worklist.empty()) {
5720 User *U = Worklist.pop_back_val();
5721 // Deleting the Old value will cause this to dangle. Postpone
5722 // that until everything else is done.
5725 if (!Visited.insert(U))
5727 if (PHINode *PN = dyn_cast<PHINode>(U))
5728 SE->ConstantEvolutionLoopExitValue.erase(PN);
5729 SE->Scalars.erase(U);
5730 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5732 Worklist.push_back(*UI);
5734 // Delete the Old value.
5735 if (PHINode *PN = dyn_cast<PHINode>(Old))
5736 SE->ConstantEvolutionLoopExitValue.erase(PN);
5737 SE->Scalars.erase(Old);
5738 // this now dangles!
5741 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
5742 : CallbackVH(V), SE(se) {}
5744 //===----------------------------------------------------------------------===//
5745 // ScalarEvolution Class Implementation
5746 //===----------------------------------------------------------------------===//
5748 ScalarEvolution::ScalarEvolution()
5749 : FunctionPass(ID), FirstUnknown(0) {
5752 bool ScalarEvolution::runOnFunction(Function &F) {
5754 LI = &getAnalysis<LoopInfo>();
5755 TD = getAnalysisIfAvailable<TargetData>();
5756 DT = &getAnalysis<DominatorTree>();
5760 void ScalarEvolution::releaseMemory() {
5761 // Iterate through all the SCEVUnknown instances and call their
5762 // destructors, so that they release their references to their values.
5763 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5768 BackedgeTakenCounts.clear();
5769 ConstantEvolutionLoopExitValue.clear();
5770 ValuesAtScopes.clear();
5771 UniqueSCEVs.clear();
5772 SCEVAllocator.Reset();
5775 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5776 AU.setPreservesAll();
5777 AU.addRequiredTransitive<LoopInfo>();
5778 AU.addRequiredTransitive<DominatorTree>();
5781 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
5782 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
5785 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
5787 // Print all inner loops first
5788 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5789 PrintLoopInfo(OS, SE, *I);
5792 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5795 SmallVector<BasicBlock *, 8> ExitBlocks;
5796 L->getExitBlocks(ExitBlocks);
5797 if (ExitBlocks.size() != 1)
5798 OS << "<multiple exits> ";
5800 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5801 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
5803 OS << "Unpredictable backedge-taken count. ";
5808 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5811 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5812 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5814 OS << "Unpredictable max backedge-taken count. ";
5820 void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
5821 // ScalarEvolution's implementation of the print method is to print
5822 // out SCEV values of all instructions that are interesting. Doing
5823 // this potentially causes it to create new SCEV objects though,
5824 // which technically conflicts with the const qualifier. This isn't
5825 // observable from outside the class though, so casting away the
5826 // const isn't dangerous.
5827 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
5829 OS << "Classifying expressions for: ";
5830 WriteAsOperand(OS, F, /*PrintType=*/false);
5832 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
5833 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
5836 const SCEV *SV = SE.getSCEV(&*I);
5839 const Loop *L = LI->getLoopFor((*I).getParent());
5841 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
5848 OS << "\t\t" "Exits: ";
5849 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
5850 if (!ExitValue->isLoopInvariant(L)) {
5851 OS << "<<Unknown>>";
5860 OS << "Determining loop execution counts for: ";
5861 WriteAsOperand(OS, F, /*PrintType=*/false);
5863 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5864 PrintLoopInfo(OS, &SE, *I);