Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1 | //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by the LLVM research group and is distributed under |
| 6 | // the University of Illinois Open Source License. See LICENSE.TXT for details. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file contains the implementation of the scalar evolution analysis |
| 11 | // engine, which is used primarily to analyze expressions involving induction |
| 12 | // variables in loops. |
| 13 | // |
| 14 | // There are several aspects to this library. First is the representation of |
| 15 | // scalar expressions, which are represented as subclasses of the SCEV class. |
| 16 | // These classes are used to represent certain types of subexpressions that we |
| 17 | // can handle. These classes are reference counted, managed by the SCEVHandle |
| 18 | // class. We only create one SCEV of a particular shape, so pointer-comparisons |
| 19 | // for equality are legal. |
| 20 | // |
| 21 | // One important aspect of the SCEV objects is that they are never cyclic, even |
| 22 | // if there is a cycle in the dataflow for an expression (ie, a PHI node). If |
| 23 | // the PHI node is one of the idioms that we can represent (e.g., a polynomial |
| 24 | // recurrence) then we represent it directly as a recurrence node, otherwise we |
| 25 | // represent it as a SCEVUnknown node. |
| 26 | // |
| 27 | // In addition to being able to represent expressions of various types, we also |
| 28 | // have folders that are used to build the *canonical* representation for a |
| 29 | // particular expression. These folders are capable of using a variety of |
| 30 | // rewrite rules to simplify the expressions. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 31 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 32 | // Once the folders are defined, we can implement the more interesting |
| 33 | // higher-level code, such as the code that recognizes PHI nodes of various |
| 34 | // types, computes the execution count of a loop, etc. |
| 35 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 36 | // TODO: We should use these routines and value representations to implement |
| 37 | // dependence analysis! |
| 38 | // |
| 39 | //===----------------------------------------------------------------------===// |
| 40 | // |
| 41 | // There are several good references for the techniques used in this analysis. |
| 42 | // |
| 43 | // Chains of recurrences -- a method to expedite the evaluation |
| 44 | // of closed-form functions |
| 45 | // Olaf Bachmann, Paul S. Wang, Eugene V. Zima |
| 46 | // |
| 47 | // On computational properties of chains of recurrences |
| 48 | // Eugene V. Zima |
| 49 | // |
| 50 | // Symbolic Evaluation of Chains of Recurrences for Loop Optimization |
| 51 | // Robert A. van Engelen |
| 52 | // |
| 53 | // Efficient Symbolic Analysis for Optimizing Compilers |
| 54 | // Robert A. van Engelen |
| 55 | // |
| 56 | // Using the chains of recurrences algebra for data dependence testing and |
| 57 | // induction variable substitution |
| 58 | // MS Thesis, Johnie Birch |
| 59 | // |
| 60 | //===----------------------------------------------------------------------===// |
| 61 | |
Chris Lattner | 3b27d68 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 62 | #define DEBUG_TYPE "scalar-evolution" |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 63 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 64 | #include "llvm/Constants.h" |
| 65 | #include "llvm/DerivedTypes.h" |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 66 | #include "llvm/GlobalVariable.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 67 | #include "llvm/Instructions.h" |
John Criswell | a115643 | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/LoopInfo.h" |
| 70 | #include "llvm/Assembly/Writer.h" |
| 71 | #include "llvm/Transforms/Scalar.h" |
| 72 | #include "llvm/Support/CFG.h" |
Chris Lattner | 9525528 | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 73 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 74 | #include "llvm/Support/Compiler.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 75 | #include "llvm/Support/ConstantRange.h" |
| 76 | #include "llvm/Support/InstIterator.h" |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 77 | #include "llvm/Support/ManagedStatic.h" |
Chris Lattner | 75de5ab | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 78 | #include "llvm/Support/MathExtras.h" |
Bill Wendling | 6f81b51 | 2006-11-28 22:46:12 +0000 | [diff] [blame] | 79 | #include "llvm/Support/Streams.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 80 | #include "llvm/ADT/Statistic.h" |
Bill Wendling | 6f81b51 | 2006-11-28 22:46:12 +0000 | [diff] [blame] | 81 | #include <ostream> |
Alkis Evlogimenos | 20aa474 | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 82 | #include <algorithm> |
Jeff Cohen | 97af751 | 2006-12-02 02:22:01 +0000 | [diff] [blame] | 83 | #include <cmath> |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 84 | using namespace llvm; |
| 85 | |
Chris Lattner | 3b27d68 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 86 | STATISTIC(NumBruteForceEvaluations, |
| 87 | "Number of brute force evaluations needed to " |
| 88 | "calculate high-order polynomial exit values"); |
| 89 | STATISTIC(NumArrayLenItCounts, |
| 90 | "Number of trip counts computed with array length"); |
| 91 | STATISTIC(NumTripCountsComputed, |
| 92 | "Number of loops with predictable loop counts"); |
| 93 | STATISTIC(NumTripCountsNotComputed, |
| 94 | "Number of loops without predictable loop counts"); |
| 95 | STATISTIC(NumBruteForceTripCountsComputed, |
| 96 | "Number of loops with trip counts computed by force"); |
| 97 | |
| 98 | cl::opt<unsigned> |
| 99 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 100 | cl::desc("Maximum number of iterations SCEV will " |
| 101 | "symbolically execute a constant derived loop"), |
| 102 | cl::init(100)); |
| 103 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 104 | namespace { |
Chris Lattner | 5d8925c | 2006-08-27 22:30:17 +0000 | [diff] [blame] | 105 | RegisterPass<ScalarEvolution> |
Chris Lattner | 45a1cf8 | 2004-04-19 03:42:32 +0000 | [diff] [blame] | 106 | R("scalar-evolution", "Scalar Evolution Analysis"); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 107 | } |
| 108 | |
| 109 | //===----------------------------------------------------------------------===// |
| 110 | // SCEV class definitions |
| 111 | //===----------------------------------------------------------------------===// |
| 112 | |
| 113 | //===----------------------------------------------------------------------===// |
| 114 | // Implementation of the SCEV class. |
| 115 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 116 | SCEV::~SCEV() {} |
| 117 | void SCEV::dump() const { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 118 | print(cerr); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 119 | } |
| 120 | |
| 121 | /// getValueRange - Return the tightest constant bounds that this value is |
| 122 | /// known to have. This method is only valid on integer SCEV objects. |
| 123 | ConstantRange SCEV::getValueRange() const { |
| 124 | const Type *Ty = getType(); |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 125 | assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!"); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 126 | // Default to a full range if no better information is available. |
Reid Spencer | c6aedf7 | 2007-02-28 22:03:51 +0000 | [diff] [blame] | 127 | return ConstantRange(getBitWidth()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 128 | } |
| 129 | |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 130 | uint32_t SCEV::getBitWidth() const { |
| 131 | if (const IntegerType* ITy = dyn_cast<IntegerType>(getType())) |
| 132 | return ITy->getBitWidth(); |
| 133 | return 0; |
| 134 | } |
| 135 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 136 | |
| 137 | SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} |
| 138 | |
| 139 | bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { |
| 140 | assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); |
Misha Brukman | bb2aff1 | 2004-04-05 19:00:46 +0000 | [diff] [blame] | 141 | return false; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 142 | } |
| 143 | |
| 144 | const Type *SCEVCouldNotCompute::getType() const { |
| 145 | assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); |
Misha Brukman | bb2aff1 | 2004-04-05 19:00:46 +0000 | [diff] [blame] | 146 | return 0; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 147 | } |
| 148 | |
| 149 | bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { |
| 150 | assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); |
| 151 | return false; |
| 152 | } |
| 153 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 154 | SCEVHandle SCEVCouldNotCompute:: |
| 155 | replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, |
| 156 | const SCEVHandle &Conc) const { |
| 157 | return this; |
| 158 | } |
| 159 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 160 | void SCEVCouldNotCompute::print(std::ostream &OS) const { |
| 161 | OS << "***COULDNOTCOMPUTE***"; |
| 162 | } |
| 163 | |
| 164 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 165 | return S->getSCEVType() == scCouldNotCompute; |
| 166 | } |
| 167 | |
| 168 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 169 | // SCEVConstants - Only allow the creation of one SCEVConstant for any |
| 170 | // particular value. Don't use a SCEVHandle here, or else the object will |
| 171 | // never be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 172 | static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 173 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 174 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 175 | SCEVConstant::~SCEVConstant() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 176 | SCEVConstants->erase(V); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 177 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 178 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 179 | SCEVHandle SCEVConstant::get(ConstantInt *V) { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 180 | SCEVConstant *&R = (*SCEVConstants)[V]; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 181 | if (R == 0) R = new SCEVConstant(V); |
| 182 | return R; |
| 183 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 184 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 185 | ConstantRange SCEVConstant::getValueRange() const { |
Reid Spencer | dc5c159 | 2007-02-28 18:57:32 +0000 | [diff] [blame] | 186 | return ConstantRange(V->getValue()); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 187 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 188 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 189 | const Type *SCEVConstant::getType() const { return V->getType(); } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 190 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 191 | void SCEVConstant::print(std::ostream &OS) const { |
| 192 | WriteAsOperand(OS, V, false); |
| 193 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 194 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 195 | // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any |
| 196 | // particular input. Don't use a SCEVHandle here, or else the object will |
| 197 | // never be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 198 | static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, |
| 199 | SCEVTruncateExpr*> > SCEVTruncates; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 200 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 201 | SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) |
| 202 | : SCEV(scTruncate), Op(op), Ty(ty) { |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 203 | assert(Op->getType()->isInteger() && Ty->isInteger() && |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 204 | "Cannot truncate non-integer value!"); |
Reid Spencer | e7ca042 | 2007-01-08 01:26:33 +0000 | [diff] [blame] | 205 | assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits() |
| 206 | && "This is not a truncating conversion!"); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 207 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 208 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 209 | SCEVTruncateExpr::~SCEVTruncateExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 210 | SCEVTruncates->erase(std::make_pair(Op, Ty)); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 211 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 212 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 213 | ConstantRange SCEVTruncateExpr::getValueRange() const { |
Reid Spencer | c6aedf7 | 2007-02-28 22:03:51 +0000 | [diff] [blame] | 214 | return getOperand()->getValueRange().truncate(getBitWidth()); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 215 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 216 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 217 | void SCEVTruncateExpr::print(std::ostream &OS) const { |
| 218 | OS << "(truncate " << *Op << " to " << *Ty << ")"; |
| 219 | } |
| 220 | |
| 221 | // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any |
| 222 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 223 | // be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 224 | static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, |
| 225 | SCEVZeroExtendExpr*> > SCEVZeroExtends; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 226 | |
| 227 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) |
Reid Spencer | 48d8a70 | 2006-11-01 21:53:12 +0000 | [diff] [blame] | 228 | : SCEV(scZeroExtend), Op(op), Ty(ty) { |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 229 | assert(Op->getType()->isInteger() && Ty->isInteger() && |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 230 | "Cannot zero extend non-integer value!"); |
Reid Spencer | e7ca042 | 2007-01-08 01:26:33 +0000 | [diff] [blame] | 231 | assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits() |
| 232 | && "This is not an extending conversion!"); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 233 | } |
| 234 | |
| 235 | SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 236 | SCEVZeroExtends->erase(std::make_pair(Op, Ty)); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 237 | } |
| 238 | |
| 239 | ConstantRange SCEVZeroExtendExpr::getValueRange() const { |
Reid Spencer | c6aedf7 | 2007-02-28 22:03:51 +0000 | [diff] [blame] | 240 | return getOperand()->getValueRange().zeroExtend(getBitWidth()); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 241 | } |
| 242 | |
| 243 | void SCEVZeroExtendExpr::print(std::ostream &OS) const { |
| 244 | OS << "(zeroextend " << *Op << " to " << *Ty << ")"; |
| 245 | } |
| 246 | |
| 247 | // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any |
| 248 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 249 | // be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 250 | static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >, |
| 251 | SCEVCommutativeExpr*> > SCEVCommExprs; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 252 | |
| 253 | SCEVCommutativeExpr::~SCEVCommutativeExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 254 | SCEVCommExprs->erase(std::make_pair(getSCEVType(), |
| 255 | std::vector<SCEV*>(Operands.begin(), |
| 256 | Operands.end()))); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 257 | } |
| 258 | |
| 259 | void SCEVCommutativeExpr::print(std::ostream &OS) const { |
| 260 | assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); |
| 261 | const char *OpStr = getOperationStr(); |
| 262 | OS << "(" << *Operands[0]; |
| 263 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
| 264 | OS << OpStr << *Operands[i]; |
| 265 | OS << ")"; |
| 266 | } |
| 267 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 268 | SCEVHandle SCEVCommutativeExpr:: |
| 269 | replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, |
| 270 | const SCEVHandle &Conc) const { |
| 271 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { |
| 272 | SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); |
| 273 | if (H != getOperand(i)) { |
| 274 | std::vector<SCEVHandle> NewOps; |
| 275 | NewOps.reserve(getNumOperands()); |
| 276 | for (unsigned j = 0; j != i; ++j) |
| 277 | NewOps.push_back(getOperand(j)); |
| 278 | NewOps.push_back(H); |
| 279 | for (++i; i != e; ++i) |
| 280 | NewOps.push_back(getOperand(i)-> |
| 281 | replaceSymbolicValuesWithConcrete(Sym, Conc)); |
| 282 | |
| 283 | if (isa<SCEVAddExpr>(this)) |
| 284 | return SCEVAddExpr::get(NewOps); |
| 285 | else if (isa<SCEVMulExpr>(this)) |
| 286 | return SCEVMulExpr::get(NewOps); |
| 287 | else |
| 288 | assert(0 && "Unknown commutative expr!"); |
| 289 | } |
| 290 | } |
| 291 | return this; |
| 292 | } |
| 293 | |
| 294 | |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 295 | // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 296 | // input. Don't use a SCEVHandle here, or else the object will never be |
| 297 | // deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 298 | static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, |
| 299 | SCEVSDivExpr*> > SCEVSDivs; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 300 | |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 301 | SCEVSDivExpr::~SCEVSDivExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 302 | SCEVSDivs->erase(std::make_pair(LHS, RHS)); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 303 | } |
| 304 | |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 305 | void SCEVSDivExpr::print(std::ostream &OS) const { |
| 306 | OS << "(" << *LHS << " /s " << *RHS << ")"; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 307 | } |
| 308 | |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 309 | const Type *SCEVSDivExpr::getType() const { |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 310 | return LHS->getType(); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 311 | } |
| 312 | |
| 313 | // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any |
| 314 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 315 | // be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 316 | static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >, |
| 317 | SCEVAddRecExpr*> > SCEVAddRecExprs; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 318 | |
| 319 | SCEVAddRecExpr::~SCEVAddRecExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 320 | SCEVAddRecExprs->erase(std::make_pair(L, |
| 321 | std::vector<SCEV*>(Operands.begin(), |
| 322 | Operands.end()))); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 323 | } |
| 324 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 325 | SCEVHandle SCEVAddRecExpr:: |
| 326 | replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, |
| 327 | const SCEVHandle &Conc) const { |
| 328 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { |
| 329 | SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); |
| 330 | if (H != getOperand(i)) { |
| 331 | std::vector<SCEVHandle> NewOps; |
| 332 | NewOps.reserve(getNumOperands()); |
| 333 | for (unsigned j = 0; j != i; ++j) |
| 334 | NewOps.push_back(getOperand(j)); |
| 335 | NewOps.push_back(H); |
| 336 | for (++i; i != e; ++i) |
| 337 | NewOps.push_back(getOperand(i)-> |
| 338 | replaceSymbolicValuesWithConcrete(Sym, Conc)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 339 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 340 | return get(NewOps, L); |
| 341 | } |
| 342 | } |
| 343 | return this; |
| 344 | } |
| 345 | |
| 346 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 347 | bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { |
| 348 | // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't |
Chris Lattner | ff2006a | 2005-08-16 00:37:01 +0000 | [diff] [blame] | 349 | // contain L and if the start is invariant. |
| 350 | return !QueryLoop->contains(L->getHeader()) && |
| 351 | getOperand(0)->isLoopInvariant(QueryLoop); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 352 | } |
| 353 | |
| 354 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 355 | void SCEVAddRecExpr::print(std::ostream &OS) const { |
| 356 | OS << "{" << *Operands[0]; |
| 357 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
| 358 | OS << ",+," << *Operands[i]; |
| 359 | OS << "}<" << L->getHeader()->getName() + ">"; |
| 360 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 361 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 362 | // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular |
| 363 | // value. Don't use a SCEVHandle here, or else the object will never be |
| 364 | // deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 365 | static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 366 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 367 | SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 368 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 369 | bool SCEVUnknown::isLoopInvariant(const Loop *L) const { |
| 370 | // All non-instruction values are loop invariant. All instructions are loop |
| 371 | // invariant if they are not contained in the specified loop. |
| 372 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 373 | return !L->contains(I->getParent()); |
| 374 | return true; |
| 375 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 376 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 377 | const Type *SCEVUnknown::getType() const { |
| 378 | return V->getType(); |
| 379 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 380 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 381 | void SCEVUnknown::print(std::ostream &OS) const { |
| 382 | WriteAsOperand(OS, V, false); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 383 | } |
| 384 | |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 385 | //===----------------------------------------------------------------------===// |
| 386 | // SCEV Utilities |
| 387 | //===----------------------------------------------------------------------===// |
| 388 | |
| 389 | namespace { |
| 390 | /// SCEVComplexityCompare - Return true if the complexity of the LHS is less |
| 391 | /// than the complexity of the RHS. This comparator is used to canonicalize |
| 392 | /// expressions. |
Chris Lattner | 9525528 | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 393 | struct VISIBILITY_HIDDEN SCEVComplexityCompare { |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 394 | bool operator()(SCEV *LHS, SCEV *RHS) { |
| 395 | return LHS->getSCEVType() < RHS->getSCEVType(); |
| 396 | } |
| 397 | }; |
| 398 | } |
| 399 | |
| 400 | /// GroupByComplexity - Given a list of SCEV objects, order them by their |
| 401 | /// complexity, and group objects of the same complexity together by value. |
| 402 | /// When this routine is finished, we know that any duplicates in the vector are |
| 403 | /// consecutive and that complexity is monotonically increasing. |
| 404 | /// |
| 405 | /// Note that we go take special precautions to ensure that we get determinstic |
| 406 | /// results from this routine. In other words, we don't want the results of |
| 407 | /// this to depend on where the addresses of various SCEV objects happened to |
| 408 | /// land in memory. |
| 409 | /// |
| 410 | static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { |
| 411 | if (Ops.size() < 2) return; // Noop |
| 412 | if (Ops.size() == 2) { |
| 413 | // This is the common case, which also happens to be trivially simple. |
| 414 | // Special case it. |
| 415 | if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType()) |
| 416 | std::swap(Ops[0], Ops[1]); |
| 417 | return; |
| 418 | } |
| 419 | |
| 420 | // Do the rough sort by complexity. |
| 421 | std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); |
| 422 | |
| 423 | // Now that we are sorted by complexity, group elements of the same |
| 424 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 425 | // be extremely short in practice. Note that we take this approach because we |
| 426 | // do not want to depend on the addresses of the objects we are grouping. |
Chris Lattner | 2d58452 | 2004-06-20 17:01:44 +0000 | [diff] [blame] | 427 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 428 | SCEV *S = Ops[i]; |
| 429 | unsigned Complexity = S->getSCEVType(); |
| 430 | |
| 431 | // If there are any objects of the same complexity and same value as this |
| 432 | // one, group them. |
| 433 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 434 | if (Ops[j] == S) { // Found a duplicate. |
| 435 | // Move it to immediately after i'th element. |
| 436 | std::swap(Ops[i+1], Ops[j]); |
| 437 | ++i; // no need to rescan it. |
Chris Lattner | 541ad5e | 2004-06-20 20:32:16 +0000 | [diff] [blame] | 438 | if (i == e-2) return; // Done! |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 439 | } |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 444 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 445 | |
| 446 | //===----------------------------------------------------------------------===// |
| 447 | // Simple SCEV method implementations |
| 448 | //===----------------------------------------------------------------------===// |
| 449 | |
| 450 | /// getIntegerSCEV - Given an integer or FP type, create a constant for the |
| 451 | /// specified signed integer value and return a SCEV for the constant. |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 452 | SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 453 | Constant *C; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 454 | if (Val == 0) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 455 | C = Constant::getNullValue(Ty); |
| 456 | else if (Ty->isFloatingPoint()) |
| 457 | C = ConstantFP::get(Ty, Val); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 458 | else |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 459 | C = ConstantInt::get(Ty, Val); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 460 | return SCEVUnknown::get(C); |
| 461 | } |
| 462 | |
| 463 | /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 464 | /// input value to the specified type. If the type must be extended, it is zero |
| 465 | /// extended. |
| 466 | static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) { |
| 467 | const Type *SrcTy = V->getType(); |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 468 | assert(SrcTy->isInteger() && Ty->isInteger() && |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 469 | "Cannot truncate or zero extend with non-integer arguments!"); |
Reid Spencer | e7ca042 | 2007-01-08 01:26:33 +0000 | [diff] [blame] | 470 | if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits()) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 471 | return V; // No conversion |
Reid Spencer | e7ca042 | 2007-01-08 01:26:33 +0000 | [diff] [blame] | 472 | if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 473 | return SCEVTruncateExpr::get(V, Ty); |
| 474 | return SCEVZeroExtendExpr::get(V, Ty); |
| 475 | } |
| 476 | |
| 477 | /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V |
| 478 | /// |
Chris Lattner | bac5b46 | 2005-03-09 05:34:41 +0000 | [diff] [blame] | 479 | SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 480 | if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
| 481 | return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue())); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 482 | |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 483 | return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType())); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 484 | } |
| 485 | |
| 486 | /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. |
| 487 | /// |
Chris Lattner | bac5b46 | 2005-03-09 05:34:41 +0000 | [diff] [blame] | 488 | SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 489 | // X - Y --> X + -Y |
Chris Lattner | bac5b46 | 2005-03-09 05:34:41 +0000 | [diff] [blame] | 490 | return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 491 | } |
| 492 | |
| 493 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 494 | /// PartialFact - Compute V!/(V-NumSteps)! |
| 495 | static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) { |
| 496 | // Handle this case efficiently, it is common to have constant iteration |
| 497 | // counts while computing loop exit values. |
| 498 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) { |
Reid Spencer | dc5c159 | 2007-02-28 18:57:32 +0000 | [diff] [blame] | 499 | APInt Val = SC->getValue()->getValue(); |
| 500 | APInt Result(Val.getBitWidth(), 1); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 501 | for (; NumSteps; --NumSteps) |
| 502 | Result *= Val-(NumSteps-1); |
Reid Spencer | c7cd7a0 | 2007-03-01 19:32:33 +0000 | [diff] [blame^] | 503 | return SCEVUnknown::get(ConstantInt::get(Result)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 504 | } |
| 505 | |
| 506 | const Type *Ty = V->getType(); |
| 507 | if (NumSteps == 0) |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 508 | return SCEVUnknown::getIntegerSCEV(1, Ty); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 509 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 510 | SCEVHandle Result = V; |
| 511 | for (unsigned i = 1; i != NumSteps; ++i) |
Chris Lattner | bac5b46 | 2005-03-09 05:34:41 +0000 | [diff] [blame] | 512 | Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V, |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 513 | SCEVUnknown::getIntegerSCEV(i, Ty))); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 514 | return Result; |
| 515 | } |
| 516 | |
| 517 | |
| 518 | /// evaluateAtIteration - Return the value of this chain of recurrences at |
| 519 | /// the specified iteration number. We can evaluate this recurrence by |
| 520 | /// multiplying each element in the chain by the binomial coefficient |
| 521 | /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: |
| 522 | /// |
| 523 | /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3) |
| 524 | /// |
| 525 | /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow. |
| 526 | /// Is the binomial equation safe using modular arithmetic?? |
| 527 | /// |
| 528 | SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const { |
| 529 | SCEVHandle Result = getStart(); |
| 530 | int Divisor = 1; |
| 531 | const Type *Ty = It->getType(); |
| 532 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
| 533 | SCEVHandle BC = PartialFact(It, i); |
| 534 | Divisor *= i; |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 535 | SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)), |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 536 | SCEVUnknown::getIntegerSCEV(Divisor,Ty)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 537 | Result = SCEVAddExpr::get(Result, Val); |
| 538 | } |
| 539 | return Result; |
| 540 | } |
| 541 | |
| 542 | |
| 543 | //===----------------------------------------------------------------------===// |
| 544 | // SCEV Expression folder implementations |
| 545 | //===----------------------------------------------------------------------===// |
| 546 | |
| 547 | SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) { |
| 548 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Reid Spencer | 7858b33 | 2006-12-05 19:14:13 +0000 | [diff] [blame] | 549 | return SCEVUnknown::get( |
Reid Spencer | 315d055 | 2006-12-05 22:39:58 +0000 | [diff] [blame] | 550 | ConstantExpr::getTrunc(SC->getValue(), Ty)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 551 | |
| 552 | // If the input value is a chrec scev made out of constants, truncate |
| 553 | // all of the constants. |
| 554 | if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 555 | std::vector<SCEVHandle> Operands; |
| 556 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 557 | // FIXME: This should allow truncation of other expression types! |
| 558 | if (isa<SCEVConstant>(AddRec->getOperand(i))) |
| 559 | Operands.push_back(get(AddRec->getOperand(i), Ty)); |
| 560 | else |
| 561 | break; |
| 562 | if (Operands.size() == AddRec->getNumOperands()) |
| 563 | return SCEVAddRecExpr::get(Operands, AddRec->getLoop()); |
| 564 | } |
| 565 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 566 | SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 567 | if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); |
| 568 | return Result; |
| 569 | } |
| 570 | |
| 571 | SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) { |
| 572 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Reid Spencer | 7858b33 | 2006-12-05 19:14:13 +0000 | [diff] [blame] | 573 | return SCEVUnknown::get( |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 574 | ConstantExpr::getZExt(SC->getValue(), Ty)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 575 | |
| 576 | // FIXME: If the input value is a chrec scev, and we can prove that the value |
| 577 | // did not overflow the old, smaller, value, we can zero extend all of the |
| 578 | // operands (often constants). This would allow analysis of something like |
| 579 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
| 580 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 581 | SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 582 | if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); |
| 583 | return Result; |
| 584 | } |
| 585 | |
| 586 | // get - Get a canonical add expression, or something simpler if possible. |
| 587 | SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) { |
| 588 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 627018b | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 589 | if (Ops.size() == 1) return Ops[0]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 590 | |
| 591 | // Sort by complexity, this groups all similar expression types together. |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 592 | GroupByComplexity(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 593 | |
| 594 | // If there are any constants, fold them together. |
| 595 | unsigned Idx = 0; |
| 596 | if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
| 597 | ++Idx; |
Chris Lattner | 627018b | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 598 | assert(Idx < Ops.size()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 599 | while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
| 600 | // We found two constants, fold them together! |
| 601 | Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue()); |
| 602 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { |
| 603 | Ops[0] = SCEVConstant::get(CI); |
| 604 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 605 | if (Ops.size() == 1) return Ops[0]; |
Chris Lattner | 7ffc07d | 2005-02-26 18:50:19 +0000 | [diff] [blame] | 606 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 607 | } else { |
| 608 | // If we couldn't fold the expression, move to the next constant. Note |
| 609 | // that this is impossible to happen in practice because we always |
| 610 | // constant fold constant ints to constant ints. |
| 611 | ++Idx; |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | // If we are left with a constant zero being added, strip it off. |
| 616 | if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { |
| 617 | Ops.erase(Ops.begin()); |
| 618 | --Idx; |
| 619 | } |
| 620 | } |
| 621 | |
Chris Lattner | 627018b | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 622 | if (Ops.size() == 1) return Ops[0]; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 623 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 624 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 625 | // so, merge them together into an multiply expression. Since we sorted the |
| 626 | // list, these values are required to be adjacent. |
| 627 | const Type *Ty = Ops[0]->getType(); |
| 628 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
| 629 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
| 630 | // Found a match, merge the two values into a multiply, and add any |
| 631 | // remaining values to the result. |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 632 | SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 633 | SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two); |
| 634 | if (Ops.size() == 2) |
| 635 | return Mul; |
| 636 | Ops.erase(Ops.begin()+i, Ops.begin()+i+2); |
| 637 | Ops.push_back(Mul); |
| 638 | return SCEVAddExpr::get(Ops); |
| 639 | } |
| 640 | |
| 641 | // Okay, now we know the first non-constant operand. If there are add |
| 642 | // operands they would be next. |
| 643 | if (Idx < Ops.size()) { |
| 644 | bool DeletedAdd = false; |
| 645 | while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
| 646 | // If we have an add, expand the add operands onto the end of the operands |
| 647 | // list. |
| 648 | Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); |
| 649 | Ops.erase(Ops.begin()+Idx); |
| 650 | DeletedAdd = true; |
| 651 | } |
| 652 | |
| 653 | // If we deleted at least one add, we added operands to the end of the list, |
| 654 | // and they are not necessarily sorted. Recurse to resort and resimplify |
| 655 | // any operands we just aquired. |
| 656 | if (DeletedAdd) |
| 657 | return get(Ops); |
| 658 | } |
| 659 | |
| 660 | // Skip over the add expression until we get to a multiply. |
| 661 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 662 | ++Idx; |
| 663 | |
| 664 | // If we are adding something to a multiply expression, make sure the |
| 665 | // something is not already an operand of the multiply. If so, merge it into |
| 666 | // the multiply. |
| 667 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
| 668 | SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
| 669 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
| 670 | SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
| 671 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Chris Lattner | 6a1a78a | 2004-12-04 20:54:32 +0000 | [diff] [blame] | 672 | if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 673 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
| 674 | SCEVHandle InnerMul = Mul->getOperand(MulOp == 0); |
| 675 | if (Mul->getNumOperands() != 2) { |
| 676 | // If the multiply has more than two operands, we must get the |
| 677 | // Y*Z term. |
| 678 | std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); |
| 679 | MulOps.erase(MulOps.begin()+MulOp); |
| 680 | InnerMul = SCEVMulExpr::get(MulOps); |
| 681 | } |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 682 | SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 683 | SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One); |
| 684 | SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]); |
| 685 | if (Ops.size() == 2) return OuterMul; |
| 686 | if (AddOp < Idx) { |
| 687 | Ops.erase(Ops.begin()+AddOp); |
| 688 | Ops.erase(Ops.begin()+Idx-1); |
| 689 | } else { |
| 690 | Ops.erase(Ops.begin()+Idx); |
| 691 | Ops.erase(Ops.begin()+AddOp-1); |
| 692 | } |
| 693 | Ops.push_back(OuterMul); |
| 694 | return SCEVAddExpr::get(Ops); |
| 695 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 696 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 697 | // Check this multiply against other multiplies being added together. |
| 698 | for (unsigned OtherMulIdx = Idx+1; |
| 699 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 700 | ++OtherMulIdx) { |
| 701 | SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 702 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 703 | // together. |
| 704 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 705 | OMulOp != e; ++OMulOp) |
| 706 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 707 | // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) |
| 708 | SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0); |
| 709 | if (Mul->getNumOperands() != 2) { |
| 710 | std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); |
| 711 | MulOps.erase(MulOps.begin()+MulOp); |
| 712 | InnerMul1 = SCEVMulExpr::get(MulOps); |
| 713 | } |
| 714 | SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
| 715 | if (OtherMul->getNumOperands() != 2) { |
| 716 | std::vector<SCEVHandle> MulOps(OtherMul->op_begin(), |
| 717 | OtherMul->op_end()); |
| 718 | MulOps.erase(MulOps.begin()+OMulOp); |
| 719 | InnerMul2 = SCEVMulExpr::get(MulOps); |
| 720 | } |
| 721 | SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2); |
| 722 | SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum); |
| 723 | if (Ops.size() == 2) return OuterMul; |
| 724 | Ops.erase(Ops.begin()+Idx); |
| 725 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 726 | Ops.push_back(OuterMul); |
| 727 | return SCEVAddExpr::get(Ops); |
| 728 | } |
| 729 | } |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | // If there are any add recurrences in the operands list, see if any other |
| 734 | // added values are loop invariant. If so, we can fold them into the |
| 735 | // recurrence. |
| 736 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 737 | ++Idx; |
| 738 | |
| 739 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 740 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 741 | // Scan all of the other operands to this add and add them to the vector if |
| 742 | // they are loop invariant w.r.t. the recurrence. |
| 743 | std::vector<SCEVHandle> LIOps; |
| 744 | SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
| 745 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 746 | if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { |
| 747 | LIOps.push_back(Ops[i]); |
| 748 | Ops.erase(Ops.begin()+i); |
| 749 | --i; --e; |
| 750 | } |
| 751 | |
| 752 | // If we found some loop invariants, fold them into the recurrence. |
| 753 | if (!LIOps.empty()) { |
| 754 | // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step } |
| 755 | LIOps.push_back(AddRec->getStart()); |
| 756 | |
| 757 | std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); |
| 758 | AddRecOps[0] = SCEVAddExpr::get(LIOps); |
| 759 | |
| 760 | SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop()); |
| 761 | // If all of the other operands were loop invariant, we are done. |
| 762 | if (Ops.size() == 1) return NewRec; |
| 763 | |
| 764 | // Otherwise, add the folded AddRec by the non-liv parts. |
| 765 | for (unsigned i = 0;; ++i) |
| 766 | if (Ops[i] == AddRec) { |
| 767 | Ops[i] = NewRec; |
| 768 | break; |
| 769 | } |
| 770 | return SCEVAddExpr::get(Ops); |
| 771 | } |
| 772 | |
| 773 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 774 | // there are multiple AddRec's with the same loop induction variable being |
| 775 | // added together. If so, we can fold them. |
| 776 | for (unsigned OtherIdx = Idx+1; |
| 777 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) |
| 778 | if (OtherIdx != Idx) { |
| 779 | SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 780 | if (AddRec->getLoop() == OtherAddRec->getLoop()) { |
| 781 | // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} |
| 782 | std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end()); |
| 783 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { |
| 784 | if (i >= NewOps.size()) { |
| 785 | NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, |
| 786 | OtherAddRec->op_end()); |
| 787 | break; |
| 788 | } |
| 789 | NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i)); |
| 790 | } |
| 791 | SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); |
| 792 | |
| 793 | if (Ops.size() == 2) return NewAddRec; |
| 794 | |
| 795 | Ops.erase(Ops.begin()+Idx); |
| 796 | Ops.erase(Ops.begin()+OtherIdx-1); |
| 797 | Ops.push_back(NewAddRec); |
| 798 | return SCEVAddExpr::get(Ops); |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 803 | // next one. |
| 804 | } |
| 805 | |
| 806 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 807 | // already have one, otherwise create a new one. |
| 808 | std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 809 | SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr, |
| 810 | SCEVOps)]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 811 | if (Result == 0) Result = new SCEVAddExpr(Ops); |
| 812 | return Result; |
| 813 | } |
| 814 | |
| 815 | |
| 816 | SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) { |
| 817 | assert(!Ops.empty() && "Cannot get empty mul!"); |
| 818 | |
| 819 | // Sort by complexity, this groups all similar expression types together. |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 820 | GroupByComplexity(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 821 | |
| 822 | // If there are any constants, fold them together. |
| 823 | unsigned Idx = 0; |
| 824 | if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
| 825 | |
| 826 | // C1*(C2+V) -> C1*C2 + C1*V |
| 827 | if (Ops.size() == 2) |
| 828 | if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 829 | if (Add->getNumOperands() == 2 && |
| 830 | isa<SCEVConstant>(Add->getOperand(0))) |
| 831 | return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)), |
| 832 | SCEVMulExpr::get(LHSC, Add->getOperand(1))); |
| 833 | |
| 834 | |
| 835 | ++Idx; |
| 836 | while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
| 837 | // We found two constants, fold them together! |
| 838 | Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue()); |
| 839 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { |
| 840 | Ops[0] = SCEVConstant::get(CI); |
| 841 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 842 | if (Ops.size() == 1) return Ops[0]; |
Chris Lattner | 7ffc07d | 2005-02-26 18:50:19 +0000 | [diff] [blame] | 843 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 844 | } else { |
| 845 | // If we couldn't fold the expression, move to the next constant. Note |
| 846 | // that this is impossible to happen in practice because we always |
| 847 | // constant fold constant ints to constant ints. |
| 848 | ++Idx; |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | // If we are left with a constant one being multiplied, strip it off. |
| 853 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 854 | Ops.erase(Ops.begin()); |
| 855 | --Idx; |
| 856 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { |
| 857 | // If we have a multiply of zero, it will always be zero. |
| 858 | return Ops[0]; |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | // Skip over the add expression until we get to a multiply. |
| 863 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 864 | ++Idx; |
| 865 | |
| 866 | if (Ops.size() == 1) |
| 867 | return Ops[0]; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 868 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 869 | // If there are mul operands inline them all into this expression. |
| 870 | if (Idx < Ops.size()) { |
| 871 | bool DeletedMul = false; |
| 872 | while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
| 873 | // If we have an mul, expand the mul operands onto the end of the operands |
| 874 | // list. |
| 875 | Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); |
| 876 | Ops.erase(Ops.begin()+Idx); |
| 877 | DeletedMul = true; |
| 878 | } |
| 879 | |
| 880 | // If we deleted at least one mul, we added operands to the end of the list, |
| 881 | // and they are not necessarily sorted. Recurse to resort and resimplify |
| 882 | // any operands we just aquired. |
| 883 | if (DeletedMul) |
| 884 | return get(Ops); |
| 885 | } |
| 886 | |
| 887 | // If there are any add recurrences in the operands list, see if any other |
| 888 | // added values are loop invariant. If so, we can fold them into the |
| 889 | // recurrence. |
| 890 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 891 | ++Idx; |
| 892 | |
| 893 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 894 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 895 | // Scan all of the other operands to this mul and add them to the vector if |
| 896 | // they are loop invariant w.r.t. the recurrence. |
| 897 | std::vector<SCEVHandle> LIOps; |
| 898 | SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
| 899 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 900 | if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { |
| 901 | LIOps.push_back(Ops[i]); |
| 902 | Ops.erase(Ops.begin()+i); |
| 903 | --i; --e; |
| 904 | } |
| 905 | |
| 906 | // If we found some loop invariants, fold them into the recurrence. |
| 907 | if (!LIOps.empty()) { |
| 908 | // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step } |
| 909 | std::vector<SCEVHandle> NewOps; |
| 910 | NewOps.reserve(AddRec->getNumOperands()); |
| 911 | if (LIOps.size() == 1) { |
| 912 | SCEV *Scale = LIOps[0]; |
| 913 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 914 | NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i))); |
| 915 | } else { |
| 916 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 917 | std::vector<SCEVHandle> MulOps(LIOps); |
| 918 | MulOps.push_back(AddRec->getOperand(i)); |
| 919 | NewOps.push_back(SCEVMulExpr::get(MulOps)); |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); |
| 924 | |
| 925 | // If all of the other operands were loop invariant, we are done. |
| 926 | if (Ops.size() == 1) return NewRec; |
| 927 | |
| 928 | // Otherwise, multiply the folded AddRec by the non-liv parts. |
| 929 | for (unsigned i = 0;; ++i) |
| 930 | if (Ops[i] == AddRec) { |
| 931 | Ops[i] = NewRec; |
| 932 | break; |
| 933 | } |
| 934 | return SCEVMulExpr::get(Ops); |
| 935 | } |
| 936 | |
| 937 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 938 | // there are multiple AddRec's with the same loop induction variable being |
| 939 | // multiplied together. If so, we can fold them. |
| 940 | for (unsigned OtherIdx = Idx+1; |
| 941 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) |
| 942 | if (OtherIdx != Idx) { |
| 943 | SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 944 | if (AddRec->getLoop() == OtherAddRec->getLoop()) { |
| 945 | // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} |
| 946 | SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; |
| 947 | SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(), |
| 948 | G->getStart()); |
| 949 | SCEVHandle B = F->getStepRecurrence(); |
| 950 | SCEVHandle D = G->getStepRecurrence(); |
| 951 | SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D), |
| 952 | SCEVMulExpr::get(G, B), |
| 953 | SCEVMulExpr::get(B, D)); |
| 954 | SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep, |
| 955 | F->getLoop()); |
| 956 | if (Ops.size() == 2) return NewAddRec; |
| 957 | |
| 958 | Ops.erase(Ops.begin()+Idx); |
| 959 | Ops.erase(Ops.begin()+OtherIdx-1); |
| 960 | Ops.push_back(NewAddRec); |
| 961 | return SCEVMulExpr::get(Ops); |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 966 | // next one. |
| 967 | } |
| 968 | |
| 969 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 970 | // already have one, otherwise create a new one. |
| 971 | std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 972 | SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr, |
| 973 | SCEVOps)]; |
Chris Lattner | 6a1a78a | 2004-12-04 20:54:32 +0000 | [diff] [blame] | 974 | if (Result == 0) |
| 975 | Result = new SCEVMulExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 976 | return Result; |
| 977 | } |
| 978 | |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 979 | SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 980 | if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 981 | if (RHSC->getValue()->equalsInt(1)) |
Reid Spencer | 1628cec | 2006-10-26 06:15:43 +0000 | [diff] [blame] | 982 | return LHS; // X sdiv 1 --> x |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 983 | if (RHSC->getValue()->isAllOnesValue()) |
Reid Spencer | 1628cec | 2006-10-26 06:15:43 +0000 | [diff] [blame] | 984 | return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 985 | |
| 986 | if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 987 | Constant *LHSCV = LHSC->getValue(); |
| 988 | Constant *RHSCV = RHSC->getValue(); |
Reid Spencer | 1628cec | 2006-10-26 06:15:43 +0000 | [diff] [blame] | 989 | return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 990 | } |
| 991 | } |
| 992 | |
| 993 | // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow. |
| 994 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 995 | SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)]; |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 996 | if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 997 | return Result; |
| 998 | } |
| 999 | |
| 1000 | |
| 1001 | /// SCEVAddRecExpr::get - Get a add recurrence expression for the |
| 1002 | /// specified loop. Simplify the expression as much as possible. |
| 1003 | SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start, |
| 1004 | const SCEVHandle &Step, const Loop *L) { |
| 1005 | std::vector<SCEVHandle> Operands; |
| 1006 | Operands.push_back(Start); |
| 1007 | if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
| 1008 | if (StepChrec->getLoop() == L) { |
| 1009 | Operands.insert(Operands.end(), StepChrec->op_begin(), |
| 1010 | StepChrec->op_end()); |
| 1011 | return get(Operands, L); |
| 1012 | } |
| 1013 | |
| 1014 | Operands.push_back(Step); |
| 1015 | return get(Operands, L); |
| 1016 | } |
| 1017 | |
| 1018 | /// SCEVAddRecExpr::get - Get a add recurrence expression for the |
| 1019 | /// specified loop. Simplify the expression as much as possible. |
| 1020 | SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands, |
| 1021 | const Loop *L) { |
| 1022 | if (Operands.size() == 1) return Operands[0]; |
| 1023 | |
| 1024 | if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back())) |
| 1025 | if (StepC->getValue()->isNullValue()) { |
| 1026 | Operands.pop_back(); |
| 1027 | return get(Operands, L); // { X,+,0 } --> X |
| 1028 | } |
| 1029 | |
| 1030 | SCEVAddRecExpr *&Result = |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 1031 | (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(), |
| 1032 | Operands.end()))]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1033 | if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); |
| 1034 | return Result; |
| 1035 | } |
| 1036 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 1037 | SCEVHandle SCEVUnknown::get(Value *V) { |
| 1038 | if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
| 1039 | return SCEVConstant::get(CI); |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 1040 | SCEVUnknown *&Result = (*SCEVUnknowns)[V]; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 1041 | if (Result == 0) Result = new SCEVUnknown(V); |
| 1042 | return Result; |
| 1043 | } |
| 1044 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1045 | |
| 1046 | //===----------------------------------------------------------------------===// |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1047 | // ScalarEvolutionsImpl Definition and Implementation |
| 1048 | //===----------------------------------------------------------------------===// |
| 1049 | // |
| 1050 | /// ScalarEvolutionsImpl - This class implements the main driver for the scalar |
| 1051 | /// evolution code. |
| 1052 | /// |
| 1053 | namespace { |
Chris Lattner | 9525528 | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 1054 | struct VISIBILITY_HIDDEN ScalarEvolutionsImpl { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1055 | /// F - The function we are analyzing. |
| 1056 | /// |
| 1057 | Function &F; |
| 1058 | |
| 1059 | /// LI - The loop information for the function we are currently analyzing. |
| 1060 | /// |
| 1061 | LoopInfo &LI; |
| 1062 | |
| 1063 | /// UnknownValue - This SCEV is used to represent unknown trip counts and |
| 1064 | /// things. |
| 1065 | SCEVHandle UnknownValue; |
| 1066 | |
| 1067 | /// Scalars - This is a cache of the scalars we have analyzed so far. |
| 1068 | /// |
| 1069 | std::map<Value*, SCEVHandle> Scalars; |
| 1070 | |
| 1071 | /// IterationCounts - Cache the iteration count of the loops for this |
| 1072 | /// function as they are computed. |
| 1073 | std::map<const Loop*, SCEVHandle> IterationCounts; |
| 1074 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1075 | /// ConstantEvolutionLoopExitValue - This map contains entries for all of |
| 1076 | /// the PHI instructions that we attempt to compute constant evolutions for. |
| 1077 | /// This allows us to avoid potentially expensive recomputation of these |
| 1078 | /// properties. An instruction maps to null if we are unable to compute its |
| 1079 | /// exit value. |
| 1080 | std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1081 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1082 | public: |
| 1083 | ScalarEvolutionsImpl(Function &f, LoopInfo &li) |
| 1084 | : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {} |
| 1085 | |
| 1086 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 1087 | /// expression and create a new one. |
| 1088 | SCEVHandle getSCEV(Value *V); |
| 1089 | |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 1090 | /// hasSCEV - Return true if the SCEV for this value has already been |
| 1091 | /// computed. |
| 1092 | bool hasSCEV(Value *V) const { |
| 1093 | return Scalars.count(V); |
| 1094 | } |
| 1095 | |
| 1096 | /// setSCEV - Insert the specified SCEV into the map of current SCEVs for |
| 1097 | /// the specified value. |
| 1098 | void setSCEV(Value *V, const SCEVHandle &H) { |
| 1099 | bool isNew = Scalars.insert(std::make_pair(V, H)).second; |
| 1100 | assert(isNew && "This entry already existed!"); |
| 1101 | } |
| 1102 | |
| 1103 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1104 | /// getSCEVAtScope - Compute the value of the specified expression within |
| 1105 | /// the indicated loop (which may be null to indicate in no loop). If the |
| 1106 | /// expression cannot be evaluated, return UnknownValue itself. |
| 1107 | SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L); |
| 1108 | |
| 1109 | |
| 1110 | /// hasLoopInvariantIterationCount - Return true if the specified loop has |
| 1111 | /// an analyzable loop-invariant iteration count. |
| 1112 | bool hasLoopInvariantIterationCount(const Loop *L); |
| 1113 | |
| 1114 | /// getIterationCount - If the specified loop has a predictable iteration |
| 1115 | /// count, return it. Note that it is not valid to call this method on a |
| 1116 | /// loop without a loop-invariant iteration count. |
| 1117 | SCEVHandle getIterationCount(const Loop *L); |
| 1118 | |
| 1119 | /// deleteInstructionFromRecords - This method should be called by the |
| 1120 | /// client before it removes an instruction from the program, to make sure |
| 1121 | /// that no dangling references are left around. |
| 1122 | void deleteInstructionFromRecords(Instruction *I); |
| 1123 | |
| 1124 | private: |
| 1125 | /// createSCEV - We know that there is no SCEV for the specified value. |
| 1126 | /// Analyze the expression. |
| 1127 | SCEVHandle createSCEV(Value *V); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1128 | |
| 1129 | /// createNodeForPHI - Provide the special handling we need to analyze PHI |
| 1130 | /// SCEVs. |
| 1131 | SCEVHandle createNodeForPHI(PHINode *PN); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1132 | |
| 1133 | /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value |
| 1134 | /// for the specified instruction and replaces any references to the |
| 1135 | /// symbolic value SymName with the specified value. This is used during |
| 1136 | /// PHI resolution. |
| 1137 | void ReplaceSymbolicValueWithConcrete(Instruction *I, |
| 1138 | const SCEVHandle &SymName, |
| 1139 | const SCEVHandle &NewVal); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1140 | |
| 1141 | /// ComputeIterationCount - Compute the number of times the specified loop |
| 1142 | /// will iterate. |
| 1143 | SCEVHandle ComputeIterationCount(const Loop *L); |
| 1144 | |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1145 | /// ComputeLoadConstantCompareIterationCount - Given an exit condition of |
| 1146 | /// 'setcc load X, cst', try to se if we can compute the trip count. |
| 1147 | SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI, |
| 1148 | Constant *RHS, |
| 1149 | const Loop *L, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1150 | ICmpInst::Predicate p); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1151 | |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1152 | /// ComputeIterationCountExhaustively - If the trip is known to execute a |
| 1153 | /// constant number of times (the condition evolves only from constants), |
| 1154 | /// try to evaluate a few iterations of the loop until we get the exit |
| 1155 | /// condition gets a value of ExitWhen (true or false). If we cannot |
| 1156 | /// evaluate the trip count of the loop, return UnknownValue. |
| 1157 | SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond, |
| 1158 | bool ExitWhen); |
| 1159 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1160 | /// HowFarToZero - Return the number of times a backedge comparing the |
| 1161 | /// specified value to zero will execute. If not computable, return |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1162 | /// UnknownValue. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1163 | SCEVHandle HowFarToZero(SCEV *V, const Loop *L); |
| 1164 | |
| 1165 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 1166 | /// specified value for nonzero will execute. If not computable, return |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1167 | /// UnknownValue. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1168 | SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1169 | |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1170 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 1171 | /// specified less-than comparison will execute. If not computable, return |
| 1172 | /// UnknownValue. |
| 1173 | SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L); |
| 1174 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1175 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 1176 | /// in the header of its containing loop, we know the loop executes a |
| 1177 | /// constant number of times, and the PHI node is just a recurrence |
| 1178 | /// involving constants, fold it. |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1179 | Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1180 | const Loop *L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1181 | }; |
| 1182 | } |
| 1183 | |
| 1184 | //===----------------------------------------------------------------------===// |
| 1185 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 1186 | // |
| 1187 | |
| 1188 | /// deleteInstructionFromRecords - This method should be called by the |
| 1189 | /// client before it removes an instruction from the program, to make sure |
| 1190 | /// that no dangling references are left around. |
| 1191 | void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) { |
| 1192 | Scalars.erase(I); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1193 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 1194 | ConstantEvolutionLoopExitValue.erase(PN); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1195 | } |
| 1196 | |
| 1197 | |
| 1198 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 1199 | /// expression and create a new one. |
| 1200 | SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) { |
| 1201 | assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!"); |
| 1202 | |
| 1203 | std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); |
| 1204 | if (I != Scalars.end()) return I->second; |
| 1205 | SCEVHandle S = createSCEV(V); |
| 1206 | Scalars.insert(std::make_pair(V, S)); |
| 1207 | return S; |
| 1208 | } |
| 1209 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1210 | /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for |
| 1211 | /// the specified instruction and replaces any references to the symbolic value |
| 1212 | /// SymName with the specified value. This is used during PHI resolution. |
| 1213 | void ScalarEvolutionsImpl:: |
| 1214 | ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, |
| 1215 | const SCEVHandle &NewVal) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1216 | std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1217 | if (SI == Scalars.end()) return; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1218 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1219 | SCEVHandle NV = |
| 1220 | SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal); |
| 1221 | if (NV == SI->second) return; // No change. |
| 1222 | |
| 1223 | SI->second = NV; // Update the scalars map! |
| 1224 | |
| 1225 | // Any instruction values that use this instruction might also need to be |
| 1226 | // updated! |
| 1227 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); |
| 1228 | UI != E; ++UI) |
| 1229 | ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); |
| 1230 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1231 | |
| 1232 | /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in |
| 1233 | /// a loop header, making it a potential recurrence, or it doesn't. |
| 1234 | /// |
| 1235 | SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) { |
| 1236 | if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. |
| 1237 | if (const Loop *L = LI.getLoopFor(PN->getParent())) |
| 1238 | if (L->getHeader() == PN->getParent()) { |
| 1239 | // If it lives in the loop header, it has two incoming values, one |
| 1240 | // from outside the loop, and one from inside. |
| 1241 | unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); |
| 1242 | unsigned BackEdge = IncomingEdge^1; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1243 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1244 | // While we are analyzing this PHI node, handle its value symbolically. |
| 1245 | SCEVHandle SymbolicName = SCEVUnknown::get(PN); |
| 1246 | assert(Scalars.find(PN) == Scalars.end() && |
| 1247 | "PHI node already processed?"); |
| 1248 | Scalars.insert(std::make_pair(PN, SymbolicName)); |
| 1249 | |
| 1250 | // Using this symbolic name for the PHI, analyze the value coming around |
| 1251 | // the back-edge. |
| 1252 | SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); |
| 1253 | |
| 1254 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 1255 | // has a special value for the first iteration of the loop. |
| 1256 | |
| 1257 | // If the value coming around the backedge is an add with the symbolic |
| 1258 | // value we just inserted, then we found a simple induction variable! |
| 1259 | if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 1260 | // If there is a single occurrence of the symbolic value, replace it |
| 1261 | // with a recurrence. |
| 1262 | unsigned FoundIndex = Add->getNumOperands(); |
| 1263 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 1264 | if (Add->getOperand(i) == SymbolicName) |
| 1265 | if (FoundIndex == e) { |
| 1266 | FoundIndex = i; |
| 1267 | break; |
| 1268 | } |
| 1269 | |
| 1270 | if (FoundIndex != Add->getNumOperands()) { |
| 1271 | // Create an add with everything but the specified operand. |
| 1272 | std::vector<SCEVHandle> Ops; |
| 1273 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 1274 | if (i != FoundIndex) |
| 1275 | Ops.push_back(Add->getOperand(i)); |
| 1276 | SCEVHandle Accum = SCEVAddExpr::get(Ops); |
| 1277 | |
| 1278 | // This is not a valid addrec if the step amount is varying each |
| 1279 | // loop iteration, but is not itself an addrec in this loop. |
| 1280 | if (Accum->isLoopInvariant(L) || |
| 1281 | (isa<SCEVAddRecExpr>(Accum) && |
| 1282 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 1283 | SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); |
| 1284 | SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L); |
| 1285 | |
| 1286 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 1287 | // to be symbolic. We now need to go back and update all of the |
| 1288 | // entries for the scalars that use the PHI (except for the PHI |
| 1289 | // itself) to use the new analyzed value instead of the "symbolic" |
| 1290 | // value. |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1291 | ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1292 | return PHISCEV; |
| 1293 | } |
| 1294 | } |
Chris Lattner | 97156e7 | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 1295 | } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) { |
| 1296 | // Otherwise, this could be a loop like this: |
| 1297 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 1298 | // In this case, j = {1,+,1} and BEValue is j. |
| 1299 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 1300 | // i really is an addrec evolution. |
| 1301 | if (AddRec->getLoop() == L && AddRec->isAffine()) { |
| 1302 | SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); |
| 1303 | |
| 1304 | // If StartVal = j.start - j.stride, we can use StartVal as the |
| 1305 | // initial step of the addrec evolution. |
| 1306 | if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0), |
| 1307 | AddRec->getOperand(1))) { |
| 1308 | SCEVHandle PHISCEV = |
| 1309 | SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L); |
| 1310 | |
| 1311 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 1312 | // to be symbolic. We now need to go back and update all of the |
| 1313 | // entries for the scalars that use the PHI (except for the PHI |
| 1314 | // itself) to use the new analyzed value instead of the "symbolic" |
| 1315 | // value. |
| 1316 | ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); |
| 1317 | return PHISCEV; |
| 1318 | } |
| 1319 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1320 | } |
| 1321 | |
| 1322 | return SymbolicName; |
| 1323 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1324 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1325 | // If it's not a loop phi, we can't handle it yet. |
| 1326 | return SCEVUnknown::get(PN); |
| 1327 | } |
| 1328 | |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1329 | /// GetConstantFactor - Determine the largest constant factor that S has. For |
| 1330 | /// example, turn {4,+,8} -> 4. (S umod result) should always equal zero. |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1331 | static APInt GetConstantFactor(SCEVHandle S) { |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1332 | if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1333 | APInt V = C->getValue()->getValue(); |
| 1334 | if (!V.isMinValue()) |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1335 | return V; |
| 1336 | else // Zero is a multiple of everything. |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1337 | return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1338 | } |
| 1339 | |
| 1340 | if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
| 1341 | return GetConstantFactor(T->getOperand()) & |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1342 | cast<IntegerType>(T->getType())->getMask(); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1343 | if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) |
| 1344 | return GetConstantFactor(E->getOperand()); |
| 1345 | |
| 1346 | if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
| 1347 | // The result is the min of all operands. |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1348 | APInt Res = GetConstantFactor(A->getOperand(0)); |
| 1349 | for (unsigned i = 1, e = A->getNumOperands(); |
| 1350 | i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) |
| 1351 | Res = APIntOps::umin(Res, GetConstantFactor(A->getOperand(i))); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1352 | return Res; |
| 1353 | } |
| 1354 | |
| 1355 | if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
| 1356 | // The result is the product of all the operands. |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1357 | APInt Res = GetConstantFactor(M->getOperand(0)); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1358 | for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) |
| 1359 | Res *= GetConstantFactor(M->getOperand(i)); |
| 1360 | return Res; |
| 1361 | } |
| 1362 | |
| 1363 | if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Chris Lattner | 75de5ab | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 1364 | // For now, we just handle linear expressions. |
| 1365 | if (A->getNumOperands() == 2) { |
| 1366 | // We want the GCD between the start and the stride value. |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1367 | APInt Start = GetConstantFactor(A->getOperand(0)); |
| 1368 | if (Start == 1) |
| 1369 | return APInt(A->getBitWidth(),1); |
| 1370 | APInt Stride = GetConstantFactor(A->getOperand(1)); |
| 1371 | return APIntOps::GreatestCommonDivisor(Start, Stride); |
Chris Lattner | 75de5ab | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 1372 | } |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1373 | } |
| 1374 | |
| 1375 | // SCEVSDivExpr, SCEVUnknown. |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1376 | return APInt(S->getBitWidth(), 1); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1377 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1378 | |
| 1379 | /// createSCEV - We know that there is no SCEV for the specified value. |
| 1380 | /// Analyze the expression. |
| 1381 | /// |
| 1382 | SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) { |
| 1383 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 1384 | switch (I->getOpcode()) { |
| 1385 | case Instruction::Add: |
| 1386 | return SCEVAddExpr::get(getSCEV(I->getOperand(0)), |
| 1387 | getSCEV(I->getOperand(1))); |
| 1388 | case Instruction::Mul: |
| 1389 | return SCEVMulExpr::get(getSCEV(I->getOperand(0)), |
| 1390 | getSCEV(I->getOperand(1))); |
Reid Spencer | 1628cec | 2006-10-26 06:15:43 +0000 | [diff] [blame] | 1391 | case Instruction::SDiv: |
| 1392 | return SCEVSDivExpr::get(getSCEV(I->getOperand(0)), |
| 1393 | getSCEV(I->getOperand(1))); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1394 | break; |
| 1395 | |
| 1396 | case Instruction::Sub: |
Chris Lattner | bac5b46 | 2005-03-09 05:34:41 +0000 | [diff] [blame] | 1397 | return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)), |
| 1398 | getSCEV(I->getOperand(1))); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1399 | case Instruction::Or: |
| 1400 | // If the RHS of the Or is a constant, we may have something like: |
| 1401 | // X*4+1 which got turned into X*4|1. Handle this as an add so loop |
| 1402 | // optimizations will transparently handle this case. |
| 1403 | if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 1404 | SCEVHandle LHS = getSCEV(I->getOperand(0)); |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1405 | APInt CommonFact = GetConstantFactor(LHS); |
| 1406 | assert(!CommonFact.isMinValue() && |
| 1407 | "Common factor should at least be 1!"); |
Reid Spencer | e479ef0 | 2007-03-01 17:17:21 +0000 | [diff] [blame] | 1408 | CommonFact.zextOrTrunc(CI->getValue().getBitWidth()); |
Reid Spencer | 6263cba | 2007-02-28 23:31:17 +0000 | [diff] [blame] | 1409 | if (CommonFact.ugt(CI->getValue())) { |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1410 | // If the LHS is a multiple that is larger than the RHS, use +. |
| 1411 | return SCEVAddExpr::get(LHS, |
| 1412 | getSCEV(I->getOperand(1))); |
| 1413 | } |
| 1414 | } |
| 1415 | break; |
| 1416 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1417 | case Instruction::Shl: |
| 1418 | // Turn shift left of a constant amount into a multiply. |
| 1419 | if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 1420 | Constant *X = ConstantInt::get(V->getType(), 1); |
| 1421 | X = ConstantExpr::getShl(X, SA); |
| 1422 | return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X)); |
| 1423 | } |
| 1424 | break; |
| 1425 | |
Reid Spencer | 3da59db | 2006-11-27 01:05:10 +0000 | [diff] [blame] | 1426 | case Instruction::Trunc: |
Chris Lattner | b2f3e70 | 2007-01-15 01:58:56 +0000 | [diff] [blame] | 1427 | return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType()); |
Reid Spencer | 3da59db | 2006-11-27 01:05:10 +0000 | [diff] [blame] | 1428 | |
| 1429 | case Instruction::ZExt: |
Chris Lattner | b2f3e70 | 2007-01-15 01:58:56 +0000 | [diff] [blame] | 1430 | return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType()); |
Reid Spencer | 3da59db | 2006-11-27 01:05:10 +0000 | [diff] [blame] | 1431 | |
| 1432 | case Instruction::BitCast: |
| 1433 | // BitCasts are no-op casts so we just eliminate the cast. |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 1434 | if (I->getType()->isInteger() && |
| 1435 | I->getOperand(0)->getType()->isInteger()) |
Chris Lattner | 82e8a8f | 2006-12-11 00:12:31 +0000 | [diff] [blame] | 1436 | return getSCEV(I->getOperand(0)); |
| 1437 | break; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1438 | |
| 1439 | case Instruction::PHI: |
| 1440 | return createNodeForPHI(cast<PHINode>(I)); |
| 1441 | |
| 1442 | default: // We cannot analyze this expression. |
| 1443 | break; |
| 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | return SCEVUnknown::get(V); |
| 1448 | } |
| 1449 | |
| 1450 | |
| 1451 | |
| 1452 | //===----------------------------------------------------------------------===// |
| 1453 | // Iteration Count Computation Code |
| 1454 | // |
| 1455 | |
| 1456 | /// getIterationCount - If the specified loop has a predictable iteration |
| 1457 | /// count, return it. Note that it is not valid to call this method on a |
| 1458 | /// loop without a loop-invariant iteration count. |
| 1459 | SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) { |
| 1460 | std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L); |
| 1461 | if (I == IterationCounts.end()) { |
| 1462 | SCEVHandle ItCount = ComputeIterationCount(L); |
| 1463 | I = IterationCounts.insert(std::make_pair(L, ItCount)).first; |
| 1464 | if (ItCount != UnknownValue) { |
| 1465 | assert(ItCount->isLoopInvariant(L) && |
| 1466 | "Computed trip count isn't loop invariant for loop!"); |
| 1467 | ++NumTripCountsComputed; |
| 1468 | } else if (isa<PHINode>(L->getHeader()->begin())) { |
| 1469 | // Only count loops that have phi nodes as not being computable. |
| 1470 | ++NumTripCountsNotComputed; |
| 1471 | } |
| 1472 | } |
| 1473 | return I->second; |
| 1474 | } |
| 1475 | |
| 1476 | /// ComputeIterationCount - Compute the number of times the specified loop |
| 1477 | /// will iterate. |
| 1478 | SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) { |
| 1479 | // If the loop has a non-one exit block count, we can't analyze it. |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 1480 | std::vector<BasicBlock*> ExitBlocks; |
| 1481 | L->getExitBlocks(ExitBlocks); |
| 1482 | if (ExitBlocks.size() != 1) return UnknownValue; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1483 | |
| 1484 | // Okay, there is one exit block. Try to find the condition that causes the |
| 1485 | // loop to be exited. |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 1486 | BasicBlock *ExitBlock = ExitBlocks[0]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1487 | |
| 1488 | BasicBlock *ExitingBlock = 0; |
| 1489 | for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); |
| 1490 | PI != E; ++PI) |
| 1491 | if (L->contains(*PI)) { |
| 1492 | if (ExitingBlock == 0) |
| 1493 | ExitingBlock = *PI; |
| 1494 | else |
| 1495 | return UnknownValue; // More than one block exiting! |
| 1496 | } |
| 1497 | assert(ExitingBlock && "No exits from loop, something is broken!"); |
| 1498 | |
| 1499 | // Okay, we've computed the exiting block. See what condition causes us to |
| 1500 | // exit. |
| 1501 | // |
| 1502 | // FIXME: we should be able to handle switch instructions (with a single exit) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1503 | BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); |
| 1504 | if (ExitBr == 0) return UnknownValue; |
| 1505 | assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1506 | |
| 1507 | // At this point, we know we have a conditional branch that determines whether |
| 1508 | // the loop is exited. However, we don't know if the branch is executed each |
| 1509 | // time through the loop. If not, then the execution count of the branch will |
| 1510 | // not be equal to the trip count of the loop. |
| 1511 | // |
| 1512 | // Currently we check for this by checking to see if the Exit branch goes to |
| 1513 | // the loop header. If so, we know it will always execute the same number of |
Chris Lattner | 192e403 | 2007-01-14 01:24:47 +0000 | [diff] [blame] | 1514 | // times as the loop. We also handle the case where the exit block *is* the |
| 1515 | // loop header. This is common for un-rotated loops. More extensive analysis |
| 1516 | // could be done to handle more cases here. |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1517 | if (ExitBr->getSuccessor(0) != L->getHeader() && |
Chris Lattner | 192e403 | 2007-01-14 01:24:47 +0000 | [diff] [blame] | 1518 | ExitBr->getSuccessor(1) != L->getHeader() && |
| 1519 | ExitBr->getParent() != L->getHeader()) |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1520 | return UnknownValue; |
| 1521 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1522 | ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition()); |
| 1523 | |
| 1524 | // If its not an integer comparison then compute it the hard way. |
| 1525 | // Note that ICmpInst deals with pointer comparisons too so we must check |
| 1526 | // the type of the operand. |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1527 | if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType())) |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1528 | return ComputeIterationCountExhaustively(L, ExitBr->getCondition(), |
| 1529 | ExitBr->getSuccessor(0) == ExitBlock); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1530 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1531 | // If the condition was exit on true, convert the condition to exit on false |
| 1532 | ICmpInst::Predicate Cond; |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1533 | if (ExitBr->getSuccessor(1) == ExitBlock) |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1534 | Cond = ExitCond->getPredicate(); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1535 | else |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1536 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1537 | |
| 1538 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 1539 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 1540 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
| 1541 | SCEVHandle ItCnt = |
| 1542 | ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond); |
| 1543 | if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; |
| 1544 | } |
| 1545 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1546 | SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); |
| 1547 | SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); |
| 1548 | |
| 1549 | // Try to evaluate any dependencies out of the loop. |
| 1550 | SCEVHandle Tmp = getSCEVAtScope(LHS, L); |
| 1551 | if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; |
| 1552 | Tmp = getSCEVAtScope(RHS, L); |
| 1553 | if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; |
| 1554 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1555 | // At this point, we would like to compute how many iterations of the |
| 1556 | // loop the predicate will return true for these inputs. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1557 | if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) { |
| 1558 | // If there is a constant, force it into the RHS. |
| 1559 | std::swap(LHS, RHS); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1560 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1561 | } |
| 1562 | |
| 1563 | // FIXME: think about handling pointer comparisons! i.e.: |
| 1564 | // while (P != P+100) ++P; |
| 1565 | |
| 1566 | // If we have a comparison of a chrec against a constant, try to use value |
| 1567 | // ranges to answer this query. |
| 1568 | if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 1569 | if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 1570 | if (AddRec->getLoop() == L) { |
| 1571 | // Form the comparison range using the constant of the correct type so |
| 1572 | // that the ConstantRange class knows to do a signed or unsigned |
| 1573 | // comparison. |
| 1574 | ConstantInt *CompVal = RHSC->getValue(); |
| 1575 | const Type *RealTy = ExitCond->getOperand(0)->getType(); |
Reid Spencer | 4da4912 | 2006-12-12 05:05:00 +0000 | [diff] [blame] | 1576 | CompVal = dyn_cast<ConstantInt>( |
Reid Spencer | b6ba3e6 | 2006-12-12 09:17:50 +0000 | [diff] [blame] | 1577 | ConstantExpr::getBitCast(CompVal, RealTy)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1578 | if (CompVal) { |
| 1579 | // Form the constant range. |
Reid Spencer | c6aedf7 | 2007-02-28 22:03:51 +0000 | [diff] [blame] | 1580 | ConstantRange CompRange( |
| 1581 | ICmpInst::makeConstantRange(Cond, CompVal->getValue())); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1582 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1583 | SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 1584 | false /*Always treat as unsigned range*/); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1585 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
| 1586 | } |
| 1587 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1588 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1589 | switch (Cond) { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1590 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1591 | // Convert to: while (X-Y != 0) |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1592 | SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L); |
| 1593 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1594 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1595 | } |
| 1596 | case ICmpInst::ICMP_EQ: { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1597 | // Convert to: while (X-Y == 0) // while (X == Y) |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1598 | SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L); |
| 1599 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1600 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1601 | } |
| 1602 | case ICmpInst::ICMP_SLT: { |
| 1603 | SCEVHandle TC = HowManyLessThans(LHS, RHS, L); |
| 1604 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1605 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1606 | } |
| 1607 | case ICmpInst::ICMP_SGT: { |
| 1608 | SCEVHandle TC = HowManyLessThans(RHS, LHS, L); |
| 1609 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1610 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1611 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1612 | default: |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 1613 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1614 | cerr << "ComputeIterationCount "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1615 | if (ExitCond->getOperand(0)->getType()->isUnsigned()) |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1616 | cerr << "[unsigned] "; |
| 1617 | cerr << *LHS << " " |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1618 | << Instruction::getOpcodeName(Instruction::ICmp) |
| 1619 | << " " << *RHS << "\n"; |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 1620 | #endif |
Chris Lattner | e34c0b4 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 1621 | break; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1622 | } |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1623 | return ComputeIterationCountExhaustively(L, ExitCond, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1624 | ExitBr->getSuccessor(0) == ExitBlock); |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1625 | } |
| 1626 | |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1627 | static ConstantInt * |
| 1628 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) { |
| 1629 | SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C)); |
| 1630 | SCEVHandle Val = AddRec->evaluateAtIteration(InVal); |
| 1631 | assert(isa<SCEVConstant>(Val) && |
| 1632 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 1633 | return cast<SCEVConstant>(Val)->getValue(); |
| 1634 | } |
| 1635 | |
| 1636 | /// GetAddressedElementFromGlobal - Given a global variable with an initializer |
| 1637 | /// and a GEP expression (missing the pointer index) indexing into it, return |
| 1638 | /// the addressed element of the initializer or null if the index expression is |
| 1639 | /// invalid. |
| 1640 | static Constant * |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1641 | GetAddressedElementFromGlobal(GlobalVariable *GV, |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1642 | const std::vector<ConstantInt*> &Indices) { |
| 1643 | Constant *Init = GV->getInitializer(); |
| 1644 | for (unsigned i = 0, e = Indices.size(); i != e; ++i) { |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 1645 | uint64_t Idx = Indices[i]->getZExtValue(); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1646 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { |
| 1647 | assert(Idx < CS->getNumOperands() && "Bad struct index!"); |
| 1648 | Init = cast<Constant>(CS->getOperand(Idx)); |
| 1649 | } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { |
| 1650 | if (Idx >= CA->getNumOperands()) return 0; // Bogus program |
| 1651 | Init = cast<Constant>(CA->getOperand(Idx)); |
| 1652 | } else if (isa<ConstantAggregateZero>(Init)) { |
| 1653 | if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { |
| 1654 | assert(Idx < STy->getNumElements() && "Bad struct index!"); |
| 1655 | Init = Constant::getNullValue(STy->getElementType(Idx)); |
| 1656 | } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { |
| 1657 | if (Idx >= ATy->getNumElements()) return 0; // Bogus program |
| 1658 | Init = Constant::getNullValue(ATy->getElementType()); |
| 1659 | } else { |
| 1660 | assert(0 && "Unknown constant aggregate type!"); |
| 1661 | } |
| 1662 | return 0; |
| 1663 | } else { |
| 1664 | return 0; // Unknown initializer type |
| 1665 | } |
| 1666 | } |
| 1667 | return Init; |
| 1668 | } |
| 1669 | |
| 1670 | /// ComputeLoadConstantCompareIterationCount - Given an exit condition of |
| 1671 | /// 'setcc load X, cst', try to se if we can compute the trip count. |
| 1672 | SCEVHandle ScalarEvolutionsImpl:: |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1673 | ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1674 | const Loop *L, |
| 1675 | ICmpInst::Predicate predicate) { |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1676 | if (LI->isVolatile()) return UnknownValue; |
| 1677 | |
| 1678 | // Check to see if the loaded pointer is a getelementptr of a global. |
| 1679 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
| 1680 | if (!GEP) return UnknownValue; |
| 1681 | |
| 1682 | // Make sure that it is really a constant global we are gepping, with an |
| 1683 | // initializer, and make sure the first IDX is really 0. |
| 1684 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
| 1685 | if (!GV || !GV->isConstant() || !GV->hasInitializer() || |
| 1686 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 1687 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
| 1688 | return UnknownValue; |
| 1689 | |
| 1690 | // Okay, we allow one non-constant index into the GEP instruction. |
| 1691 | Value *VarIdx = 0; |
| 1692 | std::vector<ConstantInt*> Indexes; |
| 1693 | unsigned VarIdxNum = 0; |
| 1694 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 1695 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 1696 | Indexes.push_back(CI); |
| 1697 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
| 1698 | if (VarIdx) return UnknownValue; // Multiple non-constant idx's. |
| 1699 | VarIdx = GEP->getOperand(i); |
| 1700 | VarIdxNum = i-2; |
| 1701 | Indexes.push_back(0); |
| 1702 | } |
| 1703 | |
| 1704 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 1705 | // Check to see if X is a loop variant variable value now. |
| 1706 | SCEVHandle Idx = getSCEV(VarIdx); |
| 1707 | SCEVHandle Tmp = getSCEVAtScope(Idx, L); |
| 1708 | if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; |
| 1709 | |
| 1710 | // We can only recognize very limited forms of loop index expressions, in |
| 1711 | // particular, only affine AddRec's like {C1,+,C2}. |
| 1712 | SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
| 1713 | if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || |
| 1714 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 1715 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
| 1716 | return UnknownValue; |
| 1717 | |
| 1718 | unsigned MaxSteps = MaxBruteForceIterations; |
| 1719 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 1720 | ConstantInt *ItCst = |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 1721 | ConstantInt::get(IdxExpr->getType(), IterationNum); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1722 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst); |
| 1723 | |
| 1724 | // Form the GEP offset. |
| 1725 | Indexes[VarIdxNum] = Val; |
| 1726 | |
| 1727 | Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); |
| 1728 | if (Result == 0) break; // Cannot compute! |
| 1729 | |
| 1730 | // Evaluate the condition for this iteration. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1731 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1732 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1733 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1734 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1735 | cerr << "\n***\n*** Computed loop count " << *ItCst |
| 1736 | << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() |
| 1737 | << "***\n"; |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1738 | #endif |
| 1739 | ++NumArrayLenItCounts; |
| 1740 | return SCEVConstant::get(ItCst); // Found terminating iteration! |
| 1741 | } |
| 1742 | } |
| 1743 | return UnknownValue; |
| 1744 | } |
| 1745 | |
| 1746 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1747 | /// CanConstantFold - Return true if we can constant fold an instruction of the |
| 1748 | /// specified type, assuming that all operands were constants. |
| 1749 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 832254e | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 1750 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1751 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) |
| 1752 | return true; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1753 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1754 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 1755 | if (const Function *F = CI->getCalledFunction()) |
| 1756 | return canConstantFoldCallTo((Function*)F); // FIXME: elim cast |
| 1757 | return false; |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1758 | } |
| 1759 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1760 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 1761 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 1762 | /// way, but the operands of an operation must either be constants or a value |
| 1763 | /// derived from a constant PHI. If this expression does not fit with these |
| 1764 | /// constraints, return null. |
| 1765 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
| 1766 | // If this is not an instruction, or if this is an instruction outside of the |
| 1767 | // loop, it can't be derived from a loop PHI. |
| 1768 | Instruction *I = dyn_cast<Instruction>(V); |
| 1769 | if (I == 0 || !L->contains(I->getParent())) return 0; |
| 1770 | |
| 1771 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 1772 | if (L->getHeader() == I->getParent()) |
| 1773 | return PN; |
| 1774 | else |
| 1775 | // We don't currently keep track of the control flow needed to evaluate |
| 1776 | // PHIs, so we cannot handle PHIs inside of loops. |
| 1777 | return 0; |
| 1778 | |
| 1779 | // If we won't be able to constant fold this expression even if the operands |
| 1780 | // are constants, return early. |
| 1781 | if (!CanConstantFold(I)) return 0; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1782 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1783 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 1784 | // constant or derived from a PHI node themselves. |
| 1785 | PHINode *PHI = 0; |
| 1786 | for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) |
| 1787 | if (!(isa<Constant>(I->getOperand(Op)) || |
| 1788 | isa<GlobalValue>(I->getOperand(Op)))) { |
| 1789 | PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); |
| 1790 | if (P == 0) return 0; // Not evolving from PHI |
| 1791 | if (PHI == 0) |
| 1792 | PHI = P; |
| 1793 | else if (PHI != P) |
| 1794 | return 0; // Evolving from multiple different PHIs. |
| 1795 | } |
| 1796 | |
| 1797 | // This is a expression evolving from a constant PHI! |
| 1798 | return PHI; |
| 1799 | } |
| 1800 | |
| 1801 | /// EvaluateExpression - Given an expression that passes the |
| 1802 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 1803 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 1804 | /// reason, return null. |
| 1805 | static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { |
| 1806 | if (isa<PHINode>(V)) return PHIVal; |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1807 | if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) |
Reid Spencer | e840434 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 1808 | return GV; |
| 1809 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1810 | Instruction *I = cast<Instruction>(V); |
| 1811 | |
| 1812 | std::vector<Constant*> Operands; |
| 1813 | Operands.resize(I->getNumOperands()); |
| 1814 | |
| 1815 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 1816 | Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); |
| 1817 | if (Operands[i] == 0) return 0; |
| 1818 | } |
| 1819 | |
Chris Lattner | 2e3a1d1 | 2007-01-30 23:52:44 +0000 | [diff] [blame] | 1820 | return ConstantFoldInstOperands(I, &Operands[0], Operands.size()); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1821 | } |
| 1822 | |
| 1823 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 1824 | /// in the header of its containing loop, we know the loop executes a |
| 1825 | /// constant number of times, and the PHI node is just a recurrence |
| 1826 | /// involving constants, fold it. |
| 1827 | Constant *ScalarEvolutionsImpl:: |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1828 | getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){ |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1829 | std::map<PHINode*, Constant*>::iterator I = |
| 1830 | ConstantEvolutionLoopExitValue.find(PN); |
| 1831 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 1832 | return I->second; |
| 1833 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1834 | if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations))) |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1835 | return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. |
| 1836 | |
| 1837 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 1838 | |
| 1839 | // Since the loop is canonicalized, the PHI node must have two entries. One |
| 1840 | // entry must be a constant (coming in from outside of the loop), and the |
| 1841 | // second must be derived from the same PHI. |
| 1842 | bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); |
| 1843 | Constant *StartCST = |
| 1844 | dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); |
| 1845 | if (StartCST == 0) |
| 1846 | return RetVal = 0; // Must be a constant. |
| 1847 | |
| 1848 | Value *BEValue = PN->getIncomingValue(SecondIsBackedge); |
| 1849 | PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); |
| 1850 | if (PN2 != PN) |
| 1851 | return RetVal = 0; // Not derived from same PHI. |
| 1852 | |
| 1853 | // Execute the loop symbolically to determine the exit value. |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1854 | if (Its.getActiveBits() >= 32) |
| 1855 | return RetVal = 0; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1856 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1857 | unsigned NumIterations = Its.getZExtValue(); // must be in range |
| 1858 | unsigned IterationNum = 0; |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1859 | for (Constant *PHIVal = StartCST; ; ++IterationNum) { |
| 1860 | if (IterationNum == NumIterations) |
| 1861 | return RetVal = PHIVal; // Got exit value! |
| 1862 | |
| 1863 | // Compute the value of the PHI node for the next iteration. |
| 1864 | Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); |
| 1865 | if (NextPHI == PHIVal) |
| 1866 | return RetVal = NextPHI; // Stopped evolving! |
| 1867 | if (NextPHI == 0) |
| 1868 | return 0; // Couldn't evaluate! |
| 1869 | PHIVal = NextPHI; |
| 1870 | } |
| 1871 | } |
| 1872 | |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1873 | /// ComputeIterationCountExhaustively - If the trip is known to execute a |
| 1874 | /// constant number of times (the condition evolves only from constants), |
| 1875 | /// try to evaluate a few iterations of the loop until we get the exit |
| 1876 | /// condition gets a value of ExitWhen (true or false). If we cannot |
| 1877 | /// evaluate the trip count of the loop, return UnknownValue. |
| 1878 | SCEVHandle ScalarEvolutionsImpl:: |
| 1879 | ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { |
| 1880 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
| 1881 | if (PN == 0) return UnknownValue; |
| 1882 | |
| 1883 | // Since the loop is canonicalized, the PHI node must have two entries. One |
| 1884 | // entry must be a constant (coming in from outside of the loop), and the |
| 1885 | // second must be derived from the same PHI. |
| 1886 | bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); |
| 1887 | Constant *StartCST = |
| 1888 | dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); |
| 1889 | if (StartCST == 0) return UnknownValue; // Must be a constant. |
| 1890 | |
| 1891 | Value *BEValue = PN->getIncomingValue(SecondIsBackedge); |
| 1892 | PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); |
| 1893 | if (PN2 != PN) return UnknownValue; // Not derived from same PHI. |
| 1894 | |
| 1895 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 1896 | // the loop symbolically to determine when the condition gets a value of |
| 1897 | // "ExitWhen". |
| 1898 | unsigned IterationNum = 0; |
| 1899 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
| 1900 | for (Constant *PHIVal = StartCST; |
| 1901 | IterationNum != MaxIterations; ++IterationNum) { |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1902 | ConstantInt *CondVal = |
| 1903 | dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal)); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1904 | |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1905 | // Couldn't symbolically evaluate. |
Chris Lattner | ef3baf0 | 2007-01-12 18:28:58 +0000 | [diff] [blame] | 1906 | if (!CondVal) return UnknownValue; |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1907 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1908 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1909 | ConstantEvolutionLoopExitValue[PN] = PHIVal; |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1910 | ++NumBruteForceTripCountsComputed; |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 1911 | return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum)); |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1912 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1913 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1914 | // Compute the value of the PHI node for the next iteration. |
| 1915 | Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); |
| 1916 | if (NextPHI == 0 || NextPHI == PHIVal) |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1917 | return UnknownValue; // Couldn't evaluate or not making progress... |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1918 | PHIVal = NextPHI; |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1919 | } |
| 1920 | |
| 1921 | // Too many iterations were needed to evaluate. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1922 | return UnknownValue; |
| 1923 | } |
| 1924 | |
| 1925 | /// getSCEVAtScope - Compute the value of the specified expression within the |
| 1926 | /// indicated loop (which may be null to indicate in no loop). If the |
| 1927 | /// expression cannot be evaluated, return UnknownValue. |
| 1928 | SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) { |
| 1929 | // FIXME: this should be turned into a virtual method on SCEV! |
| 1930 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1931 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1932 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1933 | // If this instruction is evolves from a constant-evolving PHI, compute the |
| 1934 | // exit value from the loop without using SCEVs. |
| 1935 | if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
| 1936 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
| 1937 | const Loop *LI = this->LI[I->getParent()]; |
| 1938 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 1939 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 1940 | if (PN->getParent() == LI->getHeader()) { |
| 1941 | // Okay, there is no closed form solution for the PHI node. Check |
| 1942 | // to see if the loop that contains it has a known iteration count. |
| 1943 | // If so, we may be able to force computation of the exit value. |
| 1944 | SCEVHandle IterationCount = getIterationCount(LI); |
| 1945 | if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) { |
| 1946 | // Okay, we know how many times the containing loop executes. If |
| 1947 | // this is a constant evolving PHI node, get the final value at |
| 1948 | // the specified iteration number. |
| 1949 | Constant *RV = getConstantEvolutionLoopExitValue(PN, |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1950 | ICC->getValue()->getValue(), |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1951 | LI); |
| 1952 | if (RV) return SCEVUnknown::get(RV); |
| 1953 | } |
| 1954 | } |
| 1955 | |
Reid Spencer | 09906f3 | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 1956 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1957 | // into a SCEV. Check to see if it's possible to symbolically evaluate |
Reid Spencer | 09906f3 | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 1958 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1959 | // result. This is particularly useful for computing loop exit values. |
| 1960 | if (CanConstantFold(I)) { |
| 1961 | std::vector<Constant*> Operands; |
| 1962 | Operands.reserve(I->getNumOperands()); |
| 1963 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 1964 | Value *Op = I->getOperand(i); |
| 1965 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 1966 | Operands.push_back(C); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1967 | } else { |
| 1968 | SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); |
| 1969 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 1970 | Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), |
| 1971 | Op->getType(), |
| 1972 | false)); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1973 | else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { |
| 1974 | if (Constant *C = dyn_cast<Constant>(SU->getValue())) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 1975 | Operands.push_back(ConstantExpr::getIntegerCast(C, |
| 1976 | Op->getType(), |
| 1977 | false)); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1978 | else |
| 1979 | return V; |
| 1980 | } else { |
| 1981 | return V; |
| 1982 | } |
| 1983 | } |
| 1984 | } |
Chris Lattner | 2e3a1d1 | 2007-01-30 23:52:44 +0000 | [diff] [blame] | 1985 | Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size()); |
| 1986 | return SCEVUnknown::get(C); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1987 | } |
| 1988 | } |
| 1989 | |
| 1990 | // This is some other type of SCEVUnknown, just return it. |
| 1991 | return V; |
| 1992 | } |
| 1993 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1994 | if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
| 1995 | // Avoid performing the look-up in the common case where the specified |
| 1996 | // expression has no loop-variant portions. |
| 1997 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
| 1998 | SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
| 1999 | if (OpAtScope != Comm->getOperand(i)) { |
| 2000 | if (OpAtScope == UnknownValue) return UnknownValue; |
| 2001 | // Okay, at least one of these operands is loop variant but might be |
| 2002 | // foldable. Build a new instance of the folded commutative expression. |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2003 | std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2004 | NewOps.push_back(OpAtScope); |
| 2005 | |
| 2006 | for (++i; i != e; ++i) { |
| 2007 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
| 2008 | if (OpAtScope == UnknownValue) return UnknownValue; |
| 2009 | NewOps.push_back(OpAtScope); |
| 2010 | } |
| 2011 | if (isa<SCEVAddExpr>(Comm)) |
| 2012 | return SCEVAddExpr::get(NewOps); |
| 2013 | assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!"); |
| 2014 | return SCEVMulExpr::get(NewOps); |
| 2015 | } |
| 2016 | } |
| 2017 | // If we got here, all operands are loop invariant. |
| 2018 | return Comm; |
| 2019 | } |
| 2020 | |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 2021 | if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) { |
| 2022 | SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2023 | if (LHS == UnknownValue) return LHS; |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 2024 | SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2025 | if (RHS == UnknownValue) return RHS; |
Chris Lattner | 60a05cc | 2006-04-01 04:48:52 +0000 | [diff] [blame] | 2026 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 2027 | return Div; // must be loop invariant |
| 2028 | return SCEVSDivExpr::get(LHS, RHS); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2029 | } |
| 2030 | |
| 2031 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 2032 | // are dealing with the final value computed by the loop. |
| 2033 | if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
| 2034 | if (!L || !AddRec->getLoop()->contains(L->getHeader())) { |
| 2035 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 2036 | // loop iterates. Compute this now. |
| 2037 | SCEVHandle IterationCount = getIterationCount(AddRec->getLoop()); |
| 2038 | if (IterationCount == UnknownValue) return UnknownValue; |
| 2039 | IterationCount = getTruncateOrZeroExtend(IterationCount, |
| 2040 | AddRec->getType()); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2041 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2042 | // If the value is affine, simplify the expression evaluation to just |
| 2043 | // Start + Step*IterationCount. |
| 2044 | if (AddRec->isAffine()) |
| 2045 | return SCEVAddExpr::get(AddRec->getStart(), |
| 2046 | SCEVMulExpr::get(IterationCount, |
| 2047 | AddRec->getOperand(1))); |
| 2048 | |
| 2049 | // Otherwise, evaluate it the hard way. |
| 2050 | return AddRec->evaluateAtIteration(IterationCount); |
| 2051 | } |
| 2052 | return UnknownValue; |
| 2053 | } |
| 2054 | |
| 2055 | //assert(0 && "Unknown SCEV type!"); |
| 2056 | return UnknownValue; |
| 2057 | } |
| 2058 | |
| 2059 | |
| 2060 | /// SolveQuadraticEquation - Find the roots of the quadratic equation for the |
| 2061 | /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which |
| 2062 | /// might be the same) or two SCEVCouldNotCompute objects. |
| 2063 | /// |
| 2064 | static std::pair<SCEVHandle,SCEVHandle> |
| 2065 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) { |
| 2066 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2067 | SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 2068 | SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 2069 | SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2070 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2071 | // We currently can only solve this if the coefficients are constants. |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2072 | if (!LC || !MC || !NC) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2073 | SCEV *CNC = new SCEVCouldNotCompute(); |
| 2074 | return std::make_pair(CNC, CNC); |
| 2075 | } |
| 2076 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2077 | uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); |
| 2078 | APInt L(LC->getValue()->getValue()); |
| 2079 | APInt M(MC->getValue()->getValue()); |
| 2080 | APInt N(MC->getValue()->getValue()); |
| 2081 | APInt Two(BitWidth, 2); |
| 2082 | APInt Four(BitWidth, 4); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2083 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2084 | { |
| 2085 | using namespace APIntOps; |
| 2086 | APInt C(L); |
| 2087 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 2088 | // The B coefficient is M-N/2 |
| 2089 | APInt B(M); |
| 2090 | B -= sdiv(N,Two); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2091 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2092 | // The A coefficient is N/2 |
| 2093 | APInt A(N); |
| 2094 | A = A.sdiv(Two); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2095 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2096 | // Compute the B^2-4ac term. |
| 2097 | APInt SqrtTerm(B); |
| 2098 | SqrtTerm *= B; |
| 2099 | SqrtTerm -= Four * (A * C); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2100 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2101 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 2102 | // integer value or else APInt::sqrt() will assert. |
| 2103 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2104 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2105 | // Compute the two solutions for the quadratic formula. |
| 2106 | // The divisions must be performed as signed divisions. |
| 2107 | APInt NegB(-B); |
| 2108 | APInt TwoA( A * Two ); |
| 2109 | ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA)); |
| 2110 | ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2111 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2112 | return std::make_pair(SCEVUnknown::get(Solution1), |
| 2113 | SCEVUnknown::get(Solution2)); |
| 2114 | } // end APIntOps namespace |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2115 | } |
| 2116 | |
| 2117 | /// HowFarToZero - Return the number of times a backedge comparing the specified |
| 2118 | /// value to zero will execute. If not computable, return UnknownValue |
| 2119 | SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) { |
| 2120 | // If the value is a constant |
| 2121 | if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
| 2122 | // If the value is already zero, the branch will execute zero times. |
| 2123 | if (C->getValue()->isNullValue()) return C; |
| 2124 | return UnknownValue; // Otherwise it will loop infinitely. |
| 2125 | } |
| 2126 | |
| 2127 | SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
| 2128 | if (!AddRec || AddRec->getLoop() != L) |
| 2129 | return UnknownValue; |
| 2130 | |
| 2131 | if (AddRec->isAffine()) { |
| 2132 | // If this is an affine expression the execution count of this branch is |
| 2133 | // equal to: |
| 2134 | // |
| 2135 | // (0 - Start/Step) iff Start % Step == 0 |
| 2136 | // |
| 2137 | // Get the initial value for the loop. |
| 2138 | SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
Chris Lattner | 4a2b23e | 2004-10-11 04:07:27 +0000 | [diff] [blame] | 2139 | if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2140 | SCEVHandle Step = AddRec->getOperand(1); |
| 2141 | |
| 2142 | Step = getSCEVAtScope(Step, L->getParentLoop()); |
| 2143 | |
| 2144 | // Figure out if Start % Step == 0. |
| 2145 | // FIXME: We should add DivExpr and RemExpr operations to our AST. |
| 2146 | if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { |
| 2147 | if (StepC->getValue()->equalsInt(1)) // N % 1 == 0 |
Chris Lattner | bac5b46 | 2005-03-09 05:34:41 +0000 | [diff] [blame] | 2148 | return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2149 | if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0 |
| 2150 | return Start; // 0 - Start/-1 == Start |
| 2151 | |
| 2152 | // Check to see if Start is divisible by SC with no remainder. |
| 2153 | if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { |
| 2154 | ConstantInt *StartCC = StartC->getValue(); |
| 2155 | Constant *StartNegC = ConstantExpr::getNeg(StartCC); |
Reid Spencer | 0a783f7 | 2006-11-02 01:53:59 +0000 | [diff] [blame] | 2156 | Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2157 | if (Rem->isNullValue()) { |
Reid Spencer | 1628cec | 2006-10-26 06:15:43 +0000 | [diff] [blame] | 2158 | Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2159 | return SCEVUnknown::get(Result); |
| 2160 | } |
| 2161 | } |
| 2162 | } |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 2163 | } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2164 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 2165 | // the quadratic equation to solve it. |
| 2166 | std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec); |
| 2167 | SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 2168 | SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
| 2169 | if (R1) { |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 2170 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2171 | cerr << "HFTZ: " << *V << " - sol#1: " << *R1 |
| 2172 | << " sol#2: " << *R2 << "\n"; |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 2173 | #endif |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2174 | // Pick the smallest positive root value. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2175 | if (ConstantInt *CB = |
| 2176 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2177 | R1->getValue(), R2->getValue()))) { |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 2178 | if (CB->getZExtValue() == false) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2179 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2180 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2181 | // We can only use this value if the chrec ends up with an exact zero |
| 2182 | // value at this index. When solving for "X*X != 5", for example, we |
| 2183 | // should not accept a root of 2. |
| 2184 | SCEVHandle Val = AddRec->evaluateAtIteration(R1); |
| 2185 | if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val)) |
| 2186 | if (EvalVal->getValue()->isNullValue()) |
| 2187 | return R1; // We found a quadratic root! |
| 2188 | } |
| 2189 | } |
| 2190 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2191 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2192 | return UnknownValue; |
| 2193 | } |
| 2194 | |
| 2195 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 2196 | /// specified value for nonzero will execute. If not computable, return |
| 2197 | /// UnknownValue |
| 2198 | SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) { |
| 2199 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 2200 | // handle them yet except for the trivial case. This could be expanded in the |
| 2201 | // future as needed. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2202 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2203 | // If the value is a constant, check to see if it is known to be non-zero |
| 2204 | // already. If so, the backedge will execute zero times. |
| 2205 | if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
| 2206 | Constant *Zero = Constant::getNullValue(C->getValue()->getType()); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2207 | Constant *NonZero = |
| 2208 | ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero); |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2209 | if (NonZero == ConstantInt::getTrue()) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2210 | return getSCEV(Zero); |
| 2211 | return UnknownValue; // Otherwise it will loop infinitely. |
| 2212 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2213 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2214 | // We could implement others, but I really doubt anyone writes loops like |
| 2215 | // this, and if they did, they would already be constant folded. |
| 2216 | return UnknownValue; |
| 2217 | } |
| 2218 | |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2219 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 2220 | /// specified less-than comparison will execute. If not computable, return |
| 2221 | /// UnknownValue. |
| 2222 | SCEVHandle ScalarEvolutionsImpl:: |
| 2223 | HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) { |
| 2224 | // Only handle: "ADDREC < LoopInvariant". |
| 2225 | if (!RHS->isLoopInvariant(L)) return UnknownValue; |
| 2226 | |
| 2227 | SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); |
| 2228 | if (!AddRec || AddRec->getLoop() != L) |
| 2229 | return UnknownValue; |
| 2230 | |
| 2231 | if (AddRec->isAffine()) { |
| 2232 | // FORNOW: We only support unit strides. |
| 2233 | SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType()); |
| 2234 | if (AddRec->getOperand(1) != One) |
| 2235 | return UnknownValue; |
| 2236 | |
| 2237 | // The number of iterations for "[n,+,1] < m", is m-n. However, we don't |
| 2238 | // know that m is >= n on input to the loop. If it is, the condition return |
| 2239 | // true zero times. What we really should return, for full generality, is |
| 2240 | // SMAX(0, m-n). Since we cannot check this, we will instead check for a |
| 2241 | // canonical loop form: most do-loops will have a check that dominates the |
| 2242 | // loop, that only enters the loop if [n-1]<m. If we can find this check, |
| 2243 | // we know that the SMAX will evaluate to m-n, because we know that m >= n. |
| 2244 | |
| 2245 | // Search for the check. |
| 2246 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 2247 | BasicBlock *PreheaderDest = L->getHeader(); |
| 2248 | if (Preheader == 0) return UnknownValue; |
| 2249 | |
| 2250 | BranchInst *LoopEntryPredicate = |
| 2251 | dyn_cast<BranchInst>(Preheader->getTerminator()); |
| 2252 | if (!LoopEntryPredicate) return UnknownValue; |
| 2253 | |
| 2254 | // This might be a critical edge broken out. If the loop preheader ends in |
| 2255 | // an unconditional branch to the loop, check to see if the preheader has a |
| 2256 | // single predecessor, and if so, look for its terminator. |
| 2257 | while (LoopEntryPredicate->isUnconditional()) { |
| 2258 | PreheaderDest = Preheader; |
| 2259 | Preheader = Preheader->getSinglePredecessor(); |
| 2260 | if (!Preheader) return UnknownValue; // Multiple preds. |
| 2261 | |
| 2262 | LoopEntryPredicate = |
| 2263 | dyn_cast<BranchInst>(Preheader->getTerminator()); |
| 2264 | if (!LoopEntryPredicate) return UnknownValue; |
| 2265 | } |
| 2266 | |
| 2267 | // Now that we found a conditional branch that dominates the loop, check to |
| 2268 | // see if it is the comparison we are looking for. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2269 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){ |
| 2270 | Value *PreCondLHS = ICI->getOperand(0); |
| 2271 | Value *PreCondRHS = ICI->getOperand(1); |
| 2272 | ICmpInst::Predicate Cond; |
| 2273 | if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) |
| 2274 | Cond = ICI->getPredicate(); |
| 2275 | else |
| 2276 | Cond = ICI->getInversePredicate(); |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2277 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2278 | switch (Cond) { |
| 2279 | case ICmpInst::ICMP_UGT: |
| 2280 | std::swap(PreCondLHS, PreCondRHS); |
| 2281 | Cond = ICmpInst::ICMP_ULT; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2282 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2283 | case ICmpInst::ICMP_SGT: |
| 2284 | std::swap(PreCondLHS, PreCondRHS); |
| 2285 | Cond = ICmpInst::ICMP_SLT; |
| 2286 | break; |
| 2287 | default: break; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2288 | } |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2289 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2290 | if (Cond == ICmpInst::ICMP_SLT) { |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 2291 | if (PreCondLHS->getType()->isInteger()) { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2292 | if (RHS != getSCEV(PreCondRHS)) |
| 2293 | return UnknownValue; // Not a comparison against 'm'. |
| 2294 | |
| 2295 | if (SCEV::getMinusSCEV(AddRec->getOperand(0), One) |
| 2296 | != getSCEV(PreCondLHS)) |
| 2297 | return UnknownValue; // Not a comparison against 'n-1'. |
| 2298 | } |
| 2299 | else return UnknownValue; |
| 2300 | } else if (Cond == ICmpInst::ICMP_ULT) |
| 2301 | return UnknownValue; |
| 2302 | |
| 2303 | // cerr << "Computed Loop Trip Count as: " |
| 2304 | // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n"; |
| 2305 | return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)); |
| 2306 | } |
| 2307 | else |
| 2308 | return UnknownValue; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2309 | } |
| 2310 | |
| 2311 | return UnknownValue; |
| 2312 | } |
| 2313 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2314 | /// getNumIterationsInRange - Return the number of iterations of this loop that |
| 2315 | /// produce values in the specified constant range. Another way of looking at |
| 2316 | /// this is that it returns the first iteration number where the value is not in |
| 2317 | /// the condition, thus computing the exit count. If the iteration count can't |
| 2318 | /// be computed, an instance of SCEVCouldNotCompute is returned. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2319 | SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, |
| 2320 | bool isSigned) const { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2321 | if (Range.isFullSet()) // Infinite loop. |
| 2322 | return new SCEVCouldNotCompute(); |
| 2323 | |
| 2324 | // If the start is a non-zero constant, shift the range to simplify things. |
| 2325 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
| 2326 | if (!SC->getValue()->isNullValue()) { |
| 2327 | std::vector<SCEVHandle> Operands(op_begin(), op_end()); |
Chris Lattner | b06432c | 2004-04-23 21:29:03 +0000 | [diff] [blame] | 2328 | Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2329 | SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop()); |
| 2330 | if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
| 2331 | return ShiftedAddRec->getNumIterationsInRange( |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2332 | Range.subtract(SC->getValue()->getValue()),isSigned); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2333 | // This is strange and shouldn't happen. |
| 2334 | return new SCEVCouldNotCompute(); |
| 2335 | } |
| 2336 | |
| 2337 | // The only time we can solve this is when we have all constant indices. |
| 2338 | // Otherwise, we cannot determine the overflow conditions. |
| 2339 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
| 2340 | if (!isa<SCEVConstant>(getOperand(i))) |
| 2341 | return new SCEVCouldNotCompute(); |
| 2342 | |
| 2343 | |
| 2344 | // Okay at this point we know that all elements of the chrec are constants and |
| 2345 | // that the start element is zero. |
| 2346 | |
| 2347 | // First check to see if the range contains zero. If not, the first |
| 2348 | // iteration exits. |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2349 | if (!Range.contains(APInt(getBitWidth(),0))) |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2350 | return SCEVConstant::get(ConstantInt::get(getType(),0)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2351 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2352 | if (isAffine()) { |
| 2353 | // If this is an affine expression then we have this situation: |
| 2354 | // Solve {0,+,A} in Range === Ax in Range |
| 2355 | |
| 2356 | // Since we know that zero is in the range, we know that the upper value of |
| 2357 | // the range must be the first possible exit value. Also note that we |
| 2358 | // already checked for a full range. |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2359 | const APInt &Upper = Range.getUpper(); |
| 2360 | APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); |
| 2361 | APInt One(getBitWidth(),1); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2362 | |
| 2363 | // The exit value should be (Upper+A-1)/A. |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2364 | APInt ExitVal(Upper); |
| 2365 | if (A != One) |
| 2366 | ExitVal = (Upper + A - One).sdiv(A); |
Reid Spencer | c7cd7a0 | 2007-03-01 19:32:33 +0000 | [diff] [blame^] | 2367 | ConstantInt *ExitValue = ConstantInt::get(ExitVal); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2368 | |
| 2369 | // Evaluate at the exit value. If we really did fall out of the valid |
| 2370 | // range, then we computed our trip count, otherwise wrap around or other |
| 2371 | // things must have happened. |
| 2372 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2373 | if (Range.contains(Val->getValue())) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2374 | return new SCEVCouldNotCompute(); // Something strange happened |
| 2375 | |
| 2376 | // Ensure that the previous value is in the range. This is a sanity check. |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2377 | assert(Range.contains( |
| 2378 | EvaluateConstantChrecAtConstant(this, |
Reid Spencer | c7cd7a0 | 2007-03-01 19:32:33 +0000 | [diff] [blame^] | 2379 | ConstantInt::get(ExitVal - One))->getValue()) && |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2380 | "Linear scev computation is off in a bad way!"); |
| 2381 | return SCEVConstant::get(cast<ConstantInt>(ExitValue)); |
| 2382 | } else if (isQuadratic()) { |
| 2383 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 2384 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 2385 | // terms of figuring out when zero is crossed, instead of when |
| 2386 | // Range.getUpper() is crossed. |
| 2387 | std::vector<SCEVHandle> NewOps(op_begin(), op_end()); |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2388 | NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get( |
Reid Spencer | c7cd7a0 | 2007-03-01 19:32:33 +0000 | [diff] [blame^] | 2389 | ConstantInt::get(Range.getUpper()))); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2390 | SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop()); |
| 2391 | |
| 2392 | // Next, solve the constructed addrec |
| 2393 | std::pair<SCEVHandle,SCEVHandle> Roots = |
| 2394 | SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec)); |
| 2395 | SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 2396 | SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
| 2397 | if (R1) { |
| 2398 | // Pick the smallest positive root value. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2399 | if (ConstantInt *CB = |
| 2400 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2401 | R1->getValue(), R2->getValue()))) { |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 2402 | if (CB->getZExtValue() == false) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2403 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2404 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2405 | // Make sure the root is not off by one. The returned iteration should |
| 2406 | // not be in the range, but the previous one should be. When solving |
| 2407 | // for "X*X < 5", for example, we should not return a root of 2. |
| 2408 | ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, |
| 2409 | R1->getValue()); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2410 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2411 | // The next iteration must be out of the range... |
| 2412 | Constant *NextVal = |
| 2413 | ConstantExpr::getAdd(R1->getValue(), |
| 2414 | ConstantInt::get(R1->getType(), 1)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2415 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2416 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2417 | if (!Range.contains(R1Val->getValue())) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2418 | return SCEVUnknown::get(NextVal); |
| 2419 | return new SCEVCouldNotCompute(); // Something strange happened |
| 2420 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2421 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2422 | // If R1 was not in the range, then it is a good return value. Make |
| 2423 | // sure that R1-1 WAS in the range though, just in case. |
| 2424 | Constant *NextVal = |
| 2425 | ConstantExpr::getSub(R1->getValue(), |
| 2426 | ConstantInt::get(R1->getType(), 1)); |
| 2427 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2428 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2429 | return R1; |
| 2430 | return new SCEVCouldNotCompute(); // Something strange happened |
| 2431 | } |
| 2432 | } |
| 2433 | } |
| 2434 | |
| 2435 | // Fallback, if this is a general polynomial, figure out the progression |
| 2436 | // through brute force: evaluate until we find an iteration that fails the |
| 2437 | // test. This is likely to be slow, but getting an accurate trip count is |
| 2438 | // incredibly important, we will be able to simplify the exit test a lot, and |
| 2439 | // we are almost guaranteed to get a trip count in this case. |
| 2440 | ConstantInt *TestVal = ConstantInt::get(getType(), 0); |
| 2441 | ConstantInt *One = ConstantInt::get(getType(), 1); |
| 2442 | ConstantInt *EndVal = TestVal; // Stop when we wrap around. |
| 2443 | do { |
| 2444 | ++NumBruteForceEvaluations; |
| 2445 | SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal)); |
| 2446 | if (!isa<SCEVConstant>(Val)) // This shouldn't happen. |
| 2447 | return new SCEVCouldNotCompute(); |
| 2448 | |
| 2449 | // Check to see if we found the value! |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2450 | if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue())) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2451 | return SCEVConstant::get(TestVal); |
| 2452 | |
| 2453 | // Increment to test the next index. |
| 2454 | TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One)); |
| 2455 | } while (TestVal != EndVal); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2456 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2457 | return new SCEVCouldNotCompute(); |
| 2458 | } |
| 2459 | |
| 2460 | |
| 2461 | |
| 2462 | //===----------------------------------------------------------------------===// |
| 2463 | // ScalarEvolution Class Implementation |
| 2464 | //===----------------------------------------------------------------------===// |
| 2465 | |
| 2466 | bool ScalarEvolution::runOnFunction(Function &F) { |
| 2467 | Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>()); |
| 2468 | return false; |
| 2469 | } |
| 2470 | |
| 2471 | void ScalarEvolution::releaseMemory() { |
| 2472 | delete (ScalarEvolutionsImpl*)Impl; |
| 2473 | Impl = 0; |
| 2474 | } |
| 2475 | |
| 2476 | void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { |
| 2477 | AU.setPreservesAll(); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2478 | AU.addRequiredTransitive<LoopInfo>(); |
| 2479 | } |
| 2480 | |
| 2481 | SCEVHandle ScalarEvolution::getSCEV(Value *V) const { |
| 2482 | return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V); |
| 2483 | } |
| 2484 | |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 2485 | /// hasSCEV - Return true if the SCEV for this value has already been |
| 2486 | /// computed. |
| 2487 | bool ScalarEvolution::hasSCEV(Value *V) const { |
Chris Lattner | 05bd374 | 2005-08-10 00:59:40 +0000 | [diff] [blame] | 2488 | return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V); |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 2489 | } |
| 2490 | |
| 2491 | |
| 2492 | /// setSCEV - Insert the specified SCEV into the map of current SCEVs for |
| 2493 | /// the specified value. |
| 2494 | void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) { |
| 2495 | ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H); |
| 2496 | } |
| 2497 | |
| 2498 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2499 | SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const { |
| 2500 | return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L); |
| 2501 | } |
| 2502 | |
| 2503 | bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const { |
| 2504 | return !isa<SCEVCouldNotCompute>(getIterationCount(L)); |
| 2505 | } |
| 2506 | |
| 2507 | SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const { |
| 2508 | return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L); |
| 2509 | } |
| 2510 | |
| 2511 | void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const { |
| 2512 | return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I); |
| 2513 | } |
| 2514 | |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2515 | static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2516 | const Loop *L) { |
| 2517 | // Print all inner loops first |
| 2518 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 2519 | PrintLoopInfo(OS, SE, *I); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2520 | |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2521 | cerr << "Loop " << L->getHeader()->getName() << ": "; |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 2522 | |
| 2523 | std::vector<BasicBlock*> ExitBlocks; |
| 2524 | L->getExitBlocks(ExitBlocks); |
| 2525 | if (ExitBlocks.size() != 1) |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2526 | cerr << "<multiple exits> "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2527 | |
| 2528 | if (SE->hasLoopInvariantIterationCount(L)) { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2529 | cerr << *SE->getIterationCount(L) << " iterations! "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2530 | } else { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2531 | cerr << "Unpredictable iteration count. "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2532 | } |
| 2533 | |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2534 | cerr << "\n"; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2535 | } |
| 2536 | |
Reid Spencer | ce9653c | 2004-12-07 04:03:45 +0000 | [diff] [blame] | 2537 | void ScalarEvolution::print(std::ostream &OS, const Module* ) const { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2538 | Function &F = ((ScalarEvolutionsImpl*)Impl)->F; |
| 2539 | LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI; |
| 2540 | |
| 2541 | OS << "Classifying expressions for: " << F.getName() << "\n"; |
| 2542 | for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 2543 | if (I->getType()->isInteger()) { |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 2544 | OS << *I; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2545 | OS << " --> "; |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 2546 | SCEVHandle SV = getSCEV(&*I); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2547 | SV->print(OS); |
| 2548 | OS << "\t\t"; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2549 | |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 2550 | if ((*I).getType()->isInteger()) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2551 | ConstantRange Bounds = SV->getValueRange(); |
| 2552 | if (!Bounds.isFullSet()) |
| 2553 | OS << "Bounds: " << Bounds << " "; |
| 2554 | } |
| 2555 | |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 2556 | if (const Loop *L = LI.getLoopFor((*I).getParent())) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2557 | OS << "Exits: "; |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 2558 | SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2559 | if (isa<SCEVCouldNotCompute>(ExitValue)) { |
| 2560 | OS << "<<Unknown>>"; |
| 2561 | } else { |
| 2562 | OS << *ExitValue; |
| 2563 | } |
| 2564 | } |
| 2565 | |
| 2566 | |
| 2567 | OS << "\n"; |
| 2568 | } |
| 2569 | |
| 2570 | OS << "Determining loop execution counts for: " << F.getName() << "\n"; |
| 2571 | for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) |
| 2572 | PrintLoopInfo(OS, this, *I); |
| 2573 | } |
| 2574 | |