Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 1 | //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | d934c70 | 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 |
Dan Gohman | ef2ae2c | 2009-07-25 16:18:07 +0000 | [diff] [blame] | 17 | // can handle. We only create one SCEV of a particular shape, so |
| 18 | // pointer-comparisons for equality are legal. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 19 | // |
| 20 | // One important aspect of the SCEV objects is that they are never cyclic, even |
| 21 | // if there is a cycle in the dataflow for an expression (ie, a PHI node). If |
| 22 | // the PHI node is one of the idioms that we can represent (e.g., a polynomial |
| 23 | // recurrence) then we represent it directly as a recurrence node, otherwise we |
| 24 | // represent it as a SCEVUnknown node. |
| 25 | // |
| 26 | // In addition to being able to represent expressions of various types, we also |
| 27 | // have folders that are used to build the *canonical* representation for a |
| 28 | // particular expression. These folders are capable of using a variety of |
| 29 | // rewrite rules to simplify the expressions. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 30 | // |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 31 | // Once the folders are defined, we can implement the more interesting |
| 32 | // higher-level code, such as the code that recognizes PHI nodes of various |
| 33 | // types, computes the execution count of a loop, etc. |
| 34 | // |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 35 | // TODO: We should use these routines and value representations to implement |
| 36 | // dependence analysis! |
| 37 | // |
| 38 | //===----------------------------------------------------------------------===// |
| 39 | // |
| 40 | // There are several good references for the techniques used in this analysis. |
| 41 | // |
| 42 | // Chains of recurrences -- a method to expedite the evaluation |
| 43 | // of closed-form functions |
| 44 | // Olaf Bachmann, Paul S. Wang, Eugene V. Zima |
| 45 | // |
| 46 | // On computational properties of chains of recurrences |
| 47 | // Eugene V. Zima |
| 48 | // |
| 49 | // Symbolic Evaluation of Chains of Recurrences for Loop Optimization |
| 50 | // Robert A. van Engelen |
| 51 | // |
| 52 | // Efficient Symbolic Analysis for Optimizing Compilers |
| 53 | // Robert A. van Engelen |
| 54 | // |
| 55 | // Using the chains of recurrences algebra for data dependence testing and |
| 56 | // induction variable substitution |
| 57 | // MS Thesis, Johnie Birch |
| 58 | // |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 61 | #include "llvm/Analysis/ScalarEvolution.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 62 | #include "llvm/ADT/Optional.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 63 | #include "llvm/ADT/STLExtras.h" |
| 64 | #include "llvm/ADT/SmallPtrSet.h" |
| 65 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 66 | #include "llvm/Analysis/AssumptionCache.h" |
John Criswell | fe5f33b | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 67 | #include "llvm/Analysis/ConstantFolding.h" |
Duncan Sands | d06f50e | 2010-11-17 04:18:45 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/InstructionSimplify.h" |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 70 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 71 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 72 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 73 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 74 | #include "llvm/IR/Constants.h" |
| 75 | #include "llvm/IR/DataLayout.h" |
| 76 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 77 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 78 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 79 | #include "llvm/IR/GlobalAlias.h" |
| 80 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 8394857 | 2014-03-04 10:30:26 +0000 | [diff] [blame] | 81 | #include "llvm/IR/InstIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 82 | #include "llvm/IR/Instructions.h" |
| 83 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 84 | #include "llvm/IR/Metadata.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 85 | #include "llvm/IR/Operator.h" |
Chris Lattner | 996795b | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 86 | #include "llvm/Support/CommandLine.h" |
David Greene | 2330f78 | 2009-12-23 22:58:38 +0000 | [diff] [blame] | 87 | #include "llvm/Support/Debug.h" |
Torok Edwin | 56d0659 | 2009-07-11 20:10:48 +0000 | [diff] [blame] | 88 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | 0a1e993 | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 89 | #include "llvm/Support/MathExtras.h" |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 90 | #include "llvm/Support/raw_ostream.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 91 | #include <algorithm> |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 92 | using namespace llvm; |
| 93 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 94 | #define DEBUG_TYPE "scalar-evolution" |
| 95 | |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 96 | STATISTIC(NumArrayLenItCounts, |
| 97 | "Number of trip counts computed with array length"); |
| 98 | STATISTIC(NumTripCountsComputed, |
| 99 | "Number of loops with predictable loop counts"); |
| 100 | STATISTIC(NumTripCountsNotComputed, |
| 101 | "Number of loops without predictable loop counts"); |
| 102 | STATISTIC(NumBruteForceTripCountsComputed, |
| 103 | "Number of loops with trip counts computed by force"); |
| 104 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 105 | static cl::opt<unsigned> |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 106 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 107 | cl::desc("Maximum number of iterations SCEV will " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 108 | "symbolically execute a constant " |
| 109 | "derived loop"), |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 110 | cl::init(100)); |
| 111 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 112 | // FIXME: Enable this with XDEBUG when the test suite is clean. |
| 113 | static cl::opt<bool> |
| 114 | VerifySCEV("verify-scev", |
| 115 | cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); |
| 116 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 117 | //===----------------------------------------------------------------------===// |
| 118 | // SCEV class definitions |
| 119 | //===----------------------------------------------------------------------===// |
| 120 | |
| 121 | //===----------------------------------------------------------------------===// |
| 122 | // Implementation of the SCEV class. |
| 123 | // |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 124 | |
Manman Ren | 49d684e | 2012-09-12 05:06:18 +0000 | [diff] [blame] | 125 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 126 | void SCEV::dump() const { |
David Greene | df1c497 | 2009-12-23 22:18:14 +0000 | [diff] [blame] | 127 | print(dbgs()); |
| 128 | dbgs() << '\n'; |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 129 | } |
Manman Ren | c3366cc | 2012-09-06 19:55:56 +0000 | [diff] [blame] | 130 | #endif |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 131 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 132 | void SCEV::print(raw_ostream &OS) const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 133 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 134 | case scConstant: |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 135 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 136 | return; |
| 137 | case scTruncate: { |
| 138 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); |
| 139 | const SCEV *Op = Trunc->getOperand(); |
| 140 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " |
| 141 | << *Trunc->getType() << ")"; |
| 142 | return; |
| 143 | } |
| 144 | case scZeroExtend: { |
| 145 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); |
| 146 | const SCEV *Op = ZExt->getOperand(); |
| 147 | OS << "(zext " << *Op->getType() << " " << *Op << " to " |
| 148 | << *ZExt->getType() << ")"; |
| 149 | return; |
| 150 | } |
| 151 | case scSignExtend: { |
| 152 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); |
| 153 | const SCEV *Op = SExt->getOperand(); |
| 154 | OS << "(sext " << *Op->getType() << " " << *Op << " to " |
| 155 | << *SExt->getType() << ")"; |
| 156 | return; |
| 157 | } |
| 158 | case scAddRecExpr: { |
| 159 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); |
| 160 | OS << "{" << *AR->getOperand(0); |
| 161 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) |
| 162 | OS << ",+," << *AR->getOperand(i); |
| 163 | OS << "}<"; |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 164 | if (AR->getNoWrapFlags(FlagNUW)) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 165 | OS << "nuw><"; |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 166 | if (AR->getNoWrapFlags(FlagNSW)) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 167 | OS << "nsw><"; |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 168 | if (AR->getNoWrapFlags(FlagNW) && |
| 169 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) |
| 170 | OS << "nw><"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 171 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 172 | OS << ">"; |
| 173 | return; |
| 174 | } |
| 175 | case scAddExpr: |
| 176 | case scMulExpr: |
| 177 | case scUMaxExpr: |
| 178 | case scSMaxExpr: { |
| 179 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 180 | const char *OpStr = nullptr; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 181 | switch (NAry->getSCEVType()) { |
| 182 | case scAddExpr: OpStr = " + "; break; |
| 183 | case scMulExpr: OpStr = " * "; break; |
| 184 | case scUMaxExpr: OpStr = " umax "; break; |
| 185 | case scSMaxExpr: OpStr = " smax "; break; |
| 186 | } |
| 187 | OS << "("; |
| 188 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 189 | I != E; ++I) { |
| 190 | OS << **I; |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 191 | if (std::next(I) != E) |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 192 | OS << OpStr; |
| 193 | } |
| 194 | OS << ")"; |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 195 | switch (NAry->getSCEVType()) { |
| 196 | case scAddExpr: |
| 197 | case scMulExpr: |
| 198 | if (NAry->getNoWrapFlags(FlagNUW)) |
| 199 | OS << "<nuw>"; |
| 200 | if (NAry->getNoWrapFlags(FlagNSW)) |
| 201 | OS << "<nsw>"; |
| 202 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 203 | return; |
| 204 | } |
| 205 | case scUDivExpr: { |
| 206 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); |
| 207 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; |
| 208 | return; |
| 209 | } |
| 210 | case scUnknown: { |
| 211 | const SCEVUnknown *U = cast<SCEVUnknown>(this); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 212 | Type *AllocTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 213 | if (U->isSizeOf(AllocTy)) { |
| 214 | OS << "sizeof(" << *AllocTy << ")"; |
| 215 | return; |
| 216 | } |
| 217 | if (U->isAlignOf(AllocTy)) { |
| 218 | OS << "alignof(" << *AllocTy << ")"; |
| 219 | return; |
| 220 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 221 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 222 | Type *CTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 223 | Constant *FieldNo; |
| 224 | if (U->isOffsetOf(CTy, FieldNo)) { |
| 225 | OS << "offsetof(" << *CTy << ", "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 226 | FieldNo->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 227 | OS << ")"; |
| 228 | return; |
| 229 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 230 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 231 | // Otherwise just print it normally. |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 232 | U->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 233 | return; |
| 234 | } |
| 235 | case scCouldNotCompute: |
| 236 | OS << "***COULDNOTCOMPUTE***"; |
| 237 | return; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 238 | } |
| 239 | llvm_unreachable("Unknown SCEV kind!"); |
| 240 | } |
| 241 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 242 | Type *SCEV::getType() const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 243 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 244 | case scConstant: |
| 245 | return cast<SCEVConstant>(this)->getType(); |
| 246 | case scTruncate: |
| 247 | case scZeroExtend: |
| 248 | case scSignExtend: |
| 249 | return cast<SCEVCastExpr>(this)->getType(); |
| 250 | case scAddRecExpr: |
| 251 | case scMulExpr: |
| 252 | case scUMaxExpr: |
| 253 | case scSMaxExpr: |
| 254 | return cast<SCEVNAryExpr>(this)->getType(); |
| 255 | case scAddExpr: |
| 256 | return cast<SCEVAddExpr>(this)->getType(); |
| 257 | case scUDivExpr: |
| 258 | return cast<SCEVUDivExpr>(this)->getType(); |
| 259 | case scUnknown: |
| 260 | return cast<SCEVUnknown>(this)->getType(); |
| 261 | case scCouldNotCompute: |
| 262 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 263 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 264 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 265 | } |
| 266 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 267 | bool SCEV::isZero() const { |
| 268 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 269 | return SC->getValue()->isZero(); |
| 270 | return false; |
| 271 | } |
| 272 | |
Dan Gohman | ba7f6d8 | 2009-05-18 15:22:39 +0000 | [diff] [blame] | 273 | bool SCEV::isOne() const { |
| 274 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 275 | return SC->getValue()->isOne(); |
| 276 | return false; |
| 277 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 278 | |
Dan Gohman | 18a96bb | 2009-06-24 00:30:26 +0000 | [diff] [blame] | 279 | bool SCEV::isAllOnesValue() const { |
| 280 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 281 | return SC->getValue()->isAllOnesValue(); |
| 282 | return false; |
| 283 | } |
| 284 | |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 285 | /// isNonConstantNegative - Return true if the specified scev is negated, but |
| 286 | /// not a constant. |
| 287 | bool SCEV::isNonConstantNegative() const { |
| 288 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); |
| 289 | if (!Mul) return false; |
| 290 | |
| 291 | // If there is a constant factor, it will be first. |
| 292 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); |
| 293 | if (!SC) return false; |
| 294 | |
| 295 | // Return true if the value is negative, this matches things like (-42 * V). |
| 296 | return SC->getValue()->getValue().isNegative(); |
| 297 | } |
| 298 | |
Owen Anderson | 04052ec | 2009-06-22 21:57:23 +0000 | [diff] [blame] | 299 | SCEVCouldNotCompute::SCEVCouldNotCompute() : |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 300 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 301 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 302 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 303 | return S->getSCEVType() == scCouldNotCompute; |
| 304 | } |
| 305 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 306 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 307 | FoldingSetNodeID ID; |
| 308 | ID.AddInteger(scConstant); |
| 309 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 310 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 311 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 312 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 313 | UniqueSCEVs.InsertNode(S, IP); |
| 314 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 315 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 316 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 317 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 318 | return getConstant(ConstantInt::get(getContext(), Val)); |
Dan Gohman | 0a76e7f | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 319 | } |
| 320 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 321 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 322 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { |
| 323 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); |
Dan Gohman | a029cbe | 2010-04-21 16:04:04 +0000 | [diff] [blame] | 324 | return getConstant(ConstantInt::get(ITy, V, isSigned)); |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 325 | } |
| 326 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 327 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 328 | unsigned SCEVTy, const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 329 | : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 330 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 331 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 332 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 333 | : SCEVCastExpr(ID, scTruncate, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 334 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 335 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 336 | "Cannot truncate non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 337 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 338 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 339 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 340 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 341 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 342 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 343 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 344 | "Cannot zero extend non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 345 | } |
| 346 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 347 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 348 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 349 | : SCEVCastExpr(ID, scSignExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 350 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 351 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 352 | "Cannot sign extend non-integer value!"); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 353 | } |
| 354 | |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 355 | void SCEVUnknown::deleted() { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 356 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 357 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 358 | |
| 359 | // Remove this SCEVUnknown from the uniquing map. |
| 360 | SE->UniqueSCEVs.RemoveNode(this); |
| 361 | |
| 362 | // Release the value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 363 | setValPtr(nullptr); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 364 | } |
| 365 | |
| 366 | void SCEVUnknown::allUsesReplacedWith(Value *New) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 367 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 368 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 369 | |
| 370 | // Remove this SCEVUnknown from the uniquing map. |
| 371 | SE->UniqueSCEVs.RemoveNode(this); |
| 372 | |
| 373 | // Update this SCEVUnknown to point to the new value. This is needed |
| 374 | // because there may still be outstanding SCEVs which still point to |
| 375 | // this SCEVUnknown. |
| 376 | setValPtr(New); |
| 377 | } |
| 378 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 379 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 380 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 381 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 382 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 383 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 384 | CE->getOperand(0)->isNullValue() && |
| 385 | CE->getNumOperands() == 2) |
| 386 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) |
| 387 | if (CI->isOne()) { |
| 388 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) |
| 389 | ->getElementType(); |
| 390 | return true; |
| 391 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 392 | |
| 393 | return false; |
| 394 | } |
| 395 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 396 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 397 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 398 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 399 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 400 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 401 | CE->getOperand(0)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 402 | Type *Ty = |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 403 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 404 | if (StructType *STy = dyn_cast<StructType>(Ty)) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 405 | if (!STy->isPacked() && |
| 406 | CE->getNumOperands() == 3 && |
| 407 | CE->getOperand(1)->isNullValue()) { |
| 408 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) |
| 409 | if (CI->isOne() && |
| 410 | STy->getNumElements() == 2 && |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 411 | STy->getElementType(0)->isIntegerTy(1)) { |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 412 | AllocTy = STy->getElementType(1); |
| 413 | return true; |
| 414 | } |
| 415 | } |
| 416 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 417 | |
| 418 | return false; |
| 419 | } |
| 420 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 421 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 422 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 423 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 424 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
| 425 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 426 | CE->getNumOperands() == 3 && |
| 427 | CE->getOperand(0)->isNullValue() && |
| 428 | CE->getOperand(1)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 429 | Type *Ty = |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 430 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
| 431 | // Ignore vector types here so that ScalarEvolutionExpander doesn't |
| 432 | // emit getelementptrs that index into vectors. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 433 | if (Ty->isStructTy() || Ty->isArrayTy()) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 434 | CTy = Ty; |
| 435 | FieldNo = CE->getOperand(2); |
| 436 | return true; |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | return false; |
| 441 | } |
| 442 | |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 443 | //===----------------------------------------------------------------------===// |
| 444 | // SCEV Utilities |
| 445 | //===----------------------------------------------------------------------===// |
| 446 | |
| 447 | namespace { |
| 448 | /// SCEVComplexityCompare - Return true if the complexity of the LHS is less |
| 449 | /// than the complexity of the RHS. This comparator is used to canonicalize |
| 450 | /// expressions. |
Nick Lewycky | 02d5f77 | 2009-10-25 06:33:48 +0000 | [diff] [blame] | 451 | class SCEVComplexityCompare { |
Dan Gohman | 3324b9e | 2010-08-13 20:17:27 +0000 | [diff] [blame] | 452 | const LoopInfo *const LI; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 453 | public: |
Dan Gohman | 992db00 | 2010-07-23 21:18:55 +0000 | [diff] [blame] | 454 | explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 455 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 456 | // Return true or false if LHS is less than, or at least RHS, respectively. |
Dan Gohman | 5e6ce7b | 2008-04-14 18:23:56 +0000 | [diff] [blame] | 457 | bool operator()(const SCEV *LHS, const SCEV *RHS) const { |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 458 | return compare(LHS, RHS) < 0; |
| 459 | } |
| 460 | |
| 461 | // Return negative, zero, or positive, if LHS is less than, equal to, or |
| 462 | // greater than RHS, respectively. A three-way result allows recursive |
| 463 | // comparisons to be more efficient. |
| 464 | int compare(const SCEV *LHS, const SCEV *RHS) const { |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 465 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. |
| 466 | if (LHS == RHS) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 467 | return 0; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 468 | |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 469 | // Primarily, sort the SCEVs by their getSCEVType(). |
Dan Gohman | 5ae3102 | 2010-07-23 21:20:52 +0000 | [diff] [blame] | 470 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); |
| 471 | if (LType != RType) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 472 | return (int)LType - (int)RType; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 473 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 474 | // Aside from the getSCEVType() ordering, the particular ordering |
| 475 | // isn't very important except that it's beneficial to be consistent, |
| 476 | // so that (a + b) and (b + a) don't end up as different expressions. |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 477 | switch (static_cast<SCEVTypes>(LType)) { |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 478 | case scUnknown: { |
| 479 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 480 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 481 | |
| 482 | // Sort SCEVUnknown values with some loose heuristics. TODO: This is |
| 483 | // not as complete as it could be. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 484 | const Value *LV = LU->getValue(), *RV = RU->getValue(); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 485 | |
| 486 | // Order pointer values after integer values. This helps SCEVExpander |
| 487 | // form GEPs. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 488 | bool LIsPointer = LV->getType()->isPointerTy(), |
| 489 | RIsPointer = RV->getType()->isPointerTy(); |
Dan Gohman | 5ae3102 | 2010-07-23 21:20:52 +0000 | [diff] [blame] | 490 | if (LIsPointer != RIsPointer) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 491 | return (int)LIsPointer - (int)RIsPointer; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 492 | |
| 493 | // Compare getValueID values. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 494 | unsigned LID = LV->getValueID(), |
| 495 | RID = RV->getValueID(); |
Dan Gohman | 5ae3102 | 2010-07-23 21:20:52 +0000 | [diff] [blame] | 496 | if (LID != RID) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 497 | return (int)LID - (int)RID; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 498 | |
| 499 | // Sort arguments by their position. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 500 | if (const Argument *LA = dyn_cast<Argument>(LV)) { |
| 501 | const Argument *RA = cast<Argument>(RV); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 502 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); |
| 503 | return (int)LArgNo - (int)RArgNo; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 504 | } |
| 505 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 506 | // For instructions, compare their loop depth, and their operand |
| 507 | // count. This is pretty loose. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 508 | if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { |
| 509 | const Instruction *RInst = cast<Instruction>(RV); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 510 | |
| 511 | // Compare loop depths. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 512 | const BasicBlock *LParent = LInst->getParent(), |
| 513 | *RParent = RInst->getParent(); |
| 514 | if (LParent != RParent) { |
| 515 | unsigned LDepth = LI->getLoopDepth(LParent), |
| 516 | RDepth = LI->getLoopDepth(RParent); |
| 517 | if (LDepth != RDepth) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 518 | return (int)LDepth - (int)RDepth; |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 519 | } |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 520 | |
| 521 | // Compare the number of operands. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 522 | unsigned LNumOps = LInst->getNumOperands(), |
| 523 | RNumOps = RInst->getNumOperands(); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 524 | return (int)LNumOps - (int)RNumOps; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 525 | } |
| 526 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 527 | return 0; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 528 | } |
| 529 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 530 | case scConstant: { |
| 531 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 532 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 533 | |
| 534 | // Compare constant values. |
Dan Gohman | f296182 | 2010-08-16 16:25:35 +0000 | [diff] [blame] | 535 | const APInt &LA = LC->getValue()->getValue(); |
| 536 | const APInt &RA = RC->getValue()->getValue(); |
| 537 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); |
Dan Gohman | 5ae3102 | 2010-07-23 21:20:52 +0000 | [diff] [blame] | 538 | if (LBitWidth != RBitWidth) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 539 | return (int)LBitWidth - (int)RBitWidth; |
| 540 | return LA.ult(RA) ? -1 : 1; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 541 | } |
| 542 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 543 | case scAddRecExpr: { |
| 544 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 545 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 546 | |
| 547 | // Compare addrec loop depths. |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 548 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); |
| 549 | if (LLoop != RLoop) { |
| 550 | unsigned LDepth = LLoop->getLoopDepth(), |
| 551 | RDepth = RLoop->getLoopDepth(); |
| 552 | if (LDepth != RDepth) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 553 | return (int)LDepth - (int)RDepth; |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 554 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 555 | |
| 556 | // Addrec complexity grows with operand count. |
| 557 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); |
| 558 | if (LNumOps != RNumOps) |
| 559 | return (int)LNumOps - (int)RNumOps; |
| 560 | |
| 561 | // Lexicographically compare. |
| 562 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 563 | long X = compare(LA->getOperand(i), RA->getOperand(i)); |
| 564 | if (X != 0) |
| 565 | return X; |
| 566 | } |
| 567 | |
| 568 | return 0; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 569 | } |
| 570 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 571 | case scAddExpr: |
| 572 | case scMulExpr: |
| 573 | case scSMaxExpr: |
| 574 | case scUMaxExpr: { |
| 575 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 576 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 577 | |
| 578 | // Lexicographically compare n-ary expressions. |
Dan Gohman | 5ae3102 | 2010-07-23 21:20:52 +0000 | [diff] [blame] | 579 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); |
Andrew Trick | c3bc8b8 | 2013-07-31 02:43:40 +0000 | [diff] [blame] | 580 | if (LNumOps != RNumOps) |
| 581 | return (int)LNumOps - (int)RNumOps; |
| 582 | |
Dan Gohman | 5ae3102 | 2010-07-23 21:20:52 +0000 | [diff] [blame] | 583 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 584 | if (i >= RNumOps) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 585 | return 1; |
| 586 | long X = compare(LC->getOperand(i), RC->getOperand(i)); |
| 587 | if (X != 0) |
| 588 | return X; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 589 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 590 | return (int)LNumOps - (int)RNumOps; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 591 | } |
| 592 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 593 | case scUDivExpr: { |
| 594 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 595 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 596 | |
| 597 | // Lexicographically compare udiv expressions. |
| 598 | long X = compare(LC->getLHS(), RC->getLHS()); |
| 599 | if (X != 0) |
| 600 | return X; |
| 601 | return compare(LC->getRHS(), RC->getRHS()); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 602 | } |
| 603 | |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 604 | case scTruncate: |
| 605 | case scZeroExtend: |
| 606 | case scSignExtend: { |
| 607 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 608 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 609 | |
| 610 | // Compare cast expressions by operand. |
| 611 | return compare(LC->getOperand(), RC->getOperand()); |
| 612 | } |
| 613 | |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 614 | case scCouldNotCompute: |
| 615 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 616 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 617 | llvm_unreachable("Unknown SCEV kind!"); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 618 | } |
| 619 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 620 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 621 | |
| 622 | /// GroupByComplexity - Given a list of SCEV objects, order them by their |
| 623 | /// complexity, and group objects of the same complexity together by value. |
| 624 | /// When this routine is finished, we know that any duplicates in the vector are |
| 625 | /// consecutive and that complexity is monotonically increasing. |
| 626 | /// |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 627 | /// Note that we go take special precautions to ensure that we get deterministic |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 628 | /// results from this routine. In other words, we don't want the results of |
| 629 | /// this to depend on where the addresses of various SCEV objects happened to |
| 630 | /// land in memory. |
| 631 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 632 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 633 | LoopInfo *LI) { |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 634 | if (Ops.size() < 2) return; // Noop |
| 635 | if (Ops.size() == 2) { |
| 636 | // This is the common case, which also happens to be trivially simple. |
| 637 | // Special case it. |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 638 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; |
| 639 | if (SCEVComplexityCompare(LI)(RHS, LHS)) |
| 640 | std::swap(LHS, RHS); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 641 | return; |
| 642 | } |
| 643 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 644 | // Do the rough sort by complexity. |
| 645 | std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); |
| 646 | |
| 647 | // Now that we are sorted by complexity, group elements of the same |
| 648 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 649 | // be extremely short in practice. Note that we take this approach because we |
| 650 | // do not want to depend on the addresses of the objects we are grouping. |
| 651 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
| 652 | const SCEV *S = Ops[i]; |
| 653 | unsigned Complexity = S->getSCEVType(); |
| 654 | |
| 655 | // If there are any objects of the same complexity and same value as this |
| 656 | // one, group them. |
| 657 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 658 | if (Ops[j] == S) { // Found a duplicate. |
| 659 | // Move it to immediately after i'th element. |
| 660 | std::swap(Ops[i+1], Ops[j]); |
| 661 | ++i; // no need to rescan it. |
| 662 | if (i == e-2) return; // Done! |
| 663 | } |
| 664 | } |
| 665 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 666 | } |
| 667 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 668 | namespace { |
| 669 | struct FindSCEVSize { |
| 670 | int Size; |
| 671 | FindSCEVSize() : Size(0) {} |
| 672 | |
| 673 | bool follow(const SCEV *S) { |
| 674 | ++Size; |
| 675 | // Keep looking at all operands of S. |
| 676 | return true; |
| 677 | } |
| 678 | bool isDone() const { |
| 679 | return false; |
| 680 | } |
| 681 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 682 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 683 | |
| 684 | // Returns the size of the SCEV S. |
| 685 | static inline int sizeOfSCEV(const SCEV *S) { |
| 686 | FindSCEVSize F; |
| 687 | SCEVTraversal<FindSCEVSize> ST(F); |
| 688 | ST.visitAll(S); |
| 689 | return F.Size; |
| 690 | } |
| 691 | |
| 692 | namespace { |
| 693 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 694 | struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 695 | public: |
| 696 | // Computes the Quotient and Remainder of the division of Numerator by |
| 697 | // Denominator. |
| 698 | static void divide(ScalarEvolution &SE, const SCEV *Numerator, |
| 699 | const SCEV *Denominator, const SCEV **Quotient, |
| 700 | const SCEV **Remainder) { |
| 701 | assert(Numerator && Denominator && "Uninitialized SCEV"); |
| 702 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 703 | SCEVDivision D(SE, Numerator, Denominator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 704 | |
| 705 | // Check for the trivial case here to avoid having to check for it in the |
| 706 | // rest of the code. |
| 707 | if (Numerator == Denominator) { |
| 708 | *Quotient = D.One; |
| 709 | *Remainder = D.Zero; |
| 710 | return; |
| 711 | } |
| 712 | |
| 713 | if (Numerator->isZero()) { |
| 714 | *Quotient = D.Zero; |
| 715 | *Remainder = D.Zero; |
| 716 | return; |
| 717 | } |
| 718 | |
Brendon Cahoon | a57cc8b | 2015-04-20 16:03:28 +0000 | [diff] [blame] | 719 | // A simple case when N/1. The quotient is N. |
| 720 | if (Denominator->isOne()) { |
| 721 | *Quotient = Numerator; |
| 722 | *Remainder = D.Zero; |
| 723 | return; |
| 724 | } |
| 725 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 726 | // Split the Denominator when it is a product. |
| 727 | if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) { |
| 728 | const SCEV *Q, *R; |
| 729 | *Quotient = Numerator; |
| 730 | for (const SCEV *Op : T->operands()) { |
| 731 | divide(SE, *Quotient, Op, &Q, &R); |
| 732 | *Quotient = Q; |
| 733 | |
| 734 | // Bail out when the Numerator is not divisible by one of the terms of |
| 735 | // the Denominator. |
| 736 | if (!R->isZero()) { |
| 737 | *Quotient = D.Zero; |
| 738 | *Remainder = Numerator; |
| 739 | return; |
| 740 | } |
| 741 | } |
| 742 | *Remainder = D.Zero; |
| 743 | return; |
| 744 | } |
| 745 | |
| 746 | D.visit(Numerator); |
| 747 | *Quotient = D.Quotient; |
| 748 | *Remainder = D.Remainder; |
| 749 | } |
| 750 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 751 | // Except in the trivial case described above, we do not know how to divide |
| 752 | // Expr by Denominator for the following functions with empty implementation. |
| 753 | void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} |
| 754 | void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} |
| 755 | void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} |
| 756 | void visitUDivExpr(const SCEVUDivExpr *Numerator) {} |
| 757 | void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} |
| 758 | void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} |
| 759 | void visitUnknown(const SCEVUnknown *Numerator) {} |
| 760 | void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} |
| 761 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 762 | void visitConstant(const SCEVConstant *Numerator) { |
| 763 | if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { |
| 764 | APInt NumeratorVal = Numerator->getValue()->getValue(); |
| 765 | APInt DenominatorVal = D->getValue()->getValue(); |
| 766 | uint32_t NumeratorBW = NumeratorVal.getBitWidth(); |
| 767 | uint32_t DenominatorBW = DenominatorVal.getBitWidth(); |
| 768 | |
| 769 | if (NumeratorBW > DenominatorBW) |
| 770 | DenominatorVal = DenominatorVal.sext(NumeratorBW); |
| 771 | else if (NumeratorBW < DenominatorBW) |
| 772 | NumeratorVal = NumeratorVal.sext(DenominatorBW); |
| 773 | |
| 774 | APInt QuotientVal(NumeratorVal.getBitWidth(), 0); |
| 775 | APInt RemainderVal(NumeratorVal.getBitWidth(), 0); |
| 776 | APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); |
| 777 | Quotient = SE.getConstant(QuotientVal); |
| 778 | Remainder = SE.getConstant(RemainderVal); |
| 779 | return; |
| 780 | } |
| 781 | } |
| 782 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 783 | void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { |
| 784 | const SCEV *StartQ, *StartR, *StepQ, *StepR; |
| 785 | assert(Numerator->isAffine() && "Numerator should be affine"); |
| 786 | divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); |
| 787 | divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); |
Brendon Cahoon | f9751ad | 2015-04-22 15:06:40 +0000 | [diff] [blame] | 788 | // Bail out if the types do not match. |
| 789 | Type *Ty = Denominator->getType(); |
| 790 | if (Ty != StartQ->getType() || Ty != StartR->getType() || |
| 791 | Ty != StepQ->getType() || Ty != StepR->getType()) { |
| 792 | Quotient = Zero; |
| 793 | Remainder = Numerator; |
| 794 | return; |
| 795 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 796 | Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), |
| 797 | Numerator->getNoWrapFlags()); |
| 798 | Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), |
| 799 | Numerator->getNoWrapFlags()); |
| 800 | } |
| 801 | |
| 802 | void visitAddExpr(const SCEVAddExpr *Numerator) { |
| 803 | SmallVector<const SCEV *, 2> Qs, Rs; |
| 804 | Type *Ty = Denominator->getType(); |
| 805 | |
| 806 | for (const SCEV *Op : Numerator->operands()) { |
| 807 | const SCEV *Q, *R; |
| 808 | divide(SE, Op, Denominator, &Q, &R); |
| 809 | |
| 810 | // Bail out if types do not match. |
| 811 | if (Ty != Q->getType() || Ty != R->getType()) { |
| 812 | Quotient = Zero; |
| 813 | Remainder = Numerator; |
| 814 | return; |
| 815 | } |
| 816 | |
| 817 | Qs.push_back(Q); |
| 818 | Rs.push_back(R); |
| 819 | } |
| 820 | |
| 821 | if (Qs.size() == 1) { |
| 822 | Quotient = Qs[0]; |
| 823 | Remainder = Rs[0]; |
| 824 | return; |
| 825 | } |
| 826 | |
| 827 | Quotient = SE.getAddExpr(Qs); |
| 828 | Remainder = SE.getAddExpr(Rs); |
| 829 | } |
| 830 | |
| 831 | void visitMulExpr(const SCEVMulExpr *Numerator) { |
| 832 | SmallVector<const SCEV *, 2> Qs; |
| 833 | Type *Ty = Denominator->getType(); |
| 834 | |
| 835 | bool FoundDenominatorTerm = false; |
| 836 | for (const SCEV *Op : Numerator->operands()) { |
| 837 | // Bail out if types do not match. |
| 838 | if (Ty != Op->getType()) { |
| 839 | Quotient = Zero; |
| 840 | Remainder = Numerator; |
| 841 | return; |
| 842 | } |
| 843 | |
| 844 | if (FoundDenominatorTerm) { |
| 845 | Qs.push_back(Op); |
| 846 | continue; |
| 847 | } |
| 848 | |
| 849 | // Check whether Denominator divides one of the product operands. |
| 850 | const SCEV *Q, *R; |
| 851 | divide(SE, Op, Denominator, &Q, &R); |
| 852 | if (!R->isZero()) { |
| 853 | Qs.push_back(Op); |
| 854 | continue; |
| 855 | } |
| 856 | |
| 857 | // Bail out if types do not match. |
| 858 | if (Ty != Q->getType()) { |
| 859 | Quotient = Zero; |
| 860 | Remainder = Numerator; |
| 861 | return; |
| 862 | } |
| 863 | |
| 864 | FoundDenominatorTerm = true; |
| 865 | Qs.push_back(Q); |
| 866 | } |
| 867 | |
| 868 | if (FoundDenominatorTerm) { |
| 869 | Remainder = Zero; |
| 870 | if (Qs.size() == 1) |
| 871 | Quotient = Qs[0]; |
| 872 | else |
| 873 | Quotient = SE.getMulExpr(Qs); |
| 874 | return; |
| 875 | } |
| 876 | |
| 877 | if (!isa<SCEVUnknown>(Denominator)) { |
| 878 | Quotient = Zero; |
| 879 | Remainder = Numerator; |
| 880 | return; |
| 881 | } |
| 882 | |
| 883 | // The Remainder is obtained by replacing Denominator by 0 in Numerator. |
| 884 | ValueToValueMap RewriteMap; |
| 885 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 886 | cast<SCEVConstant>(Zero)->getValue(); |
| 887 | Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 888 | |
| 889 | if (Remainder->isZero()) { |
| 890 | // The Quotient is obtained by replacing Denominator by 1 in Numerator. |
| 891 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 892 | cast<SCEVConstant>(One)->getValue(); |
| 893 | Quotient = |
| 894 | SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 895 | return; |
| 896 | } |
| 897 | |
| 898 | // Quotient is (Numerator - Remainder) divided by Denominator. |
| 899 | const SCEV *Q, *R; |
| 900 | const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); |
| 901 | if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) { |
| 902 | // This SCEV does not seem to simplify: fail the division here. |
| 903 | Quotient = Zero; |
| 904 | Remainder = Numerator; |
| 905 | return; |
| 906 | } |
| 907 | divide(SE, Diff, Denominator, &Q, &R); |
| 908 | assert(R == Zero && |
| 909 | "(Numerator - Remainder) should evenly divide Denominator"); |
| 910 | Quotient = Q; |
| 911 | } |
| 912 | |
| 913 | private: |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 914 | SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, |
| 915 | const SCEV *Denominator) |
| 916 | : SE(S), Denominator(Denominator) { |
| 917 | Zero = SE.getConstant(Denominator->getType(), 0); |
| 918 | One = SE.getConstant(Denominator->getType(), 1); |
| 919 | |
| 920 | // By default, we don't know how to divide Expr by Denominator. |
| 921 | // Providing the default here simplifies the rest of the code. |
| 922 | Quotient = Zero; |
| 923 | Remainder = Numerator; |
| 924 | } |
| 925 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 926 | ScalarEvolution &SE; |
| 927 | const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; |
David Majnemer | 32b8ccf | 2014-11-16 20:35:19 +0000 | [diff] [blame] | 928 | }; |
| 929 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 930 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 931 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 932 | //===----------------------------------------------------------------------===// |
| 933 | // Simple SCEV method implementations |
| 934 | //===----------------------------------------------------------------------===// |
| 935 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 936 | /// BinomialCoefficient - Compute BC(It, K). The result has width W. |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 937 | /// Assume, K > 0. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 938 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 939 | ScalarEvolution &SE, |
Nick Lewycky | 702cf1e | 2011-09-06 06:39:54 +0000 | [diff] [blame] | 940 | Type *ResultTy) { |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 941 | // Handle the simplest case efficiently. |
| 942 | if (K == 1) |
| 943 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 944 | |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 945 | // We are using the following formula for BC(It, K): |
| 946 | // |
| 947 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 948 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 949 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 950 | // overflow. Hence, we must assure that the result of our computation is |
| 951 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 952 | // safe in modular arithmetic. |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 953 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 954 | // However, this code doesn't use exactly that formula; the formula it uses |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 955 | // is something like the following, where T is the number of factors of 2 in |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 956 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 957 | // exponentiation: |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 958 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 959 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 960 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 961 | // This formula is trivially equivalent to the previous formula. However, |
| 962 | // this formula can be implemented much more efficiently. The trick is that |
| 963 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 964 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 965 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 966 | // width W. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 967 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 968 | // The next issue is how to safely do the division by 2^T. The way this |
| 969 | // is done is by doing the multiplication step at a width of at least W + T |
| 970 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 971 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 972 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 973 | // truncated out after the division by 2^T. |
| 974 | // |
| 975 | // In comparison to just directly using the first formula, this technique |
| 976 | // is much more efficient; using the first formula requires W * K bits, |
| 977 | // but this formula less than W + K bits. Also, the first formula requires |
| 978 | // a division step, whereas this formula only requires multiplies and shifts. |
| 979 | // |
| 980 | // It doesn't matter whether the subtraction step is done in the calculation |
| 981 | // width or the input iteration count's width; if the subtraction overflows, |
| 982 | // the result must be zero anyway. We prefer here to do it in the width of |
| 983 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 984 | // isn't smart enough to ignore the overflow, which leads to much less |
| 985 | // efficient code if the width of the subtraction is wider than the native |
| 986 | // register width. |
| 987 | // |
| 988 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 989 | // the multiplication; for example, K=2 can be calculated as |
| 990 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 991 | // extra arithmetic, so it's not an obvious win, and it gets |
| 992 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 993 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 994 | // Protection from insane SCEVs; this bound is conservative, |
| 995 | // but it probably doesn't matter. |
| 996 | if (K > 1000) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 997 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 998 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 999 | unsigned W = SE.getTypeSizeInBits(ResultTy); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1000 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1001 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 1002 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 1003 | // Other overflow doesn't matter because we only care about the bottom |
| 1004 | // W bits of the result. |
| 1005 | APInt OddFactorial(W, 1); |
| 1006 | unsigned T = 1; |
| 1007 | for (unsigned i = 3; i <= K; ++i) { |
| 1008 | APInt Mult(W, i); |
| 1009 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 1010 | T += TwoFactors; |
| 1011 | Mult = Mult.lshr(TwoFactors); |
| 1012 | OddFactorial *= Mult; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1013 | } |
Nick Lewycky | ed169d5 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 1014 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1015 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 21add8f | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 1016 | unsigned CalculationBits = W + T; |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1017 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1018 | // Calculate 2^T, at width T+W. |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 1019 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1020 | |
| 1021 | // Calculate the multiplicative inverse of K! / 2^T; |
| 1022 | // this multiplication factor will perform the exact division by |
| 1023 | // K! / 2^T. |
| 1024 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 1025 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 1026 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 1027 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 1028 | |
| 1029 | // Calculate the product, at width T+W |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1030 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1031 | CalculationBits); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1032 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1033 | for (unsigned i = 1; i != K; ++i) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1034 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1035 | Dividend = SE.getMulExpr(Dividend, |
| 1036 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 1037 | } |
| 1038 | |
| 1039 | // Divide by 2^T |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1040 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1041 | |
| 1042 | // Truncate the result, and divide by K! / 2^T. |
| 1043 | |
| 1044 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 1045 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1046 | } |
| 1047 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1048 | /// evaluateAtIteration - Return the value of this chain of recurrences at |
| 1049 | /// the specified iteration number. We can evaluate this recurrence by |
| 1050 | /// multiplying each element in the chain by the binomial coefficient |
| 1051 | /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: |
| 1052 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1053 | /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1054 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1055 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1056 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1057 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1058 | ScalarEvolution &SE) const { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1059 | const SCEV *Result = getStart(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1060 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1061 | // The computation is correct in the face of overflow provided that the |
| 1062 | // multiplication is performed _after_ the evaluation of the binomial |
| 1063 | // coefficient. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1064 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); |
Nick Lewycky | 707663e | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 1065 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 1066 | return Coeff; |
| 1067 | |
| 1068 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1069 | } |
| 1070 | return Result; |
| 1071 | } |
| 1072 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1073 | //===----------------------------------------------------------------------===// |
| 1074 | // SCEV Expression folder implementations |
| 1075 | //===----------------------------------------------------------------------===// |
| 1076 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1077 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1078 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1079 | assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1080 | "This is not a truncating conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1081 | assert(isSCEVable(Ty) && |
| 1082 | "This is not a conversion to a SCEVable type!"); |
| 1083 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1084 | |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1085 | FoldingSetNodeID ID; |
| 1086 | ID.AddInteger(scTruncate); |
| 1087 | ID.AddPointer(Op); |
| 1088 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1089 | void *IP = nullptr; |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1090 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1091 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1092 | // Fold if the operand is constant. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1093 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 8d7576e | 2009-06-24 00:38:39 +0000 | [diff] [blame] | 1094 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1095 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1096 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1097 | // trunc(trunc(x)) --> trunc(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1098 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1099 | return getTruncateExpr(ST->getOperand(), Ty); |
| 1100 | |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1101 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1102 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1103 | return getTruncateOrSignExtend(SS->getOperand(), Ty); |
| 1104 | |
| 1105 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1106 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1107 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty); |
| 1108 | |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1109 | // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can |
Nick Lewycky | 2ce2832 | 2015-03-20 02:52:23 +0000 | [diff] [blame] | 1110 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1111 | if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1112 | SmallVector<const SCEV *, 4> Operands; |
| 1113 | bool hasTrunc = false; |
| 1114 | for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1115 | const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1116 | if (!isa<SCEVCastExpr>(SA->getOperand(i))) |
| 1117 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1118 | Operands.push_back(S); |
| 1119 | } |
| 1120 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1121 | return getAddExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1122 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1123 | } |
| 1124 | |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1125 | // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1126 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1127 | if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { |
| 1128 | SmallVector<const SCEV *, 4> Operands; |
| 1129 | bool hasTrunc = false; |
| 1130 | for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1131 | const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1132 | if (!isa<SCEVCastExpr>(SM->getOperand(i))) |
| 1133 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1134 | Operands.push_back(S); |
| 1135 | } |
| 1136 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1137 | return getMulExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1138 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1139 | } |
| 1140 | |
Dan Gohman | 5a728c9 | 2009-06-18 16:24:47 +0000 | [diff] [blame] | 1141 | // If the input value is a chrec scev, truncate the chrec's operands. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1142 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1143 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1144 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 1145 | Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1146 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1147 | } |
| 1148 | |
Dan Gohman | 89dd42a | 2010-06-25 18:47:08 +0000 | [diff] [blame] | 1149 | // The cast wasn't folded; create an explicit cast node. We can reuse |
| 1150 | // the existing insert position since if we get here, we won't have |
| 1151 | // made any changes which would invalidate it. |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1152 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), |
| 1153 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1154 | UniqueSCEVs.InsertNode(S, IP); |
| 1155 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1156 | } |
| 1157 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1158 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1159 | // signed overflow as long as the value of the recurrence within the |
| 1160 | // loop does not exceed this limit before incrementing. |
| 1161 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, |
| 1162 | ICmpInst::Predicate *Pred, |
| 1163 | ScalarEvolution *SE) { |
| 1164 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1165 | if (SE->isKnownPositive(Step)) { |
| 1166 | *Pred = ICmpInst::ICMP_SLT; |
| 1167 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - |
| 1168 | SE->getSignedRange(Step).getSignedMax()); |
| 1169 | } |
| 1170 | if (SE->isKnownNegative(Step)) { |
| 1171 | *Pred = ICmpInst::ICMP_SGT; |
| 1172 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - |
| 1173 | SE->getSignedRange(Step).getSignedMin()); |
| 1174 | } |
| 1175 | return nullptr; |
| 1176 | } |
| 1177 | |
| 1178 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1179 | // unsigned overflow as long as the value of the recurrence within the loop does |
| 1180 | // not exceed this limit before incrementing. |
| 1181 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, |
| 1182 | ICmpInst::Predicate *Pred, |
| 1183 | ScalarEvolution *SE) { |
| 1184 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1185 | *Pred = ICmpInst::ICMP_ULT; |
| 1186 | |
| 1187 | return SE->getConstant(APInt::getMinValue(BitWidth) - |
| 1188 | SE->getUnsignedRange(Step).getUnsignedMax()); |
| 1189 | } |
| 1190 | |
| 1191 | namespace { |
| 1192 | |
| 1193 | struct ExtendOpTraitsBase { |
| 1194 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); |
| 1195 | }; |
| 1196 | |
| 1197 | // Used to make code generic over signed and unsigned overflow. |
| 1198 | template <typename ExtendOp> struct ExtendOpTraits { |
| 1199 | // Members present: |
| 1200 | // |
| 1201 | // static const SCEV::NoWrapFlags WrapType; |
| 1202 | // |
| 1203 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; |
| 1204 | // |
| 1205 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1206 | // ICmpInst::Predicate *Pred, |
| 1207 | // ScalarEvolution *SE); |
| 1208 | }; |
| 1209 | |
| 1210 | template <> |
| 1211 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { |
| 1212 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; |
| 1213 | |
| 1214 | static const GetExtendExprTy GetExtendExpr; |
| 1215 | |
| 1216 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1217 | ICmpInst::Predicate *Pred, |
| 1218 | ScalarEvolution *SE) { |
| 1219 | return getSignedOverflowLimitForStep(Step, Pred, SE); |
| 1220 | } |
| 1221 | }; |
| 1222 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1223 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1224 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; |
| 1225 | |
| 1226 | template <> |
| 1227 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { |
| 1228 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; |
| 1229 | |
| 1230 | static const GetExtendExprTy GetExtendExpr; |
| 1231 | |
| 1232 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1233 | ICmpInst::Predicate *Pred, |
| 1234 | ScalarEvolution *SE) { |
| 1235 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); |
| 1236 | } |
| 1237 | }; |
| 1238 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1239 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1240 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1241 | } |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1242 | |
| 1243 | // The recurrence AR has been shown to have no signed/unsigned wrap or something |
| 1244 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as |
| 1245 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This |
| 1246 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + |
| 1247 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the |
| 1248 | // expression "Step + sext/zext(PreIncAR)" is congruent with |
| 1249 | // "sext/zext(PostIncAR)" |
| 1250 | template <typename ExtendOpTy> |
| 1251 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, |
| 1252 | ScalarEvolution *SE) { |
| 1253 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1254 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1255 | |
| 1256 | const Loop *L = AR->getLoop(); |
| 1257 | const SCEV *Start = AR->getStart(); |
| 1258 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 1259 | |
| 1260 | // Check for a simple looking step prior to loop entry. |
| 1261 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); |
| 1262 | if (!SA) |
| 1263 | return nullptr; |
| 1264 | |
| 1265 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV |
| 1266 | // subtraction is expensive. For this purpose, perform a quick and dirty |
| 1267 | // difference, by checking for Step in the operand list. |
| 1268 | SmallVector<const SCEV *, 4> DiffOps; |
| 1269 | for (const SCEV *Op : SA->operands()) |
| 1270 | if (Op != Step) |
| 1271 | DiffOps.push_back(Op); |
| 1272 | |
| 1273 | if (DiffOps.size() == SA->getNumOperands()) |
| 1274 | return nullptr; |
| 1275 | |
| 1276 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + |
| 1277 | // `Step`: |
| 1278 | |
| 1279 | // 1. NSW/NUW flags on the step increment. |
| 1280 | const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags()); |
| 1281 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( |
| 1282 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); |
| 1283 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1284 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies |
| 1285 | // "S+X does not sign/unsign-overflow". |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1286 | // |
| 1287 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1288 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 1289 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && |
| 1290 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1291 | return PreStart; |
| 1292 | |
| 1293 | // 2. Direct overflow check on the step operation's expression. |
| 1294 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1295 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); |
| 1296 | const SCEV *OperandExtendedStart = |
| 1297 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), |
| 1298 | (SE->*GetExtendExpr)(Step, WideTy)); |
| 1299 | if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { |
| 1300 | if (PreAR && AR->getNoWrapFlags(WrapType)) { |
| 1301 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW |
| 1302 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then |
| 1303 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. |
| 1304 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); |
| 1305 | } |
| 1306 | return PreStart; |
| 1307 | } |
| 1308 | |
| 1309 | // 3. Loop precondition. |
| 1310 | ICmpInst::Predicate Pred; |
| 1311 | const SCEV *OverflowLimit = |
| 1312 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); |
| 1313 | |
| 1314 | if (OverflowLimit && |
| 1315 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) { |
| 1316 | return PreStart; |
| 1317 | } |
| 1318 | return nullptr; |
| 1319 | } |
| 1320 | |
| 1321 | // Get the normalized zero or sign extended expression for this AddRec's Start. |
| 1322 | template <typename ExtendOpTy> |
| 1323 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, |
| 1324 | ScalarEvolution *SE) { |
| 1325 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1326 | |
| 1327 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); |
| 1328 | if (!PreStart) |
| 1329 | return (SE->*GetExtendExpr)(AR->getStart(), Ty); |
| 1330 | |
| 1331 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), |
| 1332 | (SE->*GetExtendExpr)(PreStart, Ty)); |
| 1333 | } |
| 1334 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1335 | // Try to prove away overflow by looking at "nearby" add recurrences. A |
| 1336 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it |
| 1337 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. |
| 1338 | // |
| 1339 | // Formally: |
| 1340 | // |
| 1341 | // {S,+,X} == {S-T,+,X} + T |
| 1342 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) |
| 1343 | // |
| 1344 | // If ({S-T,+,X} + T) does not overflow ... (1) |
| 1345 | // |
| 1346 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) |
| 1347 | // |
| 1348 | // If {S-T,+,X} does not overflow ... (2) |
| 1349 | // |
| 1350 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) |
| 1351 | // == {Ext(S-T)+Ext(T),+,Ext(X)} |
| 1352 | // |
| 1353 | // If (S-T)+T does not overflow ... (3) |
| 1354 | // |
| 1355 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} |
| 1356 | // == {Ext(S),+,Ext(X)} == LHS |
| 1357 | // |
| 1358 | // Thus, if (1), (2) and (3) are true for some T, then |
| 1359 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} |
| 1360 | // |
| 1361 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) |
| 1362 | // does not overflow" restricted to the 0th iteration. Therefore we only need |
| 1363 | // to check for (1) and (2). |
| 1364 | // |
| 1365 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T |
| 1366 | // is `Delta` (defined below). |
| 1367 | // |
| 1368 | template <typename ExtendOpTy> |
| 1369 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, |
| 1370 | const SCEV *Step, |
| 1371 | const Loop *L) { |
| 1372 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1373 | |
| 1374 | // We restrict `Start` to a constant to prevent SCEV from spending too much |
| 1375 | // time here. It is correct (but more expensive) to continue with a |
| 1376 | // non-constant `Start` and do a general SCEV subtraction to compute |
| 1377 | // `PreStart` below. |
| 1378 | // |
| 1379 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); |
| 1380 | if (!StartC) |
| 1381 | return false; |
| 1382 | |
| 1383 | APInt StartAI = StartC->getValue()->getValue(); |
| 1384 | |
| 1385 | for (unsigned Delta : {-2, -1, 1, 2}) { |
| 1386 | const SCEV *PreStart = getConstant(StartAI - Delta); |
| 1387 | |
| 1388 | // Give up if we don't already have the add recurrence we need because |
| 1389 | // actually constructing an add recurrence is relatively expensive. |
| 1390 | const SCEVAddRecExpr *PreAR = [&]() { |
| 1391 | FoldingSetNodeID ID; |
| 1392 | ID.AddInteger(scAddRecExpr); |
| 1393 | ID.AddPointer(PreStart); |
| 1394 | ID.AddPointer(Step); |
| 1395 | ID.AddPointer(L); |
| 1396 | void *IP = nullptr; |
| 1397 | return static_cast<SCEVAddRecExpr *>( |
NAKAMURA Takumi | 8f49dd3 | 2015-03-05 01:02:45 +0000 | [diff] [blame] | 1398 | this->UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1399 | }(); |
| 1400 | |
| 1401 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) |
| 1402 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); |
| 1403 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 1404 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( |
| 1405 | DeltaS, &Pred, this); |
| 1406 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) |
| 1407 | return true; |
| 1408 | } |
| 1409 | } |
| 1410 | |
| 1411 | return false; |
| 1412 | } |
| 1413 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1414 | const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1415 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1416 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1417 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1418 | assert(isSCEVable(Ty) && |
| 1419 | "This is not a conversion to a SCEVable type!"); |
| 1420 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1421 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1422 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1423 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1424 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1425 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1426 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1427 | // zext(zext(x)) --> zext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1428 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1429 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1430 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1431 | // Before doing any expensive analysis, check to see if we've already |
| 1432 | // computed a SCEV for this Op and Ty. |
| 1433 | FoldingSetNodeID ID; |
| 1434 | ID.AddInteger(scZeroExtend); |
| 1435 | ID.AddPointer(Op); |
| 1436 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1437 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1438 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1439 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1440 | // zext(trunc(x)) --> zext(x) or x or trunc(x) |
| 1441 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1442 | // It's possible the bits taken off by the truncate were all zero bits. If |
| 1443 | // so, we should be able to simplify this further. |
| 1444 | const SCEV *X = ST->getOperand(); |
| 1445 | ConstantRange CR = getUnsignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1446 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1447 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1448 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1449 | CR.zextOrTrunc(NewBits))) |
| 1450 | return getTruncateOrZeroExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1451 | } |
| 1452 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1453 | // If the input value is a chrec scev, and we can prove that the value |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1454 | // did not overflow the old, smaller, value, we can zero extend all of the |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1455 | // operands (often constants). This allows analysis of something like |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1456 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1457 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1458 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1459 | const SCEV *Start = AR->getStart(); |
| 1460 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1461 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1462 | const Loop *L = AR->getLoop(); |
| 1463 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1464 | // If we have special knowledge that this addrec won't overflow, |
| 1465 | // we don't need to do any further analysis. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1466 | if (AR->getNoWrapFlags(SCEV::FlagNUW)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1467 | return getAddRecExpr( |
| 1468 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1469 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1470 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1471 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1472 | // Note that this serves two purposes: It filters out loops that are |
| 1473 | // simply not analyzable, and it covers the case where this code is |
| 1474 | // being called from within backedge-taken count analysis, such that |
| 1475 | // attempting to ask for the backedge-taken count would likely result |
| 1476 | // in infinite recursion. In the later case, the analysis code will |
| 1477 | // cope with a conservative value, and it will take care to purge |
| 1478 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1479 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1480 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1481 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1482 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1483 | |
| 1484 | // Check whether the backedge-taken count can be losslessly casted to |
| 1485 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1486 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1487 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1488 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1489 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1490 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1491 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1492 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1493 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1494 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1495 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1496 | const SCEV *WideMaxBECount = |
| 1497 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1498 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1499 | getAddExpr(WideStart, |
| 1500 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1501 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1502 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1503 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1504 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1505 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1506 | return getAddRecExpr( |
| 1507 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1508 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1509 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1510 | // Similar to above, only this time treat the step value as signed. |
| 1511 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1512 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1513 | getAddExpr(WideStart, |
| 1514 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1515 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1516 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1517 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1518 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1519 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1520 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1521 | return getAddRecExpr( |
| 1522 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1523 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1524 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1525 | } |
| 1526 | |
| 1527 | // If the backedge is guarded by a comparison with the pre-inc value |
| 1528 | // the addrec is safe. Also, if the entry is guarded by a comparison |
| 1529 | // with the start value and the backedge is guarded by a comparison |
| 1530 | // with the post-inc value, the addrec is safe. |
| 1531 | if (isKnownPositive(Step)) { |
| 1532 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1533 | getUnsignedRange(Step).getUnsignedMax()); |
| 1534 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1535 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1536 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1537 | AR->getPostIncExpr(*this), N))) { |
| 1538 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1539 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1540 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1541 | return getAddRecExpr( |
| 1542 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1543 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1544 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1545 | } else if (isKnownNegative(Step)) { |
| 1546 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1547 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1548 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1549 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1550 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1551 | AR->getPostIncExpr(*this), N))) { |
| 1552 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1553 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1554 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1555 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1556 | return getAddRecExpr( |
| 1557 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1558 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1559 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1560 | } |
| 1561 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1562 | |
| 1563 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1564 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1565 | return getAddRecExpr( |
| 1566 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1567 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1568 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1569 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1570 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1571 | // The cast wasn't folded; create an explicit cast node. |
| 1572 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1573 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1574 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1575 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1576 | UniqueSCEVs.InsertNode(S, IP); |
| 1577 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1578 | } |
| 1579 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1580 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1581 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1582 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1583 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1584 | assert(isSCEVable(Ty) && |
| 1585 | "This is not a conversion to a SCEVable type!"); |
| 1586 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1587 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1588 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1589 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1590 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1591 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1592 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1593 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1594 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1595 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1596 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1597 | // sext(zext(x)) --> zext(x) |
| 1598 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1599 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1600 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1601 | // Before doing any expensive analysis, check to see if we've already |
| 1602 | // computed a SCEV for this Op and Ty. |
| 1603 | FoldingSetNodeID ID; |
| 1604 | ID.AddInteger(scSignExtend); |
| 1605 | ID.AddPointer(Op); |
| 1606 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1607 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1608 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1609 | |
Nick Lewycky | b32c894 | 2011-01-22 22:06:21 +0000 | [diff] [blame] | 1610 | // If the input value is provably positive, build a zext instead. |
| 1611 | if (isKnownNonNegative(Op)) |
| 1612 | return getZeroExtendExpr(Op, Ty); |
| 1613 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1614 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1615 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1616 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1617 | // so, we should be able to simplify this further. |
| 1618 | const SCEV *X = ST->getOperand(); |
| 1619 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1620 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1621 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1622 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1623 | CR.sextOrTrunc(NewBits))) |
| 1624 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1625 | } |
| 1626 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1627 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
| 1628 | if (auto SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1629 | if (SA->getNumOperands() == 2) { |
| 1630 | auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1631 | auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
| 1632 | if (SMul && SC1) { |
| 1633 | if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1634 | const APInt &C1 = SC1->getValue()->getValue(); |
| 1635 | const APInt &C2 = SC2->getValue()->getValue(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1636 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1637 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1638 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1639 | getSignExtendExpr(SMul, Ty)); |
| 1640 | } |
| 1641 | } |
| 1642 | } |
| 1643 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1644 | // If the input value is a chrec scev, and we can prove that the value |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1645 | // did not overflow the old, smaller, value, we can sign extend all of the |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1646 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1647 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1648 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1649 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1650 | const SCEV *Start = AR->getStart(); |
| 1651 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1652 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1653 | const Loop *L = AR->getLoop(); |
| 1654 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1655 | // If we have special knowledge that this addrec won't overflow, |
| 1656 | // we don't need to do any further analysis. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1657 | if (AR->getNoWrapFlags(SCEV::FlagNSW)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1658 | return getAddRecExpr( |
| 1659 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1660 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1661 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1662 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1663 | // Note that this serves two purposes: It filters out loops that are |
| 1664 | // simply not analyzable, and it covers the case where this code is |
| 1665 | // being called from within backedge-taken count analysis, such that |
| 1666 | // attempting to ask for the backedge-taken count would likely result |
| 1667 | // in infinite recursion. In the later case, the analysis code will |
| 1668 | // cope with a conservative value, and it will take care to purge |
| 1669 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1670 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1671 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1672 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1673 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1674 | |
| 1675 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1676 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1677 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1678 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1679 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1680 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1681 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1682 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1683 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1684 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1685 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1686 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1687 | const SCEV *WideMaxBECount = |
| 1688 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1689 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1690 | getAddExpr(WideStart, |
| 1691 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1692 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1693 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1694 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1695 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1696 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1697 | return getAddRecExpr( |
| 1698 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1699 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1700 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1701 | // Similar to above, only this time treat the step value as unsigned. |
| 1702 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1703 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1704 | getAddExpr(WideStart, |
| 1705 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1706 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1707 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1708 | // If AR wraps around then |
| 1709 | // |
| 1710 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1711 | // => SAdd != OperandExtendedAdd |
| 1712 | // |
| 1713 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1714 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1715 | |
| 1716 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1717 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1718 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1719 | return getAddRecExpr( |
| 1720 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1721 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1722 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1723 | } |
| 1724 | |
| 1725 | // If the backedge is guarded by a comparison with the pre-inc value |
| 1726 | // the addrec is safe. Also, if the entry is guarded by a comparison |
| 1727 | // with the start value and the backedge is guarded by a comparison |
| 1728 | // with the post-inc value, the addrec is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1729 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1730 | const SCEV *OverflowLimit = |
| 1731 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1732 | if (OverflowLimit && |
| 1733 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1734 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1735 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1736 | OverflowLimit)))) { |
| 1737 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1738 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1739 | return getAddRecExpr( |
| 1740 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1741 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1742 | } |
| 1743 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1744 | // If Start and Step are constants, check if we can apply this |
| 1745 | // transformation: |
| 1746 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
| 1747 | auto SC1 = dyn_cast<SCEVConstant>(Start); |
| 1748 | auto SC2 = dyn_cast<SCEVConstant>(Step); |
| 1749 | if (SC1 && SC2) { |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1750 | const APInt &C1 = SC1->getValue()->getValue(); |
| 1751 | const APInt &C2 = SC2->getValue()->getValue(); |
| 1752 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1753 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1754 | Start = getSignExtendExpr(Start, Ty); |
| 1755 | const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step, |
| 1756 | L, AR->getNoWrapFlags()); |
| 1757 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1758 | } |
| 1759 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1760 | |
| 1761 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1762 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1763 | return getAddRecExpr( |
| 1764 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1765 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1766 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1767 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1768 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1769 | // The cast wasn't folded; create an explicit cast node. |
| 1770 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1771 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1772 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1773 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1774 | UniqueSCEVs.InsertNode(S, IP); |
| 1775 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1776 | } |
| 1777 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1778 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1779 | /// unspecified bits out to the given type. |
| 1780 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1781 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1782 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1783 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1784 | "This is not an extending conversion!"); |
| 1785 | assert(isSCEVable(Ty) && |
| 1786 | "This is not a conversion to a SCEVable type!"); |
| 1787 | Ty = getEffectiveSCEVType(Ty); |
| 1788 | |
| 1789 | // Sign-extend negative constants. |
| 1790 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1791 | if (SC->getValue()->getValue().isNegative()) |
| 1792 | return getSignExtendExpr(Op, Ty); |
| 1793 | |
| 1794 | // Peel off a truncate cast. |
| 1795 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1796 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1797 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1798 | return getAnyExtendExpr(NewOp, Ty); |
| 1799 | return getTruncateOrNoop(NewOp, Ty); |
| 1800 | } |
| 1801 | |
| 1802 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1803 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1804 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1805 | return ZExt; |
| 1806 | |
| 1807 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1808 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1809 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1810 | return SExt; |
| 1811 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1812 | // Force the cast to be folded into the operands of an addrec. |
| 1813 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1814 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1815 | for (const SCEV *Op : AR->operands()) |
| 1816 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1817 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1818 | } |
| 1819 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1820 | // If the expression is obviously signed, use the sext cast value. |
| 1821 | if (isa<SCEVSMaxExpr>(Op)) |
| 1822 | return SExt; |
| 1823 | |
| 1824 | // Absent any other information, use the zext cast value. |
| 1825 | return ZExt; |
| 1826 | } |
| 1827 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1828 | /// CollectAddOperandsWithScales - Process the given Ops list, which is |
| 1829 | /// a list of operands to be added under the given scale, update the given |
| 1830 | /// map. This is a helper function for getAddRecExpr. As an example of |
| 1831 | /// what it does, given a sequence of operands that would form an add |
| 1832 | /// expression like this: |
| 1833 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1834 | /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1835 | /// |
| 1836 | /// where A and B are constants, update the map with these values: |
| 1837 | /// |
| 1838 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1839 | /// |
| 1840 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1841 | /// This will allow getAddRecExpr to produce this: |
| 1842 | /// |
| 1843 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1844 | /// |
| 1845 | /// This form often exposes folding opportunities that are hidden in |
| 1846 | /// the original operand list. |
| 1847 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1848 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1849 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1850 | /// the common case where no interesting opportunities are present, and |
| 1851 | /// is also used as a check to avoid infinite recursion. |
| 1852 | /// |
| 1853 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1854 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1855 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1856 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1857 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1858 | const APInt &Scale, |
| 1859 | ScalarEvolution &SE) { |
| 1860 | bool Interesting = false; |
| 1861 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1862 | // Iterate over the add operands. They are sorted, with constants first. |
| 1863 | unsigned i = 0; |
| 1864 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1865 | ++i; |
| 1866 | // Pull a buried constant out to the outside. |
| 1867 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1868 | Interesting = true; |
| 1869 | AccumulatedConstant += Scale * C->getValue()->getValue(); |
| 1870 | } |
| 1871 | |
| 1872 | // Next comes everything else. We're especially interested in multiplies |
| 1873 | // here, but they're in the middle, so just visit the rest with one loop. |
| 1874 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1875 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 1876 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 1877 | APInt NewScale = |
| 1878 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue(); |
| 1879 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 1880 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1881 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1882 | Interesting |= |
| 1883 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1884 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1885 | NewScale, SE); |
| 1886 | } else { |
| 1887 | // A multiplication of a constant with some other value. Update |
| 1888 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1889 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 1890 | const SCEV *Key = SE.getMulExpr(MulOps); |
| 1891 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Dan Gohman | e00beaa | 2009-06-29 18:25:52 +0000 | [diff] [blame] | 1892 | M.insert(std::make_pair(Key, NewScale)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1893 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1894 | NewOps.push_back(Pair.first->first); |
| 1895 | } else { |
| 1896 | Pair.first->second += NewScale; |
| 1897 | // The map already had an entry for this value, which may indicate |
| 1898 | // a folding opportunity. |
| 1899 | Interesting = true; |
| 1900 | } |
| 1901 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1902 | } else { |
| 1903 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1904 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Dan Gohman | e00beaa | 2009-06-29 18:25:52 +0000 | [diff] [blame] | 1905 | M.insert(std::make_pair(Ops[i], Scale)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1906 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1907 | NewOps.push_back(Pair.first->first); |
| 1908 | } else { |
| 1909 | Pair.first->second += Scale; |
| 1910 | // The map already had an entry for this value, which may indicate |
| 1911 | // a folding opportunity. |
| 1912 | Interesting = true; |
| 1913 | } |
| 1914 | } |
| 1915 | } |
| 1916 | |
| 1917 | return Interesting; |
| 1918 | } |
| 1919 | |
| 1920 | namespace { |
| 1921 | struct APIntCompare { |
| 1922 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 1923 | return LHS.ult(RHS); |
| 1924 | } |
| 1925 | }; |
| 1926 | } |
| 1927 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1928 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 1929 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 1930 | // can't-overflow flags for the operation if possible. |
| 1931 | static SCEV::NoWrapFlags |
| 1932 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 1933 | const SmallVectorImpl<const SCEV *> &Ops, |
| 1934 | SCEV::NoWrapFlags OldFlags) { |
| 1935 | using namespace std::placeholders; |
| 1936 | |
| 1937 | bool CanAnalyze = |
| 1938 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 1939 | (void)CanAnalyze; |
| 1940 | assert(CanAnalyze && "don't call from other places!"); |
| 1941 | |
| 1942 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 1943 | SCEV::NoWrapFlags SignOrUnsignWrap = |
| 1944 | ScalarEvolution::maskFlags(OldFlags, SignOrUnsignMask); |
| 1945 | |
| 1946 | // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. |
| 1947 | auto IsKnownNonNegative = |
| 1948 | std::bind(std::mem_fn(&ScalarEvolution::isKnownNonNegative), SE, _1); |
| 1949 | |
| 1950 | if (SignOrUnsignWrap == SCEV::FlagNSW && |
| 1951 | std::all_of(Ops.begin(), Ops.end(), IsKnownNonNegative)) |
| 1952 | return ScalarEvolution::setFlags(OldFlags, |
| 1953 | (SCEV::NoWrapFlags)SignOrUnsignMask); |
| 1954 | |
| 1955 | return OldFlags; |
| 1956 | } |
| 1957 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 1958 | /// getAddExpr - Get a canonical add expression, or something simpler if |
| 1959 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 1960 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1961 | SCEV::NoWrapFlags Flags) { |
| 1962 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 1963 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1964 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 1965 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 1966 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1967 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 1968 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 1969 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 1970 | "SCEVAddExpr operand types don't match!"); |
| 1971 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1972 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1973 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1974 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1975 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1976 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1977 | |
| 1978 | // If there are any constants, fold them together. |
| 1979 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1980 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1981 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 1982 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1983 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1984 | // We found two constants, fold them together! |
Dan Gohman | 0652fd5 | 2009-06-14 22:47:23 +0000 | [diff] [blame] | 1985 | Ops[0] = getConstant(LHSC->getValue()->getValue() + |
| 1986 | RHSC->getValue()->getValue()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 1987 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 1988 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 1989 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1990 | } |
| 1991 | |
| 1992 | // If we are left with a constant zero being added, strip it off. |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 1993 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1994 | Ops.erase(Ops.begin()); |
| 1995 | --Idx; |
| 1996 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1997 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 1998 | if (Ops.size() == 1) return Ops[0]; |
| 1999 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2000 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2001 | // Okay, check to see if the same value occurs in the operand list more than |
| 2002 | // once. If so, merge them together into an multiply expression. Since we |
| 2003 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2004 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2005 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2006 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2007 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2008 | // Scan ahead to count how many equal operands there are. |
| 2009 | unsigned Count = 2; |
| 2010 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2011 | ++Count; |
| 2012 | // Merge the values into a multiply. |
| 2013 | const SCEV *Scale = getConstant(Ty, Count); |
| 2014 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2015 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2016 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2017 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2018 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2019 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2020 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2021 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2022 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2023 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2024 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2025 | // Check for truncates. If all the operands are truncated from the same |
| 2026 | // type, see if factoring out the truncate would permit the result to be |
| 2027 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2028 | // if the contents of the resulting outer trunc fold to something simple. |
| 2029 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2030 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2031 | Type *DstType = Trunc->getType(); |
| 2032 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2033 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2034 | bool Ok = true; |
| 2035 | // Check all the operands to see if they can be represented in the |
| 2036 | // source type of the truncate. |
| 2037 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2038 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2039 | if (T->getOperand()->getType() != SrcType) { |
| 2040 | Ok = false; |
| 2041 | break; |
| 2042 | } |
| 2043 | LargeOps.push_back(T->getOperand()); |
| 2044 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2045 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2046 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2047 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2048 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2049 | if (const SCEVTruncateExpr *T = |
| 2050 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2051 | if (T->getOperand()->getType() != SrcType) { |
| 2052 | Ok = false; |
| 2053 | break; |
| 2054 | } |
| 2055 | LargeMulOps.push_back(T->getOperand()); |
| 2056 | } else if (const SCEVConstant *C = |
| 2057 | dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2058 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2059 | } else { |
| 2060 | Ok = false; |
| 2061 | break; |
| 2062 | } |
| 2063 | } |
| 2064 | if (Ok) |
| 2065 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2066 | } else { |
| 2067 | Ok = false; |
| 2068 | break; |
| 2069 | } |
| 2070 | } |
| 2071 | if (Ok) { |
| 2072 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2073 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2074 | // If it folds to something simple, use it. Otherwise, don't. |
| 2075 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2076 | return getTruncateExpr(Fold, DstType); |
| 2077 | } |
| 2078 | } |
| 2079 | |
| 2080 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2081 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2082 | ++Idx; |
| 2083 | |
| 2084 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2085 | if (Idx < Ops.size()) { |
| 2086 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2087 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2088 | // If we have an add, expand the add operands onto the end of the operands |
| 2089 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2090 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2091 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2092 | DeletedAdd = true; |
| 2093 | } |
| 2094 | |
| 2095 | // If we deleted at least one add, we added operands to the end of the list, |
| 2096 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2097 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2098 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2099 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2100 | } |
| 2101 | |
| 2102 | // Skip over the add expression until we get to a multiply. |
| 2103 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2104 | ++Idx; |
| 2105 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2106 | // Check to see if there are any folding opportunities present with |
| 2107 | // operands multiplied by constant values. |
| 2108 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2109 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2110 | DenseMap<const SCEV *, APInt> M; |
| 2111 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2112 | APInt AccumulatedConstant(BitWidth, 0); |
| 2113 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2114 | Ops.data(), Ops.size(), |
| 2115 | APInt(BitWidth, 1), *this)) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2116 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2117 | // re-generate the operands list. Group the operands by constant scale, |
| 2118 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2119 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Craig Topper | 31ee586 | 2013-07-03 15:07:05 +0000 | [diff] [blame] | 2120 | for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2121 | E = NewOps.end(); I != E; ++I) |
| 2122 | MulOpLists[M.find(*I)->second].push_back(*I); |
| 2123 | // Re-generate the operands list. |
| 2124 | Ops.clear(); |
| 2125 | if (AccumulatedConstant != 0) |
| 2126 | Ops.push_back(getConstant(AccumulatedConstant)); |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2127 | for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator |
| 2128 | I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I) |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2129 | if (I->first != 0) |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2130 | Ops.push_back(getMulExpr(getConstant(I->first), |
| 2131 | getAddExpr(I->second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2132 | if (Ops.empty()) |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 2133 | return getConstant(Ty, 0); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2134 | if (Ops.size() == 1) |
| 2135 | return Ops[0]; |
| 2136 | return getAddExpr(Ops); |
| 2137 | } |
| 2138 | } |
| 2139 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2140 | // If we are adding something to a multiply expression, make sure the |
| 2141 | // something is not already an operand of the multiply. If so, merge it into |
| 2142 | // the multiply. |
| 2143 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2144 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2145 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2146 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2147 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2148 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2149 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2150 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2151 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2152 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2153 | if (Mul->getNumOperands() != 2) { |
| 2154 | // If the multiply has more than two operands, we must get the |
| 2155 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2156 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2157 | Mul->op_begin()+MulOp); |
| 2158 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2159 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2160 | } |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 2161 | const SCEV *One = getConstant(Ty, 1); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2162 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2163 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2164 | if (Ops.size() == 2) return OuterMul; |
| 2165 | if (AddOp < Idx) { |
| 2166 | Ops.erase(Ops.begin()+AddOp); |
| 2167 | Ops.erase(Ops.begin()+Idx-1); |
| 2168 | } else { |
| 2169 | Ops.erase(Ops.begin()+Idx); |
| 2170 | Ops.erase(Ops.begin()+AddOp-1); |
| 2171 | } |
| 2172 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2173 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2174 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2175 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2176 | // Check this multiply against other multiplies being added together. |
| 2177 | for (unsigned OtherMulIdx = Idx+1; |
| 2178 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2179 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2180 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2181 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2182 | // together. |
| 2183 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2184 | OMulOp != e; ++OMulOp) |
| 2185 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2186 | // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2187 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2188 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2189 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2190 | Mul->op_begin()+MulOp); |
| 2191 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2192 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2193 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2194 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2195 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2196 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2197 | OtherMul->op_begin()+OMulOp); |
| 2198 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2199 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2200 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2201 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2202 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2203 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2204 | Ops.erase(Ops.begin()+Idx); |
| 2205 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2206 | Ops.push_back(OuterMul); |
| 2207 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2208 | } |
| 2209 | } |
| 2210 | } |
| 2211 | } |
| 2212 | |
| 2213 | // If there are any add recurrences in the operands list, see if any other |
| 2214 | // added values are loop invariant. If so, we can fold them into the |
| 2215 | // recurrence. |
| 2216 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2217 | ++Idx; |
| 2218 | |
| 2219 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2220 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2221 | // Scan all of the other operands to this add and add them to the vector if |
| 2222 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2223 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2224 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2225 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2226 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2227 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2228 | LIOps.push_back(Ops[i]); |
| 2229 | Ops.erase(Ops.begin()+i); |
| 2230 | --i; --e; |
| 2231 | } |
| 2232 | |
| 2233 | // If we found some loop invariants, fold them into the recurrence. |
| 2234 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2235 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2236 | LIOps.push_back(AddRec->getStart()); |
| 2237 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2238 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2239 | AddRec->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2240 | AddRecOps[0] = getAddExpr(LIOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2241 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2242 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
Eric Christopher | 23bf3ba | 2011-01-11 09:02:09 +0000 | [diff] [blame] | 2243 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2244 | // Always propagate NW. |
| 2245 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2246 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2247 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2248 | // If all of the other operands were loop invariant, we are done. |
| 2249 | if (Ops.size() == 1) return NewRec; |
| 2250 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2251 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2252 | for (unsigned i = 0;; ++i) |
| 2253 | if (Ops[i] == AddRec) { |
| 2254 | Ops[i] = NewRec; |
| 2255 | break; |
| 2256 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2257 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2258 | } |
| 2259 | |
| 2260 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2261 | // there are multiple AddRec's with the same loop induction variable being |
| 2262 | // added together. If so, we can fold them. |
| 2263 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2264 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2265 | ++OtherIdx) |
| 2266 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2267 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2268 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2269 | AddRec->op_end()); |
| 2270 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2271 | ++OtherIdx) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2272 | if (const SCEVAddRecExpr *OtherAddRec = |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2273 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2274 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2275 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2276 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2277 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2278 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2279 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2280 | break; |
| 2281 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2282 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2283 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2284 | } |
| 2285 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2286 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2287 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2288 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2289 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2290 | } |
| 2291 | |
| 2292 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2293 | // next one. |
| 2294 | } |
| 2295 | |
| 2296 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2297 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2298 | FoldingSetNodeID ID; |
| 2299 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2300 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2301 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2302 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2303 | SCEVAddExpr *S = |
| 2304 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2305 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2306 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2307 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2308 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2309 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2310 | UniqueSCEVs.InsertNode(S, IP); |
| 2311 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2312 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2313 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2314 | } |
| 2315 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2316 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2317 | uint64_t k = i*j; |
| 2318 | if (j > 1 && k / j != i) Overflow = true; |
| 2319 | return k; |
| 2320 | } |
| 2321 | |
| 2322 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2323 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2324 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2325 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2326 | // We use the multiplicative formula: |
| 2327 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2328 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2329 | // (k-n)th term of the denominator. This division will always produce an |
| 2330 | // integral result, and helps reduce the chance of overflow in the |
| 2331 | // intermediate computations. However, we can still overflow even when the |
| 2332 | // final result would fit. |
| 2333 | |
| 2334 | if (n == 0 || n == k) return 1; |
| 2335 | if (k > n) return 0; |
| 2336 | |
| 2337 | if (k > n/2) |
| 2338 | k = n-k; |
| 2339 | |
| 2340 | uint64_t r = 1; |
| 2341 | for (uint64_t i = 1; i <= k; ++i) { |
| 2342 | r = umul_ov(r, n-(i-1), Overflow); |
| 2343 | r /= i; |
| 2344 | } |
| 2345 | return r; |
| 2346 | } |
| 2347 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2348 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2349 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2350 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2351 | SmallVector<const SCEV *, 4> Ops; |
| 2352 | Ops.push_back(StartExpr); |
| 2353 | while (!Ops.empty()) { |
| 2354 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2355 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2356 | return true; |
| 2357 | |
| 2358 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2359 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2360 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2361 | } |
| 2362 | } |
| 2363 | return false; |
| 2364 | } |
| 2365 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2366 | /// getMulExpr - Get a canonical multiply expression, or something simpler if |
| 2367 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2368 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2369 | SCEV::NoWrapFlags Flags) { |
| 2370 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2371 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2372 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2373 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2374 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2375 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2376 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2377 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2378 | "SCEVMulExpr operand types don't match!"); |
| 2379 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2380 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2381 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2382 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2383 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2384 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2385 | |
| 2386 | // If there are any constants, fold them together. |
| 2387 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2388 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2389 | |
| 2390 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2391 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2392 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2393 | // If any of Add's ops are Adds or Muls with a constant, |
| 2394 | // apply this transformation as well. |
| 2395 | if (Add->getNumOperands() == 2) |
| 2396 | if (containsConstantSomewhere(Add)) |
| 2397 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2398 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2399 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2400 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2401 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2402 | // We found two constants, fold them together! |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 2403 | ConstantInt *Fold = ConstantInt::get(getContext(), |
| 2404 | LHSC->getValue()->getValue() * |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2405 | RHSC->getValue()->getValue()); |
| 2406 | Ops[0] = getConstant(Fold); |
| 2407 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2408 | if (Ops.size() == 1) return Ops[0]; |
| 2409 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2410 | } |
| 2411 | |
| 2412 | // If we are left with a constant one being multiplied, strip it off. |
| 2413 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2414 | Ops.erase(Ops.begin()); |
| 2415 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2416 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2417 | // If we have a multiply of zero, it will always be zero. |
| 2418 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2419 | } else if (Ops[0]->isAllOnesValue()) { |
| 2420 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2421 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2422 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2423 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2424 | SmallVector<const SCEV *, 4> NewOps; |
| 2425 | bool AnyFolded = false; |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2426 | for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), |
| 2427 | E = Add->op_end(); I != E; ++I) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2428 | const SCEV *Mul = getMulExpr(Ops[0], *I); |
| 2429 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2430 | NewOps.push_back(Mul); |
| 2431 | } |
| 2432 | if (AnyFolded) |
| 2433 | return getAddExpr(NewOps); |
| 2434 | } |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2435 | else if (const SCEVAddRecExpr * |
| 2436 | AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
| 2437 | // Negation preserves a recurrence's no self-wrap property. |
| 2438 | SmallVector<const SCEV *, 4> Operands; |
| 2439 | for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(), |
| 2440 | E = AddRec->op_end(); I != E; ++I) { |
| 2441 | Operands.push_back(getMulExpr(Ops[0], *I)); |
| 2442 | } |
| 2443 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2444 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2445 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2446 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2447 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2448 | |
| 2449 | if (Ops.size() == 1) |
| 2450 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2451 | } |
| 2452 | |
| 2453 | // Skip over the add expression until we get to a multiply. |
| 2454 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2455 | ++Idx; |
| 2456 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2457 | // If there are mul operands inline them all into this expression. |
| 2458 | if (Idx < Ops.size()) { |
| 2459 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2460 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2461 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2462 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2463 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2464 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2465 | DeletedMul = true; |
| 2466 | } |
| 2467 | |
| 2468 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2469 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2470 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2471 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2472 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2473 | } |
| 2474 | |
| 2475 | // If there are any add recurrences in the operands list, see if any other |
| 2476 | // added values are loop invariant. If so, we can fold them into the |
| 2477 | // recurrence. |
| 2478 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2479 | ++Idx; |
| 2480 | |
| 2481 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2482 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2483 | // Scan all of the other operands to this mul and add them to the vector if |
| 2484 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2485 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2486 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2487 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2488 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2489 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2490 | LIOps.push_back(Ops[i]); |
| 2491 | Ops.erase(Ops.begin()+i); |
| 2492 | --i; --e; |
| 2493 | } |
| 2494 | |
| 2495 | // If we found some loop invariants, fold them into the recurrence. |
| 2496 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2497 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2498 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2499 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2500 | const SCEV *Scale = getMulExpr(LIOps); |
| 2501 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2502 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2503 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2504 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2505 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2506 | // |
| 2507 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2508 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2509 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2510 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2511 | |
| 2512 | // If all of the other operands were loop invariant, we are done. |
| 2513 | if (Ops.size() == 1) return NewRec; |
| 2514 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2515 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2516 | for (unsigned i = 0;; ++i) |
| 2517 | if (Ops[i] == AddRec) { |
| 2518 | Ops[i] = NewRec; |
| 2519 | break; |
| 2520 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2521 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2522 | } |
| 2523 | |
| 2524 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2525 | // there are multiple AddRec's with the same loop induction variable being |
| 2526 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2527 | |
| 2528 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2529 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2530 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2531 | // ]]],+,...up to x=2n}. |
| 2532 | // Note that the arguments to choose() are always integers with values |
| 2533 | // known at compile time, never SCEV objects. |
| 2534 | // |
| 2535 | // The implementation avoids pointless extra computations when the two |
| 2536 | // addrec's are of different length (mathematically, it's equivalent to |
| 2537 | // an infinite stream of zeros on the right). |
| 2538 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2539 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2540 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2541 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2542 | const SCEVAddRecExpr *OtherAddRec = |
| 2543 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2544 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2545 | continue; |
| 2546 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2547 | bool Overflow = false; |
| 2548 | Type *Ty = AddRec->getType(); |
| 2549 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2550 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2551 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2552 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
| 2553 | const SCEV *Term = getConstant(Ty, 0); |
| 2554 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2555 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2556 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2557 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2558 | z < ze && !Overflow; ++z) { |
| 2559 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2560 | uint64_t Coeff; |
| 2561 | if (LargerThan64Bits) |
| 2562 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2563 | else |
| 2564 | Coeff = Coeff1*Coeff2; |
| 2565 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2566 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2567 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2568 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2569 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2570 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2571 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2572 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2573 | if (!Overflow) { |
| 2574 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2575 | SCEV::FlagAnyWrap); |
| 2576 | if (Ops.size() == 2) return NewAddRec; |
| 2577 | Ops[Idx] = NewAddRec; |
| 2578 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2579 | OpsModified = true; |
| 2580 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2581 | if (!AddRec) |
| 2582 | break; |
| 2583 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2584 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2585 | if (OpsModified) |
| 2586 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2587 | |
| 2588 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2589 | // next one. |
| 2590 | } |
| 2591 | |
| 2592 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2593 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2594 | FoldingSetNodeID ID; |
| 2595 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2596 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2597 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2598 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2599 | SCEVMulExpr *S = |
| 2600 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2601 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2602 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2603 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2604 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2605 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2606 | UniqueSCEVs.InsertNode(S, IP); |
| 2607 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2608 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2609 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2610 | } |
| 2611 | |
Andreas Bolka | 7a5c8db | 2009-08-07 22:55:26 +0000 | [diff] [blame] | 2612 | /// getUDivExpr - Get a canonical unsigned division expression, or something |
| 2613 | /// simpler if possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2614 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2615 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2616 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2617 | getEffectiveSCEVType(RHS->getType()) && |
| 2618 | "SCEVUDivExpr operand types don't match!"); |
| 2619 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2620 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2621 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2622 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2623 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2624 | // try to analyze it, because the resolution chosen here may differ from |
| 2625 | // the resolution chosen in other parts of the compiler. |
| 2626 | if (!RHSC->getValue()->isZero()) { |
| 2627 | // Determine if the division can be folded into the operands of |
| 2628 | // its operands. |
| 2629 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2630 | Type *Ty = LHS->getType(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2631 | unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2632 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2633 | // For non-power-of-two values, effectively round the value up to the |
| 2634 | // nearest power of two. |
| 2635 | if (!RHSC->getValue()->getValue().isPowerOf2()) |
| 2636 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2637 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2638 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2639 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2640 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2641 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2642 | // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. |
| 2643 | const APInt &StepInt = Step->getValue()->getValue(); |
| 2644 | const APInt &DivInt = RHSC->getValue()->getValue(); |
| 2645 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2646 | getZeroExtendExpr(AR, ExtTy) == |
| 2647 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2648 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2649 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2650 | SmallVector<const SCEV *, 4> Operands; |
| 2651 | for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i) |
| 2652 | Operands.push_back(getUDivExpr(AR->getOperand(i), RHS)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2653 | return getAddRecExpr(Operands, AR->getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2654 | SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2655 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2656 | /// Get a canonical UDivExpr for a recurrence. |
| 2657 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2658 | // We can currently only fold X%N if X is constant. |
| 2659 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2660 | if (StartC && !DivInt.urem(StepInt) && |
| 2661 | getZeroExtendExpr(AR, ExtTy) == |
| 2662 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2663 | getZeroExtendExpr(Step, ExtTy), |
| 2664 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
| 2665 | const APInt &StartInt = StartC->getValue()->getValue(); |
| 2666 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2667 | if (StartRem != 0) |
| 2668 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2669 | AR->getLoop(), SCEV::FlagNW); |
| 2670 | } |
| 2671 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2672 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2673 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2674 | SmallVector<const SCEV *, 4> Operands; |
| 2675 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) |
| 2676 | Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy)); |
| 2677 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2678 | // Find an operand that's safely divisible. |
| 2679 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2680 | const SCEV *Op = M->getOperand(i); |
| 2681 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2682 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2683 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2684 | M->op_end()); |
| 2685 | Operands[i] = Div; |
| 2686 | return getMulExpr(Operands); |
| 2687 | } |
| 2688 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2689 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2690 | // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. |
Andrew Trick | 7d1eea8 | 2011-04-27 18:17:36 +0000 | [diff] [blame] | 2691 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2692 | SmallVector<const SCEV *, 4> Operands; |
| 2693 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) |
| 2694 | Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy)); |
| 2695 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2696 | Operands.clear(); |
| 2697 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2698 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2699 | if (isa<SCEVUDivExpr>(Op) || |
| 2700 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2701 | break; |
| 2702 | Operands.push_back(Op); |
| 2703 | } |
| 2704 | if (Operands.size() == A->getNumOperands()) |
| 2705 | return getAddExpr(Operands); |
| 2706 | } |
| 2707 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2708 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2709 | // Fold if both operands are constant. |
| 2710 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2711 | Constant *LHSCV = LHSC->getValue(); |
| 2712 | Constant *RHSCV = RHSC->getValue(); |
| 2713 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2714 | RHSCV))); |
| 2715 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2716 | } |
| 2717 | } |
| 2718 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2719 | FoldingSetNodeID ID; |
| 2720 | ID.AddInteger(scUDivExpr); |
| 2721 | ID.AddPointer(LHS); |
| 2722 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2723 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2724 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2725 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2726 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2727 | UniqueSCEVs.InsertNode(S, IP); |
| 2728 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2729 | } |
| 2730 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2731 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
| 2732 | APInt A = C1->getValue()->getValue().abs(); |
| 2733 | APInt B = C2->getValue()->getValue().abs(); |
| 2734 | uint32_t ABW = A.getBitWidth(); |
| 2735 | uint32_t BBW = B.getBitWidth(); |
| 2736 | |
| 2737 | if (ABW > BBW) |
| 2738 | B = B.zext(ABW); |
| 2739 | else if (ABW < BBW) |
| 2740 | A = A.zext(BBW); |
| 2741 | |
| 2742 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2743 | } |
| 2744 | |
| 2745 | /// getUDivExactExpr - Get a canonical unsigned division expression, or |
| 2746 | /// something simpler if possible. There is no representation for an exact udiv |
| 2747 | /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS. |
| 2748 | /// We can't do this when it's not exact because the udiv may be clearing bits. |
| 2749 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2750 | const SCEV *RHS) { |
| 2751 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2752 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2753 | // end of this file for inspiration. |
| 2754 | |
| 2755 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2756 | if (!Mul) |
| 2757 | return getUDivExpr(LHS, RHS); |
| 2758 | |
| 2759 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2760 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2761 | // first element of the mulexpr. |
| 2762 | if (const SCEVConstant *LHSCst = |
| 2763 | dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
| 2764 | if (LHSCst == RHSCst) { |
| 2765 | SmallVector<const SCEV *, 2> Operands; |
| 2766 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2767 | return getMulExpr(Operands); |
| 2768 | } |
| 2769 | |
| 2770 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2771 | // that there's a factor provided by one of the other terms. We need to |
| 2772 | // check. |
| 2773 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2774 | if (!Factor.isIntN(1)) { |
| 2775 | LHSCst = cast<SCEVConstant>( |
| 2776 | getConstant(LHSCst->getValue()->getValue().udiv(Factor))); |
| 2777 | RHSCst = cast<SCEVConstant>( |
| 2778 | getConstant(RHSCst->getValue()->getValue().udiv(Factor))); |
| 2779 | SmallVector<const SCEV *, 2> Operands; |
| 2780 | Operands.push_back(LHSCst); |
| 2781 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2782 | LHS = getMulExpr(Operands); |
| 2783 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2784 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2785 | if (!Mul) |
| 2786 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2787 | } |
| 2788 | } |
| 2789 | } |
| 2790 | |
| 2791 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2792 | if (Mul->getOperand(i) == RHS) { |
| 2793 | SmallVector<const SCEV *, 2> Operands; |
| 2794 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2795 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2796 | return getMulExpr(Operands); |
| 2797 | } |
| 2798 | } |
| 2799 | |
| 2800 | return getUDivExpr(LHS, RHS); |
| 2801 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2802 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2803 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2804 | /// Simplify the expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2805 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2806 | const Loop *L, |
| 2807 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2808 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2809 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2810 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2811 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2812 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2813 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2814 | } |
| 2815 | |
| 2816 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2817 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2818 | } |
| 2819 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2820 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2821 | /// Simplify the expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2822 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2823 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2824 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2825 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2826 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2827 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2828 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2829 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2830 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2831 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2832 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2833 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2834 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2835 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2836 | if (Operands.back()->isZero()) { |
| 2837 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2838 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2839 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2840 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2841 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2842 | // use that information to infer NUW and NSW flags. However, computing a |
| 2843 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2844 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2845 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2846 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2847 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2848 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2849 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2850 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2851 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2852 | if (L->contains(NestedLoop) |
| 2853 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2854 | : (!NestedLoop->contains(L) && |
| 2855 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2856 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2857 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2858 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2859 | // AddRecs require their operands be loop-invariant with respect to their |
| 2860 | // loops. Don't perform this transformation if it would break this |
| 2861 | // requirement. |
| 2862 | bool AllInvariant = true; |
| 2863 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2864 | if (!isLoopInvariant(Operands[i], L)) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2865 | AllInvariant = false; |
| 2866 | break; |
| 2867 | } |
| 2868 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2869 | // Create a recurrence for the outer loop with the same step size. |
| 2870 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2871 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 2872 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2873 | SCEV::NoWrapFlags OuterFlags = |
| 2874 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2875 | |
| 2876 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2877 | AllInvariant = true; |
| 2878 | for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2879 | if (!isLoopInvariant(NestedOperands[i], NestedLoop)) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2880 | AllInvariant = false; |
| 2881 | break; |
| 2882 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2883 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2884 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2885 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2886 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 2887 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2888 | SCEV::NoWrapFlags InnerFlags = |
| 2889 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2890 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 2891 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2892 | } |
| 2893 | // Reset Operands to its original state. |
| 2894 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2895 | } |
| 2896 | } |
| 2897 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 2898 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 2899 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2900 | FoldingSetNodeID ID; |
| 2901 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2902 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 2903 | ID.AddPointer(Operands[i]); |
| 2904 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2905 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2906 | SCEVAddRecExpr *S = |
| 2907 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2908 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2909 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 2910 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2911 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 2912 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2913 | UniqueSCEVs.InsertNode(S, IP); |
| 2914 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2915 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2916 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2917 | } |
| 2918 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2919 | const SCEV * |
| 2920 | ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, |
| 2921 | const SmallVectorImpl<const SCEV *> &IndexExprs, |
| 2922 | bool InBounds) { |
| 2923 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 2924 | // because SCEV::getType() preserves the address space. |
| 2925 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 2926 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 2927 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 2928 | // flow and the no-overflow bits may not be valid for the expression in any |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 2929 | // context. This can be fixed similarly to how these flags are handled for |
| 2930 | // adds. |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2931 | SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 2932 | |
| 2933 | const SCEV *TotalOffset = getConstant(IntPtrTy, 0); |
| 2934 | // The address space is unimportant. The first thing we do on CurTy is getting |
| 2935 | // its element type. |
| 2936 | Type *CurTy = PointerType::getUnqual(PointeeType); |
| 2937 | for (const SCEV *IndexExpr : IndexExprs) { |
| 2938 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 2939 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 2940 | // For a struct, add the member offset. |
| 2941 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 2942 | unsigned FieldNo = Index->getZExtValue(); |
| 2943 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 2944 | |
| 2945 | // Add the field offset to the running total offset. |
| 2946 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 2947 | |
| 2948 | // Update CurTy to the type of the field at Index. |
| 2949 | CurTy = STy->getTypeAtIndex(Index); |
| 2950 | } else { |
| 2951 | // Update CurTy to its element type. |
| 2952 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 2953 | // For an array, add the element offset, explicitly scaled. |
| 2954 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 2955 | // Getelementptr indices are signed. |
| 2956 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 2957 | |
| 2958 | // Multiply the index by the element size to compute the element offset. |
| 2959 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 2960 | |
| 2961 | // Add the element offset to the running total offset. |
| 2962 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 2963 | } |
| 2964 | } |
| 2965 | |
| 2966 | // Add the total offset from all the GEP indices to the base. |
| 2967 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 2968 | } |
| 2969 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2970 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 2971 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2972 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2973 | Ops.push_back(LHS); |
| 2974 | Ops.push_back(RHS); |
| 2975 | return getSMaxExpr(Ops); |
| 2976 | } |
| 2977 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2978 | const SCEV * |
| 2979 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2980 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 2981 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2982 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2983 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2984 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2985 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2986 | "SCEVSMaxExpr operand types don't match!"); |
| 2987 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2988 | |
| 2989 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2990 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2991 | |
| 2992 | // If there are any constants, fold them together. |
| 2993 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2994 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2995 | ++Idx; |
| 2996 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2997 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2998 | // We found two constants, fold them together! |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 2999 | ConstantInt *Fold = ConstantInt::get(getContext(), |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3000 | APIntOps::smax(LHSC->getValue()->getValue(), |
| 3001 | RHSC->getValue()->getValue())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3002 | Ops[0] = getConstant(Fold); |
| 3003 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3004 | if (Ops.size() == 1) return Ops[0]; |
| 3005 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3006 | } |
| 3007 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3008 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3009 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3010 | Ops.erase(Ops.begin()); |
| 3011 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3012 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3013 | // If we have an smax with a constant maximum-int, it will always be |
| 3014 | // maximum-int. |
| 3015 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3016 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3017 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3018 | if (Ops.size() == 1) return Ops[0]; |
| 3019 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3020 | |
| 3021 | // Find the first SMax |
| 3022 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3023 | ++Idx; |
| 3024 | |
| 3025 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3026 | // onto our operand list, and recurse to simplify. |
| 3027 | if (Idx < Ops.size()) { |
| 3028 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3029 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3030 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3031 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3032 | DeletedSMax = true; |
| 3033 | } |
| 3034 | |
| 3035 | if (DeletedSMax) |
| 3036 | return getSMaxExpr(Ops); |
| 3037 | } |
| 3038 | |
| 3039 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3040 | // so, delete one. Since we sorted the list, these values are required to |
| 3041 | // be adjacent. |
| 3042 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3043 | // X smax Y smax Y --> X smax Y |
| 3044 | // X smax Y --> X, if X is always greater than Y |
| 3045 | if (Ops[i] == Ops[i+1] || |
| 3046 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3047 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3048 | --i; --e; |
| 3049 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3050 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3051 | --i; --e; |
| 3052 | } |
| 3053 | |
| 3054 | if (Ops.size() == 1) return Ops[0]; |
| 3055 | |
| 3056 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3057 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3058 | // Okay, it looks like we really DO need an smax expr. Check to see if we |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3059 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3060 | FoldingSetNodeID ID; |
| 3061 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3062 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3063 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3064 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3065 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3066 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3067 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3068 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3069 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3070 | UniqueSCEVs.InsertNode(S, IP); |
| 3071 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3072 | } |
| 3073 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3074 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3075 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3076 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3077 | Ops.push_back(LHS); |
| 3078 | Ops.push_back(RHS); |
| 3079 | return getUMaxExpr(Ops); |
| 3080 | } |
| 3081 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3082 | const SCEV * |
| 3083 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3084 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3085 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3086 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3087 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3088 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3089 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3090 | "SCEVUMaxExpr operand types don't match!"); |
| 3091 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3092 | |
| 3093 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3094 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3095 | |
| 3096 | // If there are any constants, fold them together. |
| 3097 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3098 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3099 | ++Idx; |
| 3100 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3101 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3102 | // We found two constants, fold them together! |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 3103 | ConstantInt *Fold = ConstantInt::get(getContext(), |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3104 | APIntOps::umax(LHSC->getValue()->getValue(), |
| 3105 | RHSC->getValue()->getValue())); |
| 3106 | Ops[0] = getConstant(Fold); |
| 3107 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3108 | if (Ops.size() == 1) return Ops[0]; |
| 3109 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3110 | } |
| 3111 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3112 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3113 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3114 | Ops.erase(Ops.begin()); |
| 3115 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3116 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3117 | // If we have an umax with a constant maximum-int, it will always be |
| 3118 | // maximum-int. |
| 3119 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3120 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3121 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3122 | if (Ops.size() == 1) return Ops[0]; |
| 3123 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3124 | |
| 3125 | // Find the first UMax |
| 3126 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3127 | ++Idx; |
| 3128 | |
| 3129 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3130 | // onto our operand list, and recurse to simplify. |
| 3131 | if (Idx < Ops.size()) { |
| 3132 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3133 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3134 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3135 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3136 | DeletedUMax = true; |
| 3137 | } |
| 3138 | |
| 3139 | if (DeletedUMax) |
| 3140 | return getUMaxExpr(Ops); |
| 3141 | } |
| 3142 | |
| 3143 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3144 | // so, delete one. Since we sorted the list, these values are required to |
| 3145 | // be adjacent. |
| 3146 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3147 | // X umax Y umax Y --> X umax Y |
| 3148 | // X umax Y --> X, if X is always greater than Y |
| 3149 | if (Ops[i] == Ops[i+1] || |
| 3150 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3151 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3152 | --i; --e; |
| 3153 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3154 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3155 | --i; --e; |
| 3156 | } |
| 3157 | |
| 3158 | if (Ops.size() == 1) return Ops[0]; |
| 3159 | |
| 3160 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3161 | |
| 3162 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3163 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3164 | FoldingSetNodeID ID; |
| 3165 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3166 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3167 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3168 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3169 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3170 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3171 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3172 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3173 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3174 | UniqueSCEVs.InsertNode(S, IP); |
| 3175 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3176 | } |
| 3177 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3178 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3179 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3180 | // ~smax(~x, ~y) == smin(x, y). |
| 3181 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3182 | } |
| 3183 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3184 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3185 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3186 | // ~umax(~x, ~y) == umin(x, y) |
| 3187 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3188 | } |
| 3189 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3190 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3191 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3192 | // constant expression and then folding it back into a ConstantInt. |
| 3193 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3194 | return getConstant(IntTy, |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3195 | F.getParent()->getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3196 | } |
| 3197 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3198 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3199 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3200 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3201 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3202 | // constant expression and then folding it back into a ConstantInt. |
| 3203 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3204 | return getConstant( |
| 3205 | IntTy, |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3206 | F.getParent()->getDataLayout().getStructLayout(STy)->getElementOffset( |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3207 | FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3208 | } |
| 3209 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3210 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3211 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3212 | // here. createSCEV only calls getUnknown after checking for all other |
| 3213 | // interesting possibilities, and any other code that calls getUnknown |
| 3214 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3215 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3216 | FoldingSetNodeID ID; |
| 3217 | ID.AddInteger(scUnknown); |
| 3218 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3219 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3220 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3221 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3222 | "Stale SCEVUnknown in uniquing map!"); |
| 3223 | return S; |
| 3224 | } |
| 3225 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3226 | FirstUnknown); |
| 3227 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3228 | UniqueSCEVs.InsertNode(S, IP); |
| 3229 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3230 | } |
| 3231 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3232 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3233 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3234 | // |
| 3235 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3236 | /// isSCEVable - Test if values of the given type are analyzable within |
| 3237 | /// the SCEV framework. This primarily includes integer types, and it |
| 3238 | /// can optionally include pointer types if the ScalarEvolution class |
| 3239 | /// has access to target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3240 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3241 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3242 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3243 | } |
| 3244 | |
| 3245 | /// getTypeSizeInBits - Return the size in bits of the specified type, |
| 3246 | /// for which isSCEVable must return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3247 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3248 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3249 | return F.getParent()->getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3250 | } |
| 3251 | |
| 3252 | /// getEffectiveSCEVType - Return a type with the same bitwidth as |
| 3253 | /// the given type and which represents how SCEV will treat the given |
| 3254 | /// type, for which isSCEVable must return true. For pointer types, |
| 3255 | /// this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3256 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3257 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3258 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3259 | if (Ty->isIntegerTy()) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3260 | return Ty; |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3261 | } |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3262 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3263 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3264 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3265 | return F.getParent()->getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3266 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3267 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3268 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3269 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3270 | } |
| 3271 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3272 | namespace { |
| 3273 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3274 | // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne |
| 3275 | // is set iff if find such SCEVUnknown. |
| 3276 | // |
| 3277 | struct FindInvalidSCEVUnknown { |
| 3278 | bool FindOne; |
| 3279 | FindInvalidSCEVUnknown() { FindOne = false; } |
| 3280 | bool follow(const SCEV *S) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 3281 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3282 | case scConstant: |
| 3283 | return false; |
| 3284 | case scUnknown: |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3285 | if (!cast<SCEVUnknown>(S)->getValue()) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3286 | FindOne = true; |
| 3287 | return false; |
| 3288 | default: |
| 3289 | return true; |
| 3290 | } |
| 3291 | } |
| 3292 | bool isDone() const { return FindOne; } |
| 3293 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 3294 | } |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3295 | |
| 3296 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
| 3297 | FindInvalidSCEVUnknown F; |
| 3298 | SCEVTraversal<FindInvalidSCEVUnknown> ST(F); |
| 3299 | ST.visitAll(S); |
| 3300 | |
| 3301 | return !F.FindOne; |
| 3302 | } |
| 3303 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3304 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 3305 | /// expression and create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3306 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3307 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3308 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3309 | const SCEV *S = getExistingSCEV(V); |
| 3310 | if (S == nullptr) { |
| 3311 | S = createSCEV(V); |
| 3312 | ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S)); |
| 3313 | } |
| 3314 | return S; |
| 3315 | } |
| 3316 | |
| 3317 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3318 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3319 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3320 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3321 | if (I != ValueExprMap.end()) { |
| 3322 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3323 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3324 | return S; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3325 | ValueExprMap.erase(I); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3326 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3327 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3328 | } |
| 3329 | |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3330 | /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V |
| 3331 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3332 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3333 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3334 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3335 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3336 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3337 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3338 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3339 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3340 | return getMulExpr( |
| 3341 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3342 | } |
| 3343 | |
| 3344 | /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3345 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3346 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3347 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3348 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3349 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3350 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3351 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3352 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3353 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3354 | return getMinusSCEV(AllOnes, V); |
| 3355 | } |
| 3356 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3357 | /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. |
Chris Lattner | fc87752 | 2011-01-09 22:26:35 +0000 | [diff] [blame] | 3358 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3359 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3360 | // Fast path: X - X --> 0. |
| 3361 | if (LHS == RHS) |
| 3362 | return getConstant(LHS->getType(), 0); |
| 3363 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3364 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3365 | // makes it so that we cannot make much use of NUW. |
| 3366 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3367 | const bool RHSIsNotMinSigned = |
| 3368 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3369 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3370 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3371 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3372 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3373 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3374 | // (-1)*RHS, we need to prove that RHS != M. |
| 3375 | // |
| 3376 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3377 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3378 | // either by proving that RHS > M or that LHS >= 0. |
| 3379 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3380 | AddFlags = SCEV::FlagNSW; |
| 3381 | } |
| 3382 | } |
| 3383 | |
| 3384 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3385 | // RHS is NSW and LHS >= 0. |
| 3386 | // |
| 3387 | // The difficulty here is that the NSW flag may have been proven |
| 3388 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3389 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3390 | // larger scope than intended. |
| 3391 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3392 | |
| 3393 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3394 | } |
| 3395 | |
| 3396 | /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3397 | /// input value to the specified type. If the type must be extended, it is zero |
| 3398 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3399 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3400 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3401 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3402 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3403 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3404 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3405 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3406 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3407 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3408 | return getTruncateExpr(V, Ty); |
| 3409 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3410 | } |
| 3411 | |
| 3412 | /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3413 | /// input value to the specified type. If the type must be extended, it is sign |
| 3414 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3415 | const SCEV * |
| 3416 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3417 | Type *Ty) { |
| 3418 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3419 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3420 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3421 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3422 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3423 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3424 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3425 | return getTruncateExpr(V, Ty); |
| 3426 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3427 | } |
| 3428 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3429 | /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3430 | /// input value to the specified type. If the type must be extended, it is zero |
| 3431 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3432 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3433 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3434 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3435 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3436 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3437 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3438 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3439 | "getNoopOrZeroExtend cannot truncate!"); |
| 3440 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3441 | return V; // No conversion |
| 3442 | return getZeroExtendExpr(V, Ty); |
| 3443 | } |
| 3444 | |
| 3445 | /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3446 | /// input value to the specified type. If the type must be extended, it is sign |
| 3447 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3448 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3449 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3450 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3451 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3452 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3453 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3454 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3455 | "getNoopOrSignExtend cannot truncate!"); |
| 3456 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3457 | return V; // No conversion |
| 3458 | return getSignExtendExpr(V, Ty); |
| 3459 | } |
| 3460 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3461 | /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of |
| 3462 | /// the input value to the specified type. If the type must be extended, |
| 3463 | /// it is extended with unspecified bits. The conversion must not be |
| 3464 | /// narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3465 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3466 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3467 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3468 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3469 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3470 | "Cannot noop or any extend with non-integer arguments!"); |
| 3471 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3472 | "getNoopOrAnyExtend cannot truncate!"); |
| 3473 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3474 | return V; // No conversion |
| 3475 | return getAnyExtendExpr(V, Ty); |
| 3476 | } |
| 3477 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3478 | /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the |
| 3479 | /// input value to the specified type. The conversion must not be widening. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3480 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3481 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3482 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3483 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3484 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3485 | "Cannot truncate or noop with non-integer arguments!"); |
| 3486 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3487 | "getTruncateOrNoop cannot extend!"); |
| 3488 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3489 | return V; // No conversion |
| 3490 | return getTruncateExpr(V, Ty); |
| 3491 | } |
| 3492 | |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3493 | /// getUMaxFromMismatchedTypes - Promote the operands to the wider of |
| 3494 | /// the types using zero-extension, and then perform a umax operation |
| 3495 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3496 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3497 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3498 | const SCEV *PromotedLHS = LHS; |
| 3499 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3500 | |
| 3501 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3502 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3503 | else |
| 3504 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3505 | |
| 3506 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3507 | } |
| 3508 | |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3509 | /// getUMinFromMismatchedTypes - Promote the operands to the wider of |
| 3510 | /// the types using zero-extension, and then perform a umin operation |
| 3511 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3512 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3513 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3514 | const SCEV *PromotedLHS = LHS; |
| 3515 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3516 | |
| 3517 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3518 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3519 | else |
| 3520 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3521 | |
| 3522 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3523 | } |
| 3524 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3525 | /// getPointerBase - Transitively follow the chain of pointer-type operands |
| 3526 | /// until reaching a SCEV that does not have a single pointer operand. This |
| 3527 | /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, |
| 3528 | /// but corner cases do exist. |
| 3529 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { |
| 3530 | // A pointer operand may evaluate to a nonpointer expression, such as null. |
| 3531 | if (!V->getType()->isPointerTy()) |
| 3532 | return V; |
| 3533 | |
| 3534 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { |
| 3535 | return getPointerBase(Cast->getOperand()); |
| 3536 | } |
| 3537 | else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3538 | const SCEV *PtrOp = nullptr; |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3539 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 3540 | I != E; ++I) { |
| 3541 | if ((*I)->getType()->isPointerTy()) { |
| 3542 | // Cannot find the base of an expression with multiple pointer operands. |
| 3543 | if (PtrOp) |
| 3544 | return V; |
| 3545 | PtrOp = *I; |
| 3546 | } |
| 3547 | } |
| 3548 | if (!PtrOp) |
| 3549 | return V; |
| 3550 | return getPointerBase(PtrOp); |
| 3551 | } |
| 3552 | return V; |
| 3553 | } |
| 3554 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3555 | /// PushDefUseChildren - Push users of the given Instruction |
| 3556 | /// onto the given Worklist. |
| 3557 | static void |
| 3558 | PushDefUseChildren(Instruction *I, |
| 3559 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3560 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3561 | for (User *U : I->users()) |
| 3562 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3563 | } |
| 3564 | |
| 3565 | /// ForgetSymbolicValue - This looks up computed SCEV values for all |
| 3566 | /// instructions that depend on the given instruction and removes them from |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3567 | /// the ValueExprMapType map if they reference SymName. This is used during PHI |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3568 | /// resolution. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 3569 | void |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3570 | ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3571 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3572 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3573 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3574 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3575 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3576 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3577 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3578 | if (!Visited.insert(I).second) |
| 3579 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3580 | |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3581 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 3582 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3583 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3584 | const SCEV *Old = It->second; |
| 3585 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3586 | // Short-circuit the def-use traversal if the symbolic name |
| 3587 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3588 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3589 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3590 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3591 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3592 | // structure, it's a PHI that's in the progress of being computed |
| 3593 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3594 | // additional loop trip count information isn't going to change anything. |
| 3595 | // In the second case, createNodeForPHI will perform the necessary |
| 3596 | // updates on its own when it gets to that point. In the third, we do |
| 3597 | // want to forget the SCEVUnknown. |
| 3598 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3599 | !isa<SCEVUnknown>(Old) || |
| 3600 | (I != PN && Old == SymName)) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3601 | forgetMemoizedResults(Old); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3602 | ValueExprMap.erase(It); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3603 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3604 | } |
| 3605 | |
| 3606 | PushDefUseChildren(I, Worklist); |
| 3607 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3608 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3609 | |
| 3610 | /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in |
| 3611 | /// a loop header, making it a potential recurrence, or it doesn't. |
| 3612 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3613 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3614 | if (const Loop *L = LI.getLoopFor(PN->getParent())) |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3615 | if (L->getHeader() == PN->getParent()) { |
| 3616 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 3617 | // this phi as an addrec if it has a unique entry value and a unique |
| 3618 | // backedge value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3619 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3620 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 3621 | Value *V = PN->getIncomingValue(i); |
| 3622 | if (L->contains(PN->getIncomingBlock(i))) { |
| 3623 | if (!BEValueV) { |
| 3624 | BEValueV = V; |
| 3625 | } else if (BEValueV != V) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3626 | BEValueV = nullptr; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3627 | break; |
| 3628 | } |
| 3629 | } else if (!StartValueV) { |
| 3630 | StartValueV = V; |
| 3631 | } else if (StartValueV != V) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3632 | StartValueV = nullptr; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3633 | break; |
| 3634 | } |
| 3635 | } |
| 3636 | if (BEValueV && StartValueV) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3637 | // While we are analyzing this PHI node, handle its value symbolically. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3638 | const SCEV *SymbolicName = getUnknown(PN); |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 3639 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3640 | "PHI node already processed?"); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3641 | ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3642 | |
| 3643 | // Using this symbolic name for the PHI, analyze the value coming around |
| 3644 | // the back-edge. |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3645 | const SCEV *BEValue = getSCEV(BEValueV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3646 | |
| 3647 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 3648 | // has a special value for the first iteration of the loop. |
| 3649 | |
| 3650 | // If the value coming around the backedge is an add with the symbolic |
| 3651 | // value we just inserted, then we found a simple induction variable! |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3652 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3653 | // If there is a single occurrence of the symbolic value, replace it |
| 3654 | // with a recurrence. |
| 3655 | unsigned FoundIndex = Add->getNumOperands(); |
| 3656 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3657 | if (Add->getOperand(i) == SymbolicName) |
| 3658 | if (FoundIndex == e) { |
| 3659 | FoundIndex = i; |
| 3660 | break; |
| 3661 | } |
| 3662 | |
| 3663 | if (FoundIndex != Add->getNumOperands()) { |
| 3664 | // Create an add with everything but the specified operand. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3665 | SmallVector<const SCEV *, 8> Ops; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3666 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3667 | if (i != FoundIndex) |
| 3668 | Ops.push_back(Add->getOperand(i)); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3669 | const SCEV *Accum = getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3670 | |
| 3671 | // This is not a valid addrec if the step amount is varying each |
| 3672 | // loop iteration, but is not itself an addrec in this loop. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 3673 | if (isLoopInvariant(Accum, L) || |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3674 | (isa<SCEVAddRecExpr>(Accum) && |
| 3675 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3676 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3677 | |
| 3678 | // If the increment doesn't overflow, then neither the addrec nor |
| 3679 | // the post-increment will overflow. |
| 3680 | if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) { |
Nick Lewycky | b6ef9a1 | 2015-03-13 01:37:52 +0000 | [diff] [blame] | 3681 | if (OBO->getOperand(0) == PN) { |
| 3682 | if (OBO->hasNoUnsignedWrap()) |
| 3683 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 3684 | if (OBO->hasNoSignedWrap()) |
| 3685 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 3686 | } |
Benjamin Kramer | 6094f30 | 2013-10-28 07:30:06 +0000 | [diff] [blame] | 3687 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3688 | // If the increment is an inbounds GEP, then we know the address |
| 3689 | // space cannot be wrapped around. We cannot make any guarantee |
| 3690 | // about signed or unsigned overflow because pointers are |
| 3691 | // unsigned but we may have a negative index from the base |
Benjamin Kramer | 6094f30 | 2013-10-28 07:30:06 +0000 | [diff] [blame] | 3692 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 3693 | // indices form a positive value. |
Nick Lewycky | b6ef9a1 | 2015-03-13 01:37:52 +0000 | [diff] [blame] | 3694 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 3695 | Flags = setFlags(Flags, SCEV::FlagNW); |
Benjamin Kramer | 6094f30 | 2013-10-28 07:30:06 +0000 | [diff] [blame] | 3696 | |
| 3697 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 3698 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 3699 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 3700 | } |
Sanjoy Das | cb47366 | 2015-01-22 00:48:47 +0000 | [diff] [blame] | 3701 | |
| 3702 | // We cannot transfer nuw and nsw flags from subtraction |
| 3703 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 3704 | // for instance. |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3705 | } |
| 3706 | |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3707 | const SCEV *StartVal = getSCEV(StartValueV); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3708 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 3709 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3710 | // Since the no-wrap flags are on the increment, they apply to the |
| 3711 | // post-incremented value as well. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 3712 | if (isLoopInvariant(Accum, L)) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3713 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3714 | Accum, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3715 | |
| 3716 | // Okay, for the entire analysis of this edge we assumed the PHI |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3717 | // to be symbolic. We now need to go back and purge all of the |
| 3718 | // entries for the scalars that use the symbolic expression. |
| 3719 | ForgetSymbolicName(PN, SymbolicName); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3720 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3721 | return PHISCEV; |
| 3722 | } |
| 3723 | } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3724 | } else if (const SCEVAddRecExpr *AddRec = |
| 3725 | dyn_cast<SCEVAddRecExpr>(BEValue)) { |
Chris Lattner | e8cbdbf | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 3726 | // Otherwise, this could be a loop like this: |
| 3727 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 3728 | // In this case, j = {1,+,1} and BEValue is j. |
| 3729 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 3730 | // i really is an addrec evolution. |
| 3731 | if (AddRec->getLoop() == L && AddRec->isAffine()) { |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3732 | const SCEV *StartVal = getSCEV(StartValueV); |
Chris Lattner | e8cbdbf | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 3733 | |
| 3734 | // If StartVal = j.start - j.stride, we can use StartVal as the |
| 3735 | // initial step of the addrec evolution. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3736 | if (StartVal == getMinusSCEV(AddRec->getOperand(0), |
Dan Gohman | 068b793 | 2010-04-11 23:44:58 +0000 | [diff] [blame] | 3737 | AddRec->getOperand(1))) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3738 | // FIXME: For constant StartVal, we should be able to infer |
| 3739 | // no-wrap flags. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3740 | const SCEV *PHISCEV = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3741 | getAddRecExpr(StartVal, AddRec->getOperand(1), L, |
| 3742 | SCEV::FlagAnyWrap); |
Chris Lattner | e8cbdbf | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 3743 | |
| 3744 | // Okay, for the entire analysis of this edge we assumed the PHI |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3745 | // to be symbolic. We now need to go back and purge all of the |
| 3746 | // entries for the scalars that use the symbolic expression. |
| 3747 | ForgetSymbolicName(PN, SymbolicName); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3748 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
Chris Lattner | e8cbdbf | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 3749 | return PHISCEV; |
| 3750 | } |
| 3751 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3752 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3753 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3754 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 3755 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3756 | // If the PHI has a single incoming value, follow that value, unless the |
| 3757 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 3758 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 3759 | // it doesn't have DominatorTree information, so it may miss cases. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3760 | if (Value *V = SimplifyInstruction(PN, F.getParent()->getDataLayout(), &TLI, |
| 3761 | &DT, &AC)) |
| 3762 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3763 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 3764 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3765 | // If it's not a loop phi, we can't handle it yet. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3766 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3767 | } |
| 3768 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 3769 | /// createNodeForGEP - Expand GEP instructions into add and multiply |
| 3770 | /// operations. This allows them to be analyzed by regular SCEV code. |
| 3771 | /// |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 3772 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 2173bd3 | 2009-05-08 20:36:47 +0000 | [diff] [blame] | 3773 | Value *Base = GEP->getOperand(0); |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 3774 | // Don't attempt to analyze GEPs over unsized objects. |
Matt Arsenault | 404c60a | 2013-10-21 19:43:56 +0000 | [diff] [blame] | 3775 | if (!Base->getType()->getPointerElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 3776 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 3777 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3778 | SmallVector<const SCEV *, 4> IndexExprs; |
| 3779 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 3780 | IndexExprs.push_back(getSCEV(*Index)); |
| 3781 | return getGEPExpr(GEP->getSourceElementType(), getSCEV(Base), IndexExprs, |
| 3782 | GEP->isInBounds()); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 3783 | } |
| 3784 | |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3785 | /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is |
| 3786 | /// guaranteed to end in (at every loop iteration). It is, at the same time, |
| 3787 | /// the minimum number of times S is divisible by 2. For example, given {4,+,8} |
| 3788 | /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3789 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3790 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3791 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Chris Lattner | 69ec1ec | 2007-11-23 22:36:49 +0000 | [diff] [blame] | 3792 | return C->getValue()->getValue().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 3793 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3794 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3795 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 3796 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3797 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3798 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3799 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 3800 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 3801 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3802 | } |
| 3803 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3804 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3805 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 3806 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 3807 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3808 | } |
| 3809 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3810 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3811 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3812 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3813 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3814 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3815 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 3816 | } |
| 3817 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3818 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3819 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3820 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 3821 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3822 | for (unsigned i = 1, e = M->getNumOperands(); |
| 3823 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3824 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3825 | BitWidth); |
| 3826 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 3827 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3828 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3829 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3830 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3831 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3832 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3833 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3834 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 3835 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3836 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3837 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3838 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3839 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3840 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3841 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3842 | return MinOpRes; |
| 3843 | } |
| 3844 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3845 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3846 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3847 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3848 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3849 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3850 | return MinOpRes; |
| 3851 | } |
| 3852 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3853 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 3854 | // For a SCEVUnknown, ask ValueTracking. |
| 3855 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3856 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3857 | computeKnownBits(U->getValue(), Zeros, Ones, F.getParent()->getDataLayout(), |
| 3858 | 0, &AC, nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3859 | return Zeros.countTrailingOnes(); |
| 3860 | } |
| 3861 | |
| 3862 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 3863 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 3864 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3865 | |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 3866 | /// GetRangeFromMetadata - Helper method to assign a range to V from |
| 3867 | /// metadata present in the IR. |
| 3868 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
| 3869 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 3870 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 3871 | ConstantRange TotalRange( |
| 3872 | cast<IntegerType>(I->getType())->getBitWidth(), false); |
| 3873 | |
| 3874 | unsigned NumRanges = MD->getNumOperands() / 2; |
| 3875 | assert(NumRanges >= 1); |
| 3876 | |
| 3877 | for (unsigned i = 0; i < NumRanges; ++i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 3878 | ConstantInt *Lower = |
| 3879 | mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0)); |
| 3880 | ConstantInt *Upper = |
| 3881 | mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1)); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 3882 | ConstantRange Range(Lower->getValue(), Upper->getValue()); |
| 3883 | TotalRange = TotalRange.unionWith(Range); |
| 3884 | } |
| 3885 | |
| 3886 | return TotalRange; |
| 3887 | } |
| 3888 | } |
| 3889 | |
| 3890 | return None; |
| 3891 | } |
| 3892 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3893 | /// getRange - Determine the range for a particular SCEV. If SignHint is |
| 3894 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 3895 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3896 | /// |
| 3897 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3898 | ScalarEvolution::getRange(const SCEV *S, |
| 3899 | ScalarEvolution::RangeSignHint SignHint) { |
| 3900 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 3901 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 3902 | : SignedRanges; |
| 3903 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3904 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3905 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 3906 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3907 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3908 | |
| 3909 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3910 | return setRange(C, SignHint, ConstantRange(C->getValue()->getValue())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 3911 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 3912 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 3913 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 3914 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3915 | // If the value has known zeros, the maximum value will have those known zeros |
| 3916 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 3917 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3918 | if (TZ != 0) { |
| 3919 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 3920 | ConservativeResult = |
| 3921 | ConstantRange(APInt::getMinValue(BitWidth), |
| 3922 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 3923 | else |
| 3924 | ConservativeResult = ConstantRange( |
| 3925 | APInt::getSignedMinValue(BitWidth), |
| 3926 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 3927 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 3928 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3929 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3930 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3931 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3932 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 3933 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3934 | } |
| 3935 | |
| 3936 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3937 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3938 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3939 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 3940 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3941 | } |
| 3942 | |
| 3943 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3944 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3945 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3946 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 3947 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3948 | } |
| 3949 | |
| 3950 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3951 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3952 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3953 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 3954 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3955 | } |
| 3956 | |
| 3957 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3958 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 3959 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 3960 | return setRange(UDiv, SignHint, |
| 3961 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3962 | } |
| 3963 | |
| 3964 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3965 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 3966 | return setRange(ZExt, SignHint, |
| 3967 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3968 | } |
| 3969 | |
| 3970 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3971 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 3972 | return setRange(SExt, SignHint, |
| 3973 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3974 | } |
| 3975 | |
| 3976 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 3977 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 3978 | return setRange(Trunc, SignHint, |
| 3979 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3980 | } |
| 3981 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3982 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3983 | // If there's no unsigned wrap, the value will never be less than its |
| 3984 | // initial value. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3985 | if (AddRec->getNoWrapFlags(SCEV::FlagNUW)) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3986 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 3987 | if (!C->getValue()->isZero()) |
Dan Gohman | ae4a414 | 2010-04-11 22:12:18 +0000 | [diff] [blame] | 3988 | ConservativeResult = |
Dan Gohman | 9396b42 | 2010-06-30 06:58:35 +0000 | [diff] [blame] | 3989 | ConservativeResult.intersectWith( |
| 3990 | ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 3991 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3992 | // If there's no signed wrap, and all the operands have the same sign or |
| 3993 | // zero, the value won't ever change sign. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3994 | if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3995 | bool AllNonNeg = true; |
| 3996 | bool AllNonPos = true; |
| 3997 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 3998 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 3999 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4000 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4001 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4002 | ConservativeResult = ConservativeResult.intersectWith( |
| 4003 | ConstantRange(APInt(BitWidth, 0), |
| 4004 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4005 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4006 | ConservativeResult = ConservativeResult.intersectWith( |
| 4007 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4008 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4009 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4010 | |
| 4011 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4012 | if (AddRec->isAffine()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4013 | Type *Ty = AddRec->getType(); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4014 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4015 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4016 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4017 | |
| 4018 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4019 | // because we could be called from within the ScalarEvolution overflow |
| 4020 | // checking code. |
| 4021 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4022 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4023 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
| 4024 | ConstantRange ZExtMaxBECountRange = |
| 4025 | MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4026 | |
| 4027 | const SCEV *Start = AddRec->getStart(); |
Dan Gohman | f76210e | 2010-04-12 07:39:33 +0000 | [diff] [blame] | 4028 | const SCEV *Step = AddRec->getStepRecurrence(*this); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4029 | ConstantRange StepSRange = getSignedRange(Step); |
| 4030 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4031 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4032 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4033 | ConstantRange EndURange = |
| 4034 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
Dan Gohman | f76210e | 2010-04-12 07:39:33 +0000 | [diff] [blame] | 4035 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4036 | // Check for unsigned overflow. |
| 4037 | ConstantRange ZExtStartURange = |
| 4038 | StartURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4039 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4040 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4041 | ZExtEndURange) { |
| 4042 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4043 | EndURange.getUnsignedMin()); |
| 4044 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4045 | EndURange.getUnsignedMax()); |
| 4046 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4047 | if (!IsFullRange) |
| 4048 | ConservativeResult = |
| 4049 | ConservativeResult.intersectWith(ConstantRange(Min, Max + 1)); |
| 4050 | } |
Dan Gohman | f76210e | 2010-04-12 07:39:33 +0000 | [diff] [blame] | 4051 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4052 | ConstantRange StartSRange = getSignedRange(Start); |
| 4053 | ConstantRange EndSRange = |
| 4054 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4055 | |
| 4056 | // Check for signed overflow. This must be done with ConstantRange |
| 4057 | // arithmetic because we could be called from within the ScalarEvolution |
| 4058 | // overflow checking code. |
| 4059 | ConstantRange SExtStartSRange = |
| 4060 | StartSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4061 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4062 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4063 | SExtEndSRange) { |
| 4064 | APInt Min = APIntOps::smin(StartSRange.getSignedMin(), |
| 4065 | EndSRange.getSignedMin()); |
| 4066 | APInt Max = APIntOps::smax(StartSRange.getSignedMax(), |
| 4067 | EndSRange.getSignedMax()); |
| 4068 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4069 | if (!IsFullRange) |
| 4070 | ConservativeResult = |
| 4071 | ConservativeResult.intersectWith(ConstantRange(Min, Max + 1)); |
| 4072 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4073 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4074 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4075 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4076 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4077 | } |
| 4078 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4079 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4080 | // Check if the IR explicitly contains !range metadata. |
| 4081 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4082 | if (MDRange.hasValue()) |
| 4083 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4084 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4085 | // Split here to avoid paying the compile-time cost of calling both |
| 4086 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4087 | // if needed. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4088 | const DataLayout &DL = F.getParent()->getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4089 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4090 | // For a SCEVUnknown, ask ValueTracking. |
| 4091 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4092 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4093 | if (Ones != ~Zeros + 1) |
| 4094 | ConservativeResult = |
| 4095 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4096 | } else { |
| 4097 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4098 | "generalize as needed!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4099 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4100 | if (NS > 1) |
| 4101 | ConservativeResult = ConservativeResult.intersectWith( |
| 4102 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4103 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4104 | } |
| 4105 | |
| 4106 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4107 | } |
| 4108 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4109 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4110 | } |
| 4111 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4112 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4113 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4114 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4115 | |
| 4116 | // Return early if there are no flags to propagate to the SCEV. |
| 4117 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4118 | if (BinOp->hasNoUnsignedWrap()) |
| 4119 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4120 | if (BinOp->hasNoSignedWrap()) |
| 4121 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 4122 | if (Flags == SCEV::FlagAnyWrap) { |
| 4123 | return SCEV::FlagAnyWrap; |
| 4124 | } |
| 4125 | |
| 4126 | // Here we check that BinOp is in the header of the innermost loop |
| 4127 | // containing BinOp, since we only deal with instructions in the loop |
| 4128 | // header. The actual loop we need to check later will come from an add |
| 4129 | // recurrence, but getting that requires computing the SCEV of the operands, |
| 4130 | // which can be expensive. This check we can do cheaply to rule out some |
| 4131 | // cases early. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4132 | Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent()); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4133 | if (innermostContainingLoop == nullptr || |
| 4134 | innermostContainingLoop->getHeader() != BinOp->getParent()) |
| 4135 | return SCEV::FlagAnyWrap; |
| 4136 | |
| 4137 | // Only proceed if we can prove that BinOp does not yield poison. |
| 4138 | if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap; |
| 4139 | |
| 4140 | // At this point we know that if V is executed, then it does not wrap |
| 4141 | // according to at least one of NSW or NUW. If V is not executed, then we do |
| 4142 | // not know if the calculation that V represents would wrap. Multiple |
| 4143 | // instructions can map to the same SCEV. If we apply NSW or NUW from V to |
| 4144 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4145 | // derived from other instructions that map to the same SCEV. We cannot make |
| 4146 | // that guarantee for cases where V is not executed. So we need to find the |
| 4147 | // loop that V is considered in relation to and prove that V is executed for |
| 4148 | // every iteration of that loop. That implies that the value that V |
| 4149 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4150 | // flags to the SCEV. |
| 4151 | // |
| 4152 | // We check isLoopInvariant to disambiguate in case we are adding two |
| 4153 | // recurrences from different loops, so that we know which loop to prove |
| 4154 | // that V is executed in. |
| 4155 | for (int OpIndex = 0; OpIndex < 2; ++OpIndex) { |
| 4156 | const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex)); |
| 4157 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 4158 | const int OtherOpIndex = 1 - OpIndex; |
| 4159 | const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex)); |
| 4160 | if (isLoopInvariant(OtherOp, AddRec->getLoop()) && |
| 4161 | isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop())) |
| 4162 | return Flags; |
| 4163 | } |
| 4164 | } |
| 4165 | return SCEV::FlagAnyWrap; |
| 4166 | } |
| 4167 | |
| 4168 | /// createSCEV - We know that there is no SCEV for the specified value. Analyze |
| 4169 | /// the expression. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4170 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4171 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4172 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4173 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4174 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4175 | unsigned Opcode = Instruction::UserOp1; |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4176 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4177 | Opcode = I->getOpcode(); |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4178 | |
| 4179 | // Don't attempt to analyze instructions in blocks that aren't |
| 4180 | // reachable. Such instructions don't matter, and they aren't required |
| 4181 | // to obey basic rules for definitions dominating uses which this |
| 4182 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4183 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4184 | return getUnknown(V); |
| 4185 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4186 | Opcode = CE->getOpcode(); |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 4187 | else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
| 4188 | return getConstant(CI); |
| 4189 | else if (isa<ConstantPointerNull>(V)) |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 4190 | return getConstant(V->getType(), 0); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 4191 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
| 4192 | return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4193 | else |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4194 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 4195 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 4196 | Operator *U = cast<Operator>(V); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4197 | switch (Opcode) { |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4198 | case Instruction::Add: { |
| 4199 | // The simple thing to do would be to just call getSCEV on both operands |
| 4200 | // and call getAddExpr with the result. However if we're looking at a |
| 4201 | // bunch of things all added together, this can be quite inefficient, |
| 4202 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 4203 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 4204 | // LLVM IR canonical form means we need only traverse the left operands. |
| 4205 | SmallVector<const SCEV *, 4> AddOps; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4206 | for (Value *Op = U;; Op = U->getOperand(0)) { |
| 4207 | U = dyn_cast<Operator>(Op); |
| 4208 | unsigned Opcode = U ? U->getOpcode() : 0; |
| 4209 | if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) { |
| 4210 | assert(Op != V && "V should be an add"); |
| 4211 | AddOps.push_back(getSCEV(Op)); |
Dan Gohman | 47308d5 | 2010-08-31 22:53:17 +0000 | [diff] [blame] | 4212 | break; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4213 | } |
| 4214 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4215 | if (auto *OpSCEV = getExistingSCEV(U)) { |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4216 | AddOps.push_back(OpSCEV); |
| 4217 | break; |
| 4218 | } |
| 4219 | |
| 4220 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 4221 | // addition, then compute the SCEV for this addition by itself |
| 4222 | // with a separate call to getAddExpr. We need to do that |
| 4223 | // instead of pushing the operands of the addition onto AddOps, |
| 4224 | // since the flags are only known to apply to this particular |
| 4225 | // addition - they may not apply to other additions that can be |
| 4226 | // formed with operands from AddOps. |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4227 | const SCEV *RHS = getSCEV(U->getOperand(1)); |
| 4228 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); |
| 4229 | if (Flags != SCEV::FlagAnyWrap) { |
| 4230 | const SCEV *LHS = getSCEV(U->getOperand(0)); |
| 4231 | if (Opcode == Instruction::Sub) |
| 4232 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 4233 | else |
| 4234 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 4235 | break; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4236 | } |
| 4237 | |
Dan Gohman | 47308d5 | 2010-08-31 22:53:17 +0000 | [diff] [blame] | 4238 | if (Opcode == Instruction::Sub) |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4239 | AddOps.push_back(getNegativeSCEV(RHS)); |
Dan Gohman | 47308d5 | 2010-08-31 22:53:17 +0000 | [diff] [blame] | 4240 | else |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4241 | AddOps.push_back(RHS); |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4242 | } |
Andrew Trick | d25089f | 2011-11-29 02:16:38 +0000 | [diff] [blame] | 4243 | return getAddExpr(AddOps); |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4244 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4245 | |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4246 | case Instruction::Mul: { |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4247 | SmallVector<const SCEV *, 4> MulOps; |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4248 | for (Value *Op = U;; Op = U->getOperand(0)) { |
| 4249 | U = dyn_cast<Operator>(Op); |
| 4250 | if (!U || U->getOpcode() != Instruction::Mul) { |
| 4251 | assert(Op != V && "V should be a mul"); |
| 4252 | MulOps.push_back(getSCEV(Op)); |
| 4253 | break; |
| 4254 | } |
| 4255 | |
| 4256 | if (auto *OpSCEV = getExistingSCEV(U)) { |
| 4257 | MulOps.push_back(OpSCEV); |
| 4258 | break; |
| 4259 | } |
| 4260 | |
| 4261 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); |
| 4262 | if (Flags != SCEV::FlagAnyWrap) { |
| 4263 | MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)), |
| 4264 | getSCEV(U->getOperand(1)), Flags)); |
| 4265 | break; |
| 4266 | } |
| 4267 | |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4268 | MulOps.push_back(getSCEV(U->getOperand(1))); |
| 4269 | } |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4270 | return getMulExpr(MulOps); |
| 4271 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4272 | case Instruction::UDiv: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4273 | return getUDivExpr(getSCEV(U->getOperand(0)), |
| 4274 | getSCEV(U->getOperand(1))); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4275 | case Instruction::Sub: |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4276 | return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)), |
| 4277 | getNoWrapFlagsFromUB(U)); |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4278 | case Instruction::And: |
| 4279 | // For an expression like x&255 that merely masks off the high bits, |
| 4280 | // use zext(trunc(x)) as the SCEV expression. |
| 4281 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | df19948 | 2009-04-25 17:05:40 +0000 | [diff] [blame] | 4282 | if (CI->isNullValue()) |
| 4283 | return getSCEV(U->getOperand(1)); |
Dan Gohman | 05c1d37 | 2009-04-27 01:41:10 +0000 | [diff] [blame] | 4284 | if (CI->isAllOnesValue()) |
| 4285 | return getSCEV(U->getOperand(0)); |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4286 | const APInt &A = CI->getValue(); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4287 | |
| 4288 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 4289 | // constants, obscuring what would otherwise be a low-bits mask. |
Jay Foad | a0653a3 | 2014-05-14 21:14:37 +0000 | [diff] [blame] | 4290 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4291 | // knew about to reconstruct a low-bits mask value. |
| 4292 | unsigned LZ = A.countLeadingZeros(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 4293 | unsigned TZ = A.countTrailingZeros(); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4294 | unsigned BitWidth = A.getBitWidth(); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4295 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4296 | computeKnownBits(U->getOperand(0), KnownZero, KnownOne, |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4297 | F.getParent()->getDataLayout(), 0, &AC, nullptr, &DT); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4298 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 4299 | APInt EffectiveMask = |
| 4300 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 4301 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
| 4302 | const SCEV *MulCount = getConstant( |
| 4303 | ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ))); |
| 4304 | return getMulExpr( |
| 4305 | getZeroExtendExpr( |
| 4306 | getTruncateExpr( |
| 4307 | getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount), |
| 4308 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 4309 | U->getType()), |
| 4310 | MulCount); |
| 4311 | } |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4312 | } |
| 4313 | break; |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4314 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4315 | case Instruction::Or: |
| 4316 | // If the RHS of the Or is a constant, we may have something like: |
| 4317 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 4318 | // optimizations will transparently handle this case. |
| 4319 | // |
| 4320 | // In order for this transformation to be safe, the LHS must be of the |
| 4321 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 4322 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4323 | const SCEV *LHS = getSCEV(U->getOperand(0)); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4324 | const APInt &CIVal = CI->getValue(); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4325 | if (GetMinTrailingZeros(LHS) >= |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4326 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 4327 | // Build a plain add SCEV. |
| 4328 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 4329 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 4330 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 4331 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 4332 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 4333 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 4334 | OldAR->getNoWrapFlags()); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4335 | } |
| 4336 | return S; |
| 4337 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4338 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4339 | break; |
| 4340 | case Instruction::Xor: |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4341 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4342 | // If the RHS of the xor is a signbit, then this is just an add. |
| 4343 | // Instcombine turns add of signbit into xor as a strength reduction step. |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4344 | if (CI->getValue().isSignBit()) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4345 | return getAddExpr(getSCEV(U->getOperand(0)), |
| 4346 | getSCEV(U->getOperand(1))); |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4347 | |
| 4348 | // If the RHS of xor is -1, then this is a not operation. |
Dan Gohman | d277a1e | 2009-05-18 16:17:44 +0000 | [diff] [blame] | 4349 | if (CI->isAllOnesValue()) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4350 | return getNotSCEV(getSCEV(U->getOperand(0))); |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 4351 | |
| 4352 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 4353 | // This is a variant of the check for xor with -1, and it handles |
| 4354 | // the case where instcombine has trimmed non-demanded bits out |
| 4355 | // of an xor with -1. |
| 4356 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) |
| 4357 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1))) |
| 4358 | if (BO->getOpcode() == Instruction::And && |
| 4359 | LCI->getValue() == CI->getValue()) |
| 4360 | if (const SCEVZeroExtendExpr *Z = |
Dan Gohman | b50f5a4 | 2009-06-17 01:22:39 +0000 | [diff] [blame] | 4361 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4362 | Type *UTy = U->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4363 | const SCEV *Z0 = Z->getOperand(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4364 | Type *Z0Ty = Z0->getType(); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4365 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
| 4366 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 4367 | // If C is a low-bits mask, the zero extend is serving to |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4368 | // mask off the high bits. Complement the operand and |
| 4369 | // re-apply the zext. |
| 4370 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 4371 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 4372 | |
| 4373 | // If C is a single bit, it may be in the sign-bit position |
| 4374 | // before the zero-extend. In this case, represent the xor |
| 4375 | // using an add, which is equivalent, and re-apply the zext. |
Jay Foad | 583abbc | 2010-12-07 08:25:19 +0000 | [diff] [blame] | 4376 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 4377 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4378 | Trunc.isSignBit()) |
| 4379 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 4380 | UTy); |
Dan Gohman | b50f5a4 | 2009-06-17 01:22:39 +0000 | [diff] [blame] | 4381 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4382 | } |
| 4383 | break; |
| 4384 | |
| 4385 | case Instruction::Shl: |
| 4386 | // Turn shift left of a constant amount into a multiply. |
| 4387 | if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 4388 | uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4389 | |
| 4390 | // If the shift count is not less than the bitwidth, the result of |
| 4391 | // the shift is undefined. Don't try to analyze it, because the |
| 4392 | // resolution chosen here may differ from the resolution chosen in |
| 4393 | // other parts of the compiler. |
| 4394 | if (SA->getValue().uge(BitWidth)) |
| 4395 | break; |
| 4396 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4397 | // It is currently not resolved how to interpret NSW for left |
| 4398 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 4399 | // case. Remove this check (or this comment) once the situation |
| 4400 | // is resolved. See |
| 4401 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 4402 | // and http://reviews.llvm.org/D8890 . |
| 4403 | auto Flags = SCEV::FlagAnyWrap; |
| 4404 | if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U); |
| 4405 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4406 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 4407 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4408 | return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4409 | } |
| 4410 | break; |
| 4411 | |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4412 | case Instruction::LShr: |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 4413 | // Turn logical shift right of a constant into a unsigned divide. |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4414 | if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 4415 | uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4416 | |
| 4417 | // If the shift count is not less than the bitwidth, the result of |
| 4418 | // the shift is undefined. Don't try to analyze it, because the |
| 4419 | // resolution chosen here may differ from the resolution chosen in |
| 4420 | // other parts of the compiler. |
| 4421 | if (SA->getValue().uge(BitWidth)) |
| 4422 | break; |
| 4423 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4424 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 4425 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4426 | return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4427 | } |
| 4428 | break; |
| 4429 | |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4430 | case Instruction::AShr: |
| 4431 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 4432 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4433 | if (Operator *L = dyn_cast<Operator>(U->getOperand(0))) |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4434 | if (L->getOpcode() == Instruction::Shl && |
| 4435 | L->getOperand(1) == U->getOperand(1)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4436 | uint64_t BitWidth = getTypeSizeInBits(U->getType()); |
| 4437 | |
| 4438 | // If the shift count is not less than the bitwidth, the result of |
| 4439 | // the shift is undefined. Don't try to analyze it, because the |
| 4440 | // resolution chosen here may differ from the resolution chosen in |
| 4441 | // other parts of the compiler. |
| 4442 | if (CI->getValue().uge(BitWidth)) |
| 4443 | break; |
| 4444 | |
Dan Gohman | df19948 | 2009-04-25 17:05:40 +0000 | [diff] [blame] | 4445 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 4446 | if (Amt == BitWidth) |
| 4447 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4448 | return |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4449 | getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4450 | IntegerType::get(getContext(), |
| 4451 | Amt)), |
| 4452 | U->getType()); |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4453 | } |
| 4454 | break; |
| 4455 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4456 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4457 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4458 | |
| 4459 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4460 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4461 | |
| 4462 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4463 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4464 | |
| 4465 | case Instruction::BitCast: |
| 4466 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4467 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4468 | return getSCEV(U->getOperand(0)); |
| 4469 | break; |
| 4470 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 4471 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 4472 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 4473 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 4474 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4475 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4476 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4477 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4478 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4479 | case Instruction::PHI: |
| 4480 | return createNodeForPHI(cast<PHINode>(U)); |
| 4481 | |
| 4482 | case Instruction::Select: |
| 4483 | // This could be a smax or umax that was lowered earlier. |
| 4484 | // Try to recover it. |
| 4485 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { |
| 4486 | Value *LHS = ICI->getOperand(0); |
| 4487 | Value *RHS = ICI->getOperand(1); |
| 4488 | switch (ICI->getPredicate()) { |
| 4489 | case ICmpInst::ICMP_SLT: |
| 4490 | case ICmpInst::ICMP_SLE: |
| 4491 | std::swap(LHS, RHS); |
| 4492 | // fall through |
| 4493 | case ICmpInst::ICMP_SGT: |
| 4494 | case ICmpInst::ICMP_SGE: |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4495 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4496 | // a >s b ? b+x : a+x -> smin(a, b)+x |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 4497 | if (getTypeSizeInBits(LHS->getType()) <= |
| 4498 | getTypeSizeInBits(U->getType())) { |
| 4499 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), U->getType()); |
| 4500 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), U->getType()); |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4501 | const SCEV *LA = getSCEV(U->getOperand(1)); |
| 4502 | const SCEV *RA = getSCEV(U->getOperand(2)); |
| 4503 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4504 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4505 | if (LDiff == RDiff) |
| 4506 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4507 | LDiff = getMinusSCEV(LA, RS); |
| 4508 | RDiff = getMinusSCEV(RA, LS); |
| 4509 | if (LDiff == RDiff) |
| 4510 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4511 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4512 | break; |
| 4513 | case ICmpInst::ICMP_ULT: |
| 4514 | case ICmpInst::ICMP_ULE: |
| 4515 | std::swap(LHS, RHS); |
| 4516 | // fall through |
| 4517 | case ICmpInst::ICMP_UGT: |
| 4518 | case ICmpInst::ICMP_UGE: |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4519 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4520 | // a >u b ? b+x : a+x -> umin(a, b)+x |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 4521 | if (getTypeSizeInBits(LHS->getType()) <= |
| 4522 | getTypeSizeInBits(U->getType())) { |
| 4523 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType()); |
| 4524 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), U->getType()); |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4525 | const SCEV *LA = getSCEV(U->getOperand(1)); |
| 4526 | const SCEV *RA = getSCEV(U->getOperand(2)); |
| 4527 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4528 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4529 | if (LDiff == RDiff) |
| 4530 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4531 | LDiff = getMinusSCEV(LA, RS); |
| 4532 | RDiff = getMinusSCEV(RA, LS); |
| 4533 | if (LDiff == RDiff) |
| 4534 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4535 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4536 | break; |
Dan Gohman | 4d3c3cf | 2009-06-18 20:21:07 +0000 | [diff] [blame] | 4537 | case ICmpInst::ICMP_NE: |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4538 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 4539 | if (getTypeSizeInBits(LHS->getType()) <= |
| 4540 | getTypeSizeInBits(U->getType()) && |
| 4541 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4542 | const SCEV *One = getConstant(U->getType(), 1); |
| 4543 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType()); |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4544 | const SCEV *LA = getSCEV(U->getOperand(1)); |
| 4545 | const SCEV *RA = getSCEV(U->getOperand(2)); |
| 4546 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4547 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4548 | if (LDiff == RDiff) |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 4549 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4550 | } |
Dan Gohman | 4d3c3cf | 2009-06-18 20:21:07 +0000 | [diff] [blame] | 4551 | break; |
| 4552 | case ICmpInst::ICMP_EQ: |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4553 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 4554 | if (getTypeSizeInBits(LHS->getType()) <= |
| 4555 | getTypeSizeInBits(U->getType()) && |
| 4556 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4557 | const SCEV *One = getConstant(U->getType(), 1); |
| 4558 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType()); |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4559 | const SCEV *LA = getSCEV(U->getOperand(1)); |
| 4560 | const SCEV *RA = getSCEV(U->getOperand(2)); |
| 4561 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4562 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4563 | if (LDiff == RDiff) |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 4564 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
Dan Gohman | f33bac3 | 2010-04-24 03:09:42 +0000 | [diff] [blame] | 4565 | } |
Dan Gohman | 4d3c3cf | 2009-06-18 20:21:07 +0000 | [diff] [blame] | 4566 | break; |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4567 | default: |
| 4568 | break; |
| 4569 | } |
| 4570 | } |
| 4571 | |
| 4572 | default: // We cannot analyze this expression. |
| 4573 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4574 | } |
| 4575 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4576 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4577 | } |
| 4578 | |
| 4579 | |
| 4580 | |
| 4581 | //===----------------------------------------------------------------------===// |
| 4582 | // Iteration Count Computation Code |
| 4583 | // |
| 4584 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4585 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 4586 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 4587 | return getSmallConstantTripCount(L, ExitingBB); |
| 4588 | |
| 4589 | // No trip count information for multiple exits. |
| 4590 | return 0; |
| 4591 | } |
| 4592 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4593 | /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 4594 | /// normal unsigned value. Returns 0 if the trip count is unknown or not |
| 4595 | /// constant. Will also return 0 if the maximum trip count is very large (>= |
| 4596 | /// 2^32). |
| 4597 | /// |
| 4598 | /// This "trip count" assumes that control exits via ExitingBlock. More |
| 4599 | /// precisely, it is the number of times that control may reach ExitingBlock |
| 4600 | /// before taking the branch. For loops with multiple exits, it may not be the |
| 4601 | /// number times that the loop header executes because the loop may exit |
| 4602 | /// prematurely via another branch. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4603 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 4604 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4605 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 4606 | assert(L->isLoopExiting(ExitingBlock) && |
| 4607 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4608 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4609 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4610 | if (!ExitCount) |
| 4611 | return 0; |
| 4612 | |
| 4613 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 4614 | |
| 4615 | // Guard against huge trip counts. |
| 4616 | if (ExitConst->getValue().getActiveBits() > 32) |
| 4617 | return 0; |
| 4618 | |
| 4619 | // In case of integer overflow, this returns 0, which is correct. |
| 4620 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 4621 | } |
| 4622 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4623 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 4624 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 4625 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 4626 | |
| 4627 | // No trip multiple information for multiple exits. |
| 4628 | return 0; |
| 4629 | } |
| 4630 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4631 | /// getSmallConstantTripMultiple - Returns the largest constant divisor of the |
| 4632 | /// trip count of this loop as a normal unsigned value, if possible. This |
| 4633 | /// means that the actual trip count is always a multiple of the returned |
| 4634 | /// value (don't forget the trip count could very well be zero as well!). |
| 4635 | /// |
| 4636 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 4637 | /// multiple of a constant (which is also the case if the trip count is simply |
| 4638 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 4639 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 4640 | /// |
| 4641 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 4642 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4643 | unsigned |
| 4644 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 4645 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4646 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 4647 | assert(L->isLoopExiting(ExitingBlock) && |
| 4648 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4649 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4650 | if (ExitCount == getCouldNotCompute()) |
| 4651 | return 1; |
| 4652 | |
| 4653 | // Get the trip count from the BE count by adding 1. |
| 4654 | const SCEV *TCMul = getAddExpr(ExitCount, |
| 4655 | getConstant(ExitCount->getType(), 1)); |
| 4656 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 4657 | // to factor simple cases. |
| 4658 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 4659 | TCMul = Mul->getOperand(0); |
| 4660 | |
| 4661 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 4662 | if (!MulC) |
| 4663 | return 1; |
| 4664 | |
| 4665 | ConstantInt *Result = MulC->getValue(); |
| 4666 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 4667 | // Guard against huge trip counts (this requires checking |
| 4668 | // for zero to handle the case where the trip count == -1 and the |
| 4669 | // addition wraps). |
| 4670 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 4671 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4672 | return 1; |
| 4673 | |
| 4674 | return (unsigned)Result->getZExtValue(); |
| 4675 | } |
| 4676 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4677 | // getExitCount - Get the expression for the number of loop iterations for which |
Andrew Trick | ee9143a | 2013-05-31 23:34:46 +0000 | [diff] [blame] | 4678 | // this loop is guaranteed not to exit via ExitingBlock. Otherwise return |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4679 | // SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4680 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 4681 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4682 | } |
| 4683 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 4684 | /// getBackedgeTakenCount - If the specified loop has a predictable |
| 4685 | /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute |
| 4686 | /// object. The backedge-taken count is the number of times the loop header |
| 4687 | /// will be branched to from within the loop. This is one less than the |
| 4688 | /// trip count of the loop, since it doesn't count the first iteration, |
| 4689 | /// when the header is branched to from outside the loop. |
| 4690 | /// |
| 4691 | /// Note that it is not valid to call this method on a loop without a |
| 4692 | /// loop-invariant backedge-taken count (see |
| 4693 | /// hasLoopInvariantBackedgeTakenCount). |
| 4694 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4695 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4696 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 4697 | } |
| 4698 | |
| 4699 | /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except |
| 4700 | /// return the least SCEV value that is known never to be less than the |
| 4701 | /// actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4702 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4703 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 4704 | } |
| 4705 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4706 | /// PushLoopPHIs - Push PHI nodes in the header of the given loop |
| 4707 | /// onto the given Worklist. |
| 4708 | static void |
| 4709 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 4710 | BasicBlock *Header = L->getHeader(); |
| 4711 | |
| 4712 | // Push all Loop-header PHIs onto the Worklist stack. |
| 4713 | for (BasicBlock::iterator I = Header->begin(); |
| 4714 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 4715 | Worklist.push_back(PN); |
| 4716 | } |
| 4717 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 4718 | const ScalarEvolution::BackedgeTakenInfo & |
| 4719 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4720 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 4721 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 4722 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 4723 | // code elsewhere that it shouldn't attempt to request a new |
| 4724 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 4725 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4726 | BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo())); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4727 | if (!Pair.second) |
| 4728 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 4729 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4730 | // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it |
| 4731 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 4732 | // must be cleared in this scope. |
| 4733 | BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L); |
| 4734 | |
| 4735 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 4736 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 4737 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4738 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 4739 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4740 | } |
| 4741 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 4742 | isa<PHINode>(L->getHeader()->begin())) { |
| 4743 | // Only count loops that have phi nodes as not being computable. |
| 4744 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4745 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 4746 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4747 | // Now that we know more about the trip count for this loop, forget any |
| 4748 | // existing SCEV values for PHI nodes in this loop since they are only |
| 4749 | // conservative estimates made without the benefit of trip count |
| 4750 | // information. This is similar to the code in forgetLoop, except that |
| 4751 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4752 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4753 | SmallVector<Instruction *, 16> Worklist; |
| 4754 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4755 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4756 | SmallPtrSet<Instruction *, 8> Visited; |
| 4757 | while (!Worklist.empty()) { |
| 4758 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4759 | if (!Visited.insert(I).second) |
| 4760 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4761 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4762 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 4763 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4764 | if (It != ValueExprMap.end()) { |
| 4765 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4766 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4767 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 4768 | // structure, or it's a PHI that's in the progress of being computed |
| 4769 | // by createNodeForPHI. In the former case, additional loop trip |
| 4770 | // count information isn't going to change anything. In the later |
| 4771 | // case, createNodeForPHI will perform the necessary updates on its |
| 4772 | // own when it gets to that point. |
| 4773 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
| 4774 | forgetMemoizedResults(Old); |
| 4775 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4776 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4777 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 4778 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4779 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 4780 | |
| 4781 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4782 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4783 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 4784 | |
| 4785 | // Re-lookup the insert position, since the call to |
| 4786 | // ComputeBackedgeTakenCount above could result in a |
| 4787 | // recusive call to getBackedgeTakenInfo (on a different |
| 4788 | // loop), which would invalidate the iterator computed |
| 4789 | // earlier. |
| 4790 | return BackedgeTakenCounts.find(L)->second = Result; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4791 | } |
| 4792 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 4793 | /// forgetLoop - This method should be called by the client when it has |
| 4794 | /// changed a loop in a way that may effect ScalarEvolution's ability to |
| 4795 | /// compute a trip count, or if the loop is deleted. |
| 4796 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 4797 | // Drop any stored trip count value. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4798 | DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos = |
| 4799 | BackedgeTakenCounts.find(L); |
| 4800 | if (BTCPos != BackedgeTakenCounts.end()) { |
| 4801 | BTCPos->second.clear(); |
| 4802 | BackedgeTakenCounts.erase(BTCPos); |
| 4803 | } |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 4804 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 4805 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 4806 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4807 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 4808 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4809 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 4810 | while (!Worklist.empty()) { |
| 4811 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4812 | if (!Visited.insert(I).second) |
| 4813 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4814 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 4815 | ValueExprMapType::iterator It = |
| 4816 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 4817 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 4818 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 4819 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 4820 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 4821 | ConstantEvolutionLoopExitValue.erase(PN); |
| 4822 | } |
| 4823 | |
| 4824 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 4825 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 4826 | |
| 4827 | // Forget all contained loops too, to avoid dangling entries in the |
| 4828 | // ValuesAtScopes map. |
| 4829 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 4830 | forgetLoop(*I); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 4831 | } |
| 4832 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 4833 | /// forgetValue - This method should be called by the client when it has |
| 4834 | /// changed a value in a way that may effect its value, or which may |
| 4835 | /// disconnect it from a def-use chain linking it to a loop. |
| 4836 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 4837 | Instruction *I = dyn_cast<Instruction>(V); |
| 4838 | if (!I) return; |
| 4839 | |
| 4840 | // Drop information about expressions based on loop-header PHIs. |
| 4841 | SmallVector<Instruction *, 16> Worklist; |
| 4842 | Worklist.push_back(I); |
| 4843 | |
| 4844 | SmallPtrSet<Instruction *, 8> Visited; |
| 4845 | while (!Worklist.empty()) { |
| 4846 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4847 | if (!Visited.insert(I).second) |
| 4848 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 4849 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 4850 | ValueExprMapType::iterator It = |
| 4851 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 4852 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 4853 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 4854 | ValueExprMap.erase(It); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 4855 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 4856 | ConstantEvolutionLoopExitValue.erase(PN); |
| 4857 | } |
| 4858 | |
| 4859 | PushDefUseChildren(I, Worklist); |
| 4860 | } |
| 4861 | } |
| 4862 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4863 | /// getExact - Get the exact loop backedge taken count considering all loop |
Sanjoy Das | 135e5b9 | 2015-07-21 20:59:22 +0000 | [diff] [blame] | 4864 | /// exits. A computable result can only be returned for loops with a single |
| 4865 | /// exit. Returning the minimum taken count among all exits is incorrect |
| 4866 | /// because one of the loop's exit limit's may have been skipped. HowFarToZero |
| 4867 | /// assumes that the limit of each loop test is never skipped. This is a valid |
| 4868 | /// assumption as long as the loop exits via that test. For precise results, it |
| 4869 | /// is the caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 4870 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4871 | const SCEV * |
| 4872 | ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const { |
| 4873 | // If any exits were not computable, the loop is not computable. |
| 4874 | if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); |
| 4875 | |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 4876 | // We need exactly one computable exit. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4877 | if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4878 | assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); |
| 4879 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 4880 | const SCEV *BECount = nullptr; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4881 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 4882 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4883 | |
| 4884 | assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
| 4885 | |
| 4886 | if (!BECount) |
| 4887 | BECount = ENT->ExactNotTaken; |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 4888 | else if (BECount != ENT->ExactNotTaken) |
| 4889 | return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4890 | } |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 4891 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4892 | return BECount; |
| 4893 | } |
| 4894 | |
| 4895 | /// getExact - Get the exact not taken count for this loop exit. |
| 4896 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4897 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4898 | ScalarEvolution *SE) const { |
| 4899 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 4900 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4901 | |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4902 | if (ENT->ExitingBlock == ExitingBlock) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4903 | return ENT->ExactNotTaken; |
| 4904 | } |
| 4905 | return SE->getCouldNotCompute(); |
| 4906 | } |
| 4907 | |
| 4908 | /// getMax - Get the max backedge taken count for the loop. |
| 4909 | const SCEV * |
| 4910 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
| 4911 | return Max ? Max : SE->getCouldNotCompute(); |
| 4912 | } |
| 4913 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 4914 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 4915 | ScalarEvolution *SE) const { |
| 4916 | if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) |
| 4917 | return true; |
| 4918 | |
| 4919 | if (!ExitNotTaken.ExitingBlock) |
| 4920 | return false; |
| 4921 | |
| 4922 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 4923 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 4924 | |
| 4925 | if (ENT->ExactNotTaken != SE->getCouldNotCompute() |
| 4926 | && SE->hasOperand(ENT->ExactNotTaken, S)) { |
| 4927 | return true; |
| 4928 | } |
| 4929 | } |
| 4930 | return false; |
| 4931 | } |
| 4932 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4933 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 4934 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 4935 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
| 4936 | SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, |
| 4937 | bool Complete, const SCEV *MaxCount) : Max(MaxCount) { |
| 4938 | |
| 4939 | if (!Complete) |
| 4940 | ExitNotTaken.setIncomplete(); |
| 4941 | |
| 4942 | unsigned NumExits = ExitCounts.size(); |
| 4943 | if (NumExits == 0) return; |
| 4944 | |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4945 | ExitNotTaken.ExitingBlock = ExitCounts[0].first; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4946 | ExitNotTaken.ExactNotTaken = ExitCounts[0].second; |
| 4947 | if (NumExits == 1) return; |
| 4948 | |
| 4949 | // Handle the rare case of multiple computable exits. |
| 4950 | ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1]; |
| 4951 | |
| 4952 | ExitNotTakenInfo *PrevENT = &ExitNotTaken; |
| 4953 | for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) { |
| 4954 | PrevENT->setNextExit(ENT); |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4955 | ENT->ExitingBlock = ExitCounts[i].first; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4956 | ENT->ExactNotTaken = ExitCounts[i].second; |
| 4957 | } |
| 4958 | } |
| 4959 | |
| 4960 | /// clear - Invalidate this result and free the ExitNotTakenInfo array. |
| 4961 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 4962 | ExitNotTaken.ExitingBlock = nullptr; |
| 4963 | ExitNotTaken.ExactNotTaken = nullptr; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4964 | delete[] ExitNotTaken.getNextExit(); |
| 4965 | } |
| 4966 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 4967 | /// ComputeBackedgeTakenCount - Compute the number of times the backedge |
| 4968 | /// of the specified loop will execute. |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 4969 | ScalarEvolution::BackedgeTakenInfo |
| 4970 | ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 4971 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 4972 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4973 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 4974 | SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4975 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 4976 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 4977 | const SCEV *MustExitMaxBECount = nullptr; |
| 4978 | const SCEV *MayExitMaxBECount = nullptr; |
| 4979 | |
| 4980 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 4981 | // and compute maxBECount. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 4982 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 4983 | BasicBlock *ExitBB = ExitingBlocks[i]; |
| 4984 | ExitLimit EL = ComputeExitLimit(L, ExitBB); |
| 4985 | |
| 4986 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 4987 | // CouldComputeBECount is true only if all exits can be computed. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4988 | if (EL.Exact == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 4989 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 4990 | // we won't be able to compute an exact value for the loop. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4991 | CouldComputeBECount = false; |
| 4992 | else |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 4993 | ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact)); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4994 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 4995 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 4996 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 4997 | // LoopMustExits and LoopMayExits. |
| 4998 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4999 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5000 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
| 5001 | // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, |
| 5002 | // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is |
| 5003 | // considered greater than any computable EL.Max. |
| 5004 | if (EL.Max != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5005 | DT.dominates(ExitBB, Latch)) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5006 | if (!MustExitMaxBECount) |
| 5007 | MustExitMaxBECount = EL.Max; |
| 5008 | else { |
| 5009 | MustExitMaxBECount = |
| 5010 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5011 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5012 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
| 5013 | if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) |
| 5014 | MayExitMaxBECount = EL.Max; |
| 5015 | else { |
| 5016 | MayExitMaxBECount = |
| 5017 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); |
| 5018 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5019 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5020 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5021 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5022 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5023 | return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5024 | } |
| 5025 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5026 | /// ComputeExitLimit - Compute the number of times the backedge of the specified |
| 5027 | /// loop will execute if it exits via the specified block. |
| 5028 | ScalarEvolution::ExitLimit |
| 5029 | ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5030 | |
| 5031 | // Okay, we've chosen an exiting block. See what condition causes us to |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5032 | // exit at this block and remember the exit block and whether all other targets |
| 5033 | // lead to the loop header. |
| 5034 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5035 | BasicBlock *Exit = nullptr; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 5036 | for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock); |
| 5037 | SI != SE; ++SI) |
| 5038 | if (!L->contains(*SI)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5039 | if (Exit) // Multiple exit successors. |
| 5040 | return getCouldNotCompute(); |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 5041 | Exit = *SI; |
| 5042 | } else if (*SI != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5043 | MustExecuteLoopHeader = false; |
| 5044 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5045 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5046 | // At this point, we know we have a conditional branch that determines whether |
| 5047 | // the loop is exited. However, we don't know if the branch is executed each |
| 5048 | // time through the loop. If not, then the execution count of the branch will |
| 5049 | // not be equal to the trip count of the loop. |
| 5050 | // |
| 5051 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5052 | // the loop header. If so, we know it will always execute the same number of |
Chris Lattner | 5a55476 | 2007-01-14 01:24:47 +0000 | [diff] [blame] | 5053 | // times as the loop. We also handle the case where the exit block *is* the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5054 | // loop header. This is common for un-rotated loops. |
| 5055 | // |
| 5056 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5057 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5058 | // header is reached, the execution count of the branch will be equal to the |
| 5059 | // trip count of the loop. |
| 5060 | // |
| 5061 | // More extensive analysis could be done to handle more cases here. |
| 5062 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5063 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5064 | // The simple checks failed, try climbing the unique predecessor chain |
| 5065 | // up to the header. |
| 5066 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5067 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5068 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5069 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5070 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5071 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5072 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5073 | if (PredSucc == BB) |
| 5074 | continue; |
| 5075 | // If the predecessor has a successor that isn't BB and isn't |
| 5076 | // outside the loop, assume the worst. |
| 5077 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5078 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5079 | } |
| 5080 | if (Pred == L->getHeader()) { |
| 5081 | Ok = true; |
| 5082 | break; |
| 5083 | } |
| 5084 | BB = Pred; |
| 5085 | } |
| 5086 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5087 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5088 | } |
| 5089 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5090 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5091 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5092 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5093 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5094 | // Proceed to the next level to examine the exit condition expression. |
| 5095 | return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0), |
| 5096 | BI->getSuccessor(1), |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5097 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5098 | } |
| 5099 | |
| 5100 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
| 5101 | return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5102 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5103 | |
| 5104 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5105 | } |
| 5106 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5107 | /// ComputeExitLimitFromCond - Compute the number of times the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5108 | /// backedge of the specified loop will execute if its exit condition |
| 5109 | /// were a conditional branch of ExitCond, TBB, and FBB. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5110 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5111 | /// @param ControlsExit is true if ExitCond directly controls the exit |
| 5112 | /// branch. In this case, we can assume that the loop exits only if the |
| 5113 | /// condition is true and can infer that failing to meet the condition prior to |
| 5114 | /// integer wraparound results in undefined behavior. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5115 | ScalarEvolution::ExitLimit |
| 5116 | ScalarEvolution::ComputeExitLimitFromCond(const Loop *L, |
| 5117 | Value *ExitCond, |
| 5118 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5119 | BasicBlock *FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5120 | bool ControlsExit) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5121 | // Check if the controlling expression for this loop is an And or Or. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5122 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5123 | if (BO->getOpcode() == Instruction::And) { |
| 5124 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5125 | bool EitherMayExit = L->contains(TBB); |
| 5126 | ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5127 | ControlsExit && !EitherMayExit); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5128 | ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5129 | ControlsExit && !EitherMayExit); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5130 | const SCEV *BECount = getCouldNotCompute(); |
| 5131 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5132 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5133 | // Both conditions must be true for the loop to continue executing. |
| 5134 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5135 | if (EL0.Exact == getCouldNotCompute() || |
| 5136 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5137 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5138 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5139 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5140 | if (EL0.Max == getCouldNotCompute()) |
| 5141 | MaxBECount = EL1.Max; |
| 5142 | else if (EL1.Max == getCouldNotCompute()) |
| 5143 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5144 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5145 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5146 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5147 | // Both conditions must be true at the same time for the loop to exit. |
| 5148 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5149 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5150 | if (EL0.Max == EL1.Max) |
| 5151 | MaxBECount = EL0.Max; |
| 5152 | if (EL0.Exact == EL1.Exact) |
| 5153 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5154 | } |
| 5155 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5156 | return ExitLimit(BECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5157 | } |
| 5158 | if (BO->getOpcode() == Instruction::Or) { |
| 5159 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5160 | bool EitherMayExit = L->contains(FBB); |
| 5161 | ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5162 | ControlsExit && !EitherMayExit); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5163 | ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5164 | ControlsExit && !EitherMayExit); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5165 | const SCEV *BECount = getCouldNotCompute(); |
| 5166 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5167 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5168 | // Both conditions must be false for the loop to continue executing. |
| 5169 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5170 | if (EL0.Exact == getCouldNotCompute() || |
| 5171 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5172 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5173 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5174 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5175 | if (EL0.Max == getCouldNotCompute()) |
| 5176 | MaxBECount = EL1.Max; |
| 5177 | else if (EL1.Max == getCouldNotCompute()) |
| 5178 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5179 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5180 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5181 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5182 | // Both conditions must be false at the same time for the loop to exit. |
| 5183 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5184 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5185 | if (EL0.Max == EL1.Max) |
| 5186 | MaxBECount = EL0.Max; |
| 5187 | if (EL0.Exact == EL1.Exact) |
| 5188 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5189 | } |
| 5190 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5191 | return ExitLimit(BECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5192 | } |
| 5193 | } |
| 5194 | |
| 5195 | // With an icmp, it may be feasible to compute an exact backedge-taken count. |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5196 | // Proceed to the next level to examine the icmp. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5197 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5198 | return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5199 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5200 | // Check for a constant condition. These are normally stripped out by |
| 5201 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 5202 | // preserve the CFG and is temporarily leaving constant conditions |
| 5203 | // in place. |
| 5204 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 5205 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 5206 | // The backedge is always taken. |
| 5207 | return getCouldNotCompute(); |
| 5208 | else |
| 5209 | // The backedge is never taken. |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 5210 | return getConstant(CI->getType(), 0); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5211 | } |
| 5212 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5213 | // If it's not an integer or pointer comparison then compute it the hard way. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5214 | return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5215 | } |
| 5216 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5217 | /// ComputeExitLimitFromICmp - Compute the number of times the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5218 | /// backedge of the specified loop will execute if its exit condition |
| 5219 | /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5220 | ScalarEvolution::ExitLimit |
| 5221 | ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L, |
| 5222 | ICmpInst *ExitCond, |
| 5223 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5224 | BasicBlock *FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5225 | bool ControlsExit) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5226 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5227 | // If the condition was exit on true, convert the condition to exit on false |
| 5228 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5229 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5230 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5231 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5232 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5233 | |
| 5234 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 5235 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 5236 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5237 | ExitLimit ItCnt = |
| 5238 | ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 5239 | if (ItCnt.hasAnyInfo()) |
| 5240 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5241 | } |
| 5242 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5243 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 5244 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5245 | |
| 5246 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5247 | LHS = getSCEVAtScope(LHS, L); |
| 5248 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5249 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5250 | // At this point, we would like to compute how many iterations of the |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5251 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5252 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 5253 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5254 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5255 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5256 | } |
| 5257 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 5258 | // Simplify the operands before analyzing them. |
| 5259 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 5260 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5261 | // If we have a comparison of a chrec against a constant, try to use value |
| 5262 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5263 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 5264 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5265 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5266 | // Form the constant range. |
| 5267 | ConstantRange CompRange( |
| 5268 | ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue())); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5269 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5270 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5271 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5272 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5273 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5274 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5275 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5276 | // Convert to: while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5277 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5278 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5279 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5280 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 5281 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 5282 | // Convert to: while (X-Y == 0) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5283 | ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); |
| 5284 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5285 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5286 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5287 | case ICmpInst::ICMP_SLT: |
| 5288 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 5289 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5290 | ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5291 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5292 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5293 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5294 | case ICmpInst::ICMP_SGT: |
| 5295 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 5296 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5297 | ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5298 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5299 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5300 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5301 | default: |
Chris Lattner | 0916921 | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 5302 | #if 0 |
David Greene | df1c497 | 2009-12-23 22:18:14 +0000 | [diff] [blame] | 5303 | dbgs() << "ComputeBackedgeTakenCount "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5304 | if (ExitCond->getOperand(0)->getType()->isUnsigned()) |
David Greene | df1c497 | 2009-12-23 22:18:14 +0000 | [diff] [blame] | 5305 | dbgs() << "[unsigned] "; |
| 5306 | dbgs() << *LHS << " " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5307 | << Instruction::getOpcodeName(Instruction::ICmp) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5308 | << " " << *RHS << "\n"; |
Chris Lattner | 0916921 | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 5309 | #endif |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 5310 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5311 | } |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5312 | return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5313 | } |
| 5314 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5315 | ScalarEvolution::ExitLimit |
| 5316 | ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L, |
| 5317 | SwitchInst *Switch, |
| 5318 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5319 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5320 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 5321 | |
| 5322 | // Give up if the exit is the default dest of a switch. |
| 5323 | if (Switch->getDefaultDest() == ExitingBlock) |
| 5324 | return getCouldNotCompute(); |
| 5325 | |
| 5326 | assert(L->contains(Switch->getDefaultDest()) && |
| 5327 | "Default case must not exit the loop!"); |
| 5328 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 5329 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 5330 | |
| 5331 | // while (X != Y) --> while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5332 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5333 | if (EL.hasAnyInfo()) |
| 5334 | return EL; |
| 5335 | |
| 5336 | return getCouldNotCompute(); |
| 5337 | } |
| 5338 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5339 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 5340 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 5341 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5342 | const SCEV *InVal = SE.getConstant(C); |
| 5343 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5344 | assert(isa<SCEVConstant>(Val) && |
| 5345 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 5346 | return cast<SCEVConstant>(Val)->getValue(); |
| 5347 | } |
| 5348 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5349 | /// ComputeLoadConstantCompareExitLimit - Given an exit condition of |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5350 | /// 'icmp op load X, cst', try to see if we can compute the backedge |
| 5351 | /// execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5352 | ScalarEvolution::ExitLimit |
| 5353 | ScalarEvolution::ComputeLoadConstantCompareExitLimit( |
| 5354 | LoadInst *LI, |
| 5355 | Constant *RHS, |
| 5356 | const Loop *L, |
| 5357 | ICmpInst::Predicate predicate) { |
| 5358 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5359 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5360 | |
| 5361 | // Check to see if the loaded pointer is a getelementptr of a global. |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 5362 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5363 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5364 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5365 | |
| 5366 | // Make sure that it is really a constant global we are gepping, with an |
| 5367 | // initializer, and make sure the first IDX is really 0. |
| 5368 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 5369 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5370 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 5371 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5372 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5373 | |
| 5374 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5375 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 5376 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5377 | unsigned VarIdxNum = 0; |
| 5378 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 5379 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 5380 | Indexes.push_back(CI); |
| 5381 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5382 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5383 | VarIdx = GEP->getOperand(i); |
| 5384 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5385 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5386 | } |
| 5387 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 5388 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 5389 | if (!VarIdx) |
| 5390 | return getCouldNotCompute(); |
| 5391 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5392 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 5393 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5394 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5395 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5396 | |
| 5397 | // We can only recognize very limited forms of loop index expressions, in |
| 5398 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5399 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5400 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5401 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 5402 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5403 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5404 | |
| 5405 | unsigned MaxSteps = MaxBruteForceIterations; |
| 5406 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5407 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 5408 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5409 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5410 | |
| 5411 | // Form the GEP offset. |
| 5412 | Indexes[VarIdxNum] = Val; |
| 5413 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 5414 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 5415 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5416 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5417 | |
| 5418 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5419 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 5420 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 5421 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5422 | #if 0 |
David Greene | df1c497 | 2009-12-23 22:18:14 +0000 | [diff] [blame] | 5423 | dbgs() << "\n***\n*** Computed loop count " << *ItCst |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 5424 | << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() |
| 5425 | << "***\n"; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5426 | #endif |
| 5427 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5428 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5429 | } |
| 5430 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5431 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5432 | } |
| 5433 | |
| 5434 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5435 | /// CanConstantFold - Return true if we can constant fold an instruction of the |
| 5436 | /// specified type, assuming that all operands were constants. |
| 5437 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 5438 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5439 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 5440 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5441 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5442 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5443 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 5444 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 5445 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5446 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5447 | } |
| 5448 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5449 | /// Determine whether this instruction can constant evolve within this loop |
| 5450 | /// assuming its operands can all constant evolve. |
| 5451 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 5452 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 5453 | if (!L->contains(I)) return false; |
| 5454 | |
| 5455 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 5456 | // We don't currently keep track of the control flow needed to evaluate |
| 5457 | // PHIs, so we cannot handle PHIs inside of loops. |
| 5458 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5459 | } |
| 5460 | |
| 5461 | // If we won't be able to constant fold this expression even if the operands |
| 5462 | // are constants, bail early. |
| 5463 | return CanConstantFold(I); |
| 5464 | } |
| 5465 | |
| 5466 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 5467 | /// recursing through each instruction operand until reaching a loop header phi. |
| 5468 | static PHINode * |
| 5469 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5470 | DenseMap<Instruction *, PHINode *> &PHIMap) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5471 | |
| 5472 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 5473 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5474 | PHINode *PHI = nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5475 | for (Instruction::op_iterator OpI = UseInst->op_begin(), |
| 5476 | OpE = UseInst->op_end(); OpI != OpE; ++OpI) { |
| 5477 | |
| 5478 | if (isa<Constant>(*OpI)) continue; |
| 5479 | |
| 5480 | Instruction *OpInst = dyn_cast<Instruction>(*OpI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5481 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5482 | |
| 5483 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 5484 | if (!P) |
| 5485 | // If this operand is already visited, reuse the prior result. |
| 5486 | // We may have P != PHI if this is the deepest point at which the |
| 5487 | // inconsistent paths meet. |
| 5488 | P = PHIMap.lookup(OpInst); |
| 5489 | if (!P) { |
| 5490 | // Recurse and memoize the results, whether a phi is found or not. |
| 5491 | // This recursive call invalidates pointers into PHIMap. |
| 5492 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); |
| 5493 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5494 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5495 | if (!P) |
| 5496 | return nullptr; // Not evolving from PHI |
| 5497 | if (PHI && PHI != P) |
| 5498 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5499 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5500 | } |
| 5501 | // This is a expression evolving from a constant PHI! |
| 5502 | return PHI; |
| 5503 | } |
| 5504 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5505 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 5506 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 5507 | /// way, but the operands of an operation must either be constants or a value |
| 5508 | /// derived from a constant PHI. If this expression does not fit with these |
| 5509 | /// constraints, return null. |
| 5510 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5511 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5512 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5513 | |
Anton Korobeynikov | 579f071 | 2008-02-20 11:08:44 +0000 | [diff] [blame] | 5514 | if (PHINode *PN = dyn_cast<PHINode>(I)) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5515 | return PN; |
Anton Korobeynikov | 579f071 | 2008-02-20 11:08:44 +0000 | [diff] [blame] | 5516 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5517 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5518 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5519 | DenseMap<Instruction *, PHINode *> PHIMap; |
| 5520 | return getConstantEvolvingPHIOperands(I, L, PHIMap); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5521 | } |
| 5522 | |
| 5523 | /// EvaluateExpression - Given an expression that passes the |
| 5524 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 5525 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 5526 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5527 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 5528 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5529 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 5530 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5531 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 5532 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5533 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5534 | if (!I) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5535 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5536 | if (Constant *C = Vals.lookup(I)) return C; |
| 5537 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5538 | // An instruction inside the loop depends on a value outside the loop that we |
| 5539 | // weren't given a mapping for, or a value such as a call inside the loop. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5540 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5541 | |
| 5542 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 5543 | // or due to this not being the initial iteration through a loop where we |
| 5544 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5545 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5546 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 5547 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5548 | |
| 5549 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5550 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 5551 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 5552 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5553 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5554 | continue; |
| 5555 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5556 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5557 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5558 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5559 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5560 | } |
| 5561 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5562 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 5563 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5564 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5565 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 5566 | if (!LI->isVolatile()) |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5567 | return ConstantFoldLoadFromConstPtr(Operands[0], DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5568 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5569 | return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 5570 | TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5571 | } |
| 5572 | |
| 5573 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 5574 | /// in the header of its containing loop, we know the loop executes a |
| 5575 | /// constant number of times, and the PHI node is just a recurrence |
| 5576 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5577 | Constant * |
| 5578 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5579 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5580 | const Loop *L) { |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5581 | DenseMap<PHINode*, Constant*>::const_iterator I = |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5582 | ConstantEvolutionLoopExitValue.find(PN); |
| 5583 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 5584 | return I->second; |
| 5585 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 5586 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5587 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5588 | |
| 5589 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 5590 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5591 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5592 | BasicBlock *Header = L->getHeader(); |
| 5593 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5594 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5595 | // Since the loop is canonicalized, the PHI node must have two entries. One |
| 5596 | // entry must be a constant (coming in from outside of the loop), and the |
| 5597 | // second must be derived from the same PHI. |
| 5598 | bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5599 | PHINode *PHI = nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5600 | for (BasicBlock::iterator I = Header->begin(); |
| 5601 | (PHI = dyn_cast<PHINode>(I)); ++I) { |
| 5602 | Constant *StartCST = |
| 5603 | dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5604 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5605 | CurrentIterVals[PHI] = StartCST; |
| 5606 | } |
| 5607 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5608 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5609 | |
| 5610 | Value *BEValue = PN->getIncomingValue(SecondIsBackedge); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5611 | |
| 5612 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5613 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5614 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5615 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5616 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 5617 | unsigned IterationNum = 0; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5618 | const DataLayout &DL = F.getParent()->getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5619 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5620 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5621 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5622 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5623 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5624 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5625 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5626 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5627 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5628 | if (!NextPHI) |
| 5629 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5630 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5631 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5632 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 5633 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5634 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 5635 | // cease to be able to evaluate one of them or if they stop evolving, |
| 5636 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 5637 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5638 | for (DenseMap<Instruction *, Constant *>::const_iterator |
| 5639 | I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){ |
| 5640 | PHINode *PHI = dyn_cast<PHINode>(I->first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 5641 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 5642 | PHIsToCompute.push_back(std::make_pair(PHI, I->second)); |
| 5643 | } |
| 5644 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 5645 | // iterators into CurrentIterVals. |
| 5646 | for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator |
| 5647 | I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) { |
| 5648 | PHINode *PHI = I->first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5649 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5650 | if (!NextPHI) { // Not already computed. |
| 5651 | Value *BEValue = PHI->getIncomingValue(SecondIsBackedge); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5652 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5653 | } |
| 5654 | if (NextPHI != I->second) |
| 5655 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5656 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5657 | |
| 5658 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 5659 | // iterating, the loop can't continue to change. |
| 5660 | if (StoppedEvolving) |
| 5661 | return RetVal = CurrentIterVals[PN]; |
| 5662 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5663 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5664 | } |
| 5665 | } |
| 5666 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5667 | /// ComputeExitCountExhaustively - If the loop is known to execute a |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5668 | /// constant number of times (the condition evolves only from constants), |
| 5669 | /// try to evaluate a few iterations of the loop until we get the exit |
| 5670 | /// condition gets a value of ExitWhen (true or false). If we cannot |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5671 | /// evaluate the trip count of the loop, return getCouldNotCompute(). |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5672 | const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L, |
| 5673 | Value *Cond, |
| 5674 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5675 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5676 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5677 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 5678 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 5679 | // That's the only form we support here. |
| 5680 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 5681 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5682 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 5683 | BasicBlock *Header = L->getHeader(); |
| 5684 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 5685 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 5686 | // One entry must be a constant (coming in from outside of the loop), and the |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5687 | // second must be derived from the same PHI. |
| 5688 | bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5689 | PHINode *PHI = nullptr; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5690 | for (BasicBlock::iterator I = Header->begin(); |
| 5691 | (PHI = dyn_cast<PHINode>(I)); ++I) { |
| 5692 | Constant *StartCST = |
| 5693 | dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5694 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5695 | CurrentIterVals[PHI] = StartCST; |
| 5696 | } |
| 5697 | if (!CurrentIterVals.count(PN)) |
| 5698 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5699 | |
| 5700 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 5701 | // the loop symbolically to determine when the condition gets a value of |
| 5702 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5703 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5704 | const DataLayout &DL = F.getParent()->getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5705 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5706 | ConstantInt *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5707 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5708 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 5709 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5710 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 5711 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 5712 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5713 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 5714 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5715 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5716 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5717 | // Update all the PHI nodes for the next iteration. |
| 5718 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 5719 | |
| 5720 | // Create a list of which PHIs we need to compute. We want to do this before |
| 5721 | // calling EvaluateExpression on them because that may invalidate iterators |
| 5722 | // into CurrentIterVals. |
| 5723 | SmallVector<PHINode *, 8> PHIsToCompute; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5724 | for (DenseMap<Instruction *, Constant *>::const_iterator |
| 5725 | I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){ |
| 5726 | PHINode *PHI = dyn_cast<PHINode>(I->first); |
| 5727 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 5728 | PHIsToCompute.push_back(PHI); |
| 5729 | } |
| 5730 | for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(), |
| 5731 | E = PHIsToCompute.end(); I != E; ++I) { |
| 5732 | PHINode *PHI = *I; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5733 | Constant *&NextPHI = NextIterVals[PHI]; |
| 5734 | if (NextPHI) continue; // Already computed! |
| 5735 | |
| 5736 | Value *BEValue = PHI->getIncomingValue(SecondIsBackedge); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5737 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 5738 | } |
| 5739 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5740 | } |
| 5741 | |
| 5742 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5743 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5744 | } |
| 5745 | |
Dan Gohman | 237d9e5 | 2009-09-03 15:00:26 +0000 | [diff] [blame] | 5746 | /// getSCEVAtScope - Return a SCEV expression for the specified value |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 5747 | /// at the specified scope in the program. The L value specifies a loop |
| 5748 | /// nest to evaluate the expression at, where null is the top-level or a |
| 5749 | /// specified loop is immediately inside of the loop. |
| 5750 | /// |
| 5751 | /// This method can be used to compute the exit value for a variable defined |
| 5752 | /// in a loop by querying what the value will hold in the parent loop. |
| 5753 | /// |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5754 | /// In the case that a relevant loop exit value cannot be computed, the |
| 5755 | /// original value V is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5756 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 5757 | // Check to see if we've folded this expression at this loop before. |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 5758 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V]; |
| 5759 | for (unsigned u = 0; u < Values.size(); u++) { |
| 5760 | if (Values[u].first == L) |
| 5761 | return Values[u].second ? Values[u].second : V; |
| 5762 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5763 | Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr))); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 5764 | // Otherwise compute it. |
| 5765 | const SCEV *C = computeSCEVAtScope(V, L); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 5766 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V]; |
| 5767 | for (unsigned u = Values2.size(); u > 0; u--) { |
| 5768 | if (Values2[u - 1].first == L) { |
| 5769 | Values2[u - 1].second = C; |
| 5770 | break; |
| 5771 | } |
| 5772 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 5773 | return C; |
| 5774 | } |
| 5775 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5776 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 5777 | /// will return Constants for objects which aren't represented by a |
| 5778 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 5779 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 5780 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 5781 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5782 | case scCouldNotCompute: |
| 5783 | case scAddRecExpr: |
| 5784 | break; |
| 5785 | case scConstant: |
| 5786 | return cast<SCEVConstant>(V)->getValue(); |
| 5787 | case scUnknown: |
| 5788 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 5789 | case scSignExtend: { |
| 5790 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 5791 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 5792 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 5793 | break; |
| 5794 | } |
| 5795 | case scZeroExtend: { |
| 5796 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 5797 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 5798 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 5799 | break; |
| 5800 | } |
| 5801 | case scTruncate: { |
| 5802 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 5803 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 5804 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 5805 | break; |
| 5806 | } |
| 5807 | case scAddExpr: { |
| 5808 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 5809 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 5810 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 5811 | unsigned AS = PTy->getAddressSpace(); |
| 5812 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 5813 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 5814 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5815 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 5816 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5817 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5818 | |
| 5819 | // First pointer! |
| 5820 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 5821 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5822 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 5823 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5824 | // The offsets have been converted to bytes. We can add bytes to an |
| 5825 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 5826 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5827 | } |
| 5828 | |
| 5829 | // Don't bother trying to sum two pointers. We probably can't |
| 5830 | // statically compute a load that results from it anyway. |
| 5831 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5832 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5833 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 5834 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 5835 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5836 | C2 = ConstantExpr::getIntegerCast( |
| 5837 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 5838 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5839 | } else |
| 5840 | C = ConstantExpr::getAdd(C, C2); |
| 5841 | } |
| 5842 | return C; |
| 5843 | } |
| 5844 | break; |
| 5845 | } |
| 5846 | case scMulExpr: { |
| 5847 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 5848 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 5849 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5850 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5851 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 5852 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5853 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5854 | C = ConstantExpr::getMul(C, C2); |
| 5855 | } |
| 5856 | return C; |
| 5857 | } |
| 5858 | break; |
| 5859 | } |
| 5860 | case scUDivExpr: { |
| 5861 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 5862 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 5863 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 5864 | if (LHS->getType() == RHS->getType()) |
| 5865 | return ConstantExpr::getUDiv(LHS, RHS); |
| 5866 | break; |
| 5867 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 5868 | case scSMaxExpr: |
| 5869 | case scUMaxExpr: |
| 5870 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5871 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5872 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5873 | } |
| 5874 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 5875 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5876 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5877 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 5878 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5879 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5880 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5881 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5882 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5883 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 5884 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5885 | if (PN->getParent() == LI->getHeader()) { |
| 5886 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5887 | // to see if the loop that contains it has a known backedge-taken |
| 5888 | // count. If so, we may be able to force computation of the exit |
| 5889 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5890 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5891 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5892 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5893 | // Okay, we know how many times the containing loop executes. If |
| 5894 | // this is a constant evolving PHI node, get the final value at |
| 5895 | // the specified iteration number. |
| 5896 | Constant *RV = getConstantEvolutionLoopExitValue(PN, |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5897 | BTCC->getValue()->getValue(), |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5898 | LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 5899 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5900 | } |
| 5901 | } |
| 5902 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 5903 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5904 | // into a SCEV. Check to see if it's possible to symbolically evaluate |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 5905 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5906 | // result. This is particularly useful for computing loop exit values. |
| 5907 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5908 | SmallVector<Constant *, 4> Operands; |
| 5909 | bool MadeImprovement = false; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5910 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 5911 | Value *Op = I->getOperand(i); |
| 5912 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 5913 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5914 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5915 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5916 | |
| 5917 | // If any of the operands is non-constant and if they are |
| 5918 | // non-integer and non-pointer, don't even try to analyze them |
| 5919 | // with scev techniques. |
| 5920 | if (!isSCEVable(Op->getType())) |
| 5921 | return V; |
| 5922 | |
| 5923 | const SCEV *OrigV = getSCEV(Op); |
| 5924 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 5925 | MadeImprovement |= OrigV != OpV; |
| 5926 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5927 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5928 | if (!C) return V; |
| 5929 | if (C->getType() != Op->getType()) |
| 5930 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 5931 | Op->getType(), |
| 5932 | false), |
| 5933 | C, Op->getType()); |
| 5934 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5935 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5936 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5937 | // Check to see if getSCEVAtScope actually made an improvement. |
| 5938 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5939 | Constant *C = nullptr; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5940 | const DataLayout &DL = F.getParent()->getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5941 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5942 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5943 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5944 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 5945 | if (!LI->isVolatile()) |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5946 | C = ConstantFoldLoadFromConstPtr(Operands[0], DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5947 | } else |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5948 | C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5949 | DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5950 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 5951 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 5952 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5953 | } |
| 5954 | } |
| 5955 | |
| 5956 | // This is some other type of SCEVUnknown, just return it. |
| 5957 | return V; |
| 5958 | } |
| 5959 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5960 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5961 | // Avoid performing the look-up in the common case where the specified |
| 5962 | // expression has no loop-variant portions. |
| 5963 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5964 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5965 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5966 | // Okay, at least one of these operands is loop variant but might be |
| 5967 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5968 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 5969 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5970 | NewOps.push_back(OpAtScope); |
| 5971 | |
| 5972 | for (++i; i != e; ++i) { |
| 5973 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5974 | NewOps.push_back(OpAtScope); |
| 5975 | } |
| 5976 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5977 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 5978 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5979 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 5980 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5981 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 5982 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5983 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 5984 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5985 | } |
| 5986 | } |
| 5987 | // If we got here, all operands are loop invariant. |
| 5988 | return Comm; |
| 5989 | } |
| 5990 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5991 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5992 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 5993 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 5994 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 5995 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5996 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5997 | } |
| 5998 | |
| 5999 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6000 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6001 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6002 | // First, attempt to evaluate each operand. |
| 6003 | // Avoid performing the look-up in the common case where the specified |
| 6004 | // expression has no loop-variant portions. |
| 6005 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6006 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6007 | if (OpAtScope == AddRec->getOperand(i)) |
| 6008 | continue; |
| 6009 | |
| 6010 | // Okay, at least one of these operands is loop variant but might be |
| 6011 | // foldable. Build a new instance of the folded commutative expression. |
| 6012 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6013 | AddRec->op_begin()+i); |
| 6014 | NewOps.push_back(OpAtScope); |
| 6015 | for (++i; i != e; ++i) |
| 6016 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6017 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6018 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6019 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6020 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6021 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6022 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6023 | // induction variable is multiplied by zero after constant folding. Go |
| 6024 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6025 | if (!AddRec) |
| 6026 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6027 | break; |
| 6028 | } |
| 6029 | |
| 6030 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6031 | // loop exit value of the addrec. |
| 6032 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6033 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6034 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6035 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6036 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6037 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6038 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6039 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6040 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6041 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6042 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6043 | } |
| 6044 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6045 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6046 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6047 | if (Op == Cast->getOperand()) |
| 6048 | return Cast; // must be loop invariant |
| 6049 | return getZeroExtendExpr(Op, Cast->getType()); |
| 6050 | } |
| 6051 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6052 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6053 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6054 | if (Op == Cast->getOperand()) |
| 6055 | return Cast; // must be loop invariant |
| 6056 | return getSignExtendExpr(Op, Cast->getType()); |
| 6057 | } |
| 6058 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6059 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6060 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6061 | if (Op == Cast->getOperand()) |
| 6062 | return Cast; // must be loop invariant |
| 6063 | return getTruncateExpr(Op, Cast->getType()); |
| 6064 | } |
| 6065 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6066 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6067 | } |
| 6068 | |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6069 | /// getSCEVAtScope - This is a convenience function which does |
| 6070 | /// getSCEVAtScope(getSCEV(V), L). |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6071 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6072 | return getSCEVAtScope(getSCEV(V), L); |
| 6073 | } |
| 6074 | |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6075 | /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the |
| 6076 | /// following equation: |
| 6077 | /// |
| 6078 | /// A * X = B (mod N) |
| 6079 | /// |
| 6080 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 6081 | /// A and B isn't important. |
| 6082 | /// |
| 6083 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6084 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6085 | ScalarEvolution &SE) { |
| 6086 | uint32_t BW = A.getBitWidth(); |
| 6087 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 6088 | assert(A != 0 && "A must be non-zero."); |
| 6089 | |
| 6090 | // 1. D = gcd(A, N) |
| 6091 | // |
| 6092 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 6093 | // trailing zeros in A is its multiplicity |
| 6094 | uint32_t Mult2 = A.countTrailingZeros(); |
| 6095 | // D = 2^Mult2 |
| 6096 | |
| 6097 | // 2. Check if B is divisible by D. |
| 6098 | // |
| 6099 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 6100 | // is not less than multiplicity of this prime factor for D. |
| 6101 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 6102 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6103 | |
| 6104 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 6105 | // modulo (N / D). |
| 6106 | // |
| 6107 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 6108 | // bit width during computations. |
| 6109 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 6110 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 6111 | Mod.setBit(BW - Mult2); // Mod = N / D |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6112 | APInt I = AD.multiplicativeInverse(Mod); |
| 6113 | |
| 6114 | // 4. Compute the minimum unsigned root of the equation: |
| 6115 | // I * (B / D) mod (N / D) |
| 6116 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 6117 | |
| 6118 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 6119 | // bits. |
| 6120 | return SE.getConstant(Result.trunc(BW)); |
| 6121 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6122 | |
| 6123 | /// SolveQuadraticEquation - Find the roots of the quadratic equation for the |
| 6124 | /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which |
| 6125 | /// might be the same) or two SCEVCouldNotCompute objects. |
| 6126 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6127 | static std::pair<const SCEV *,const SCEV *> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6128 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6129 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6130 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 6131 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 6132 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6133 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6134 | // We currently can only solve this if the coefficients are constants. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6135 | if (!LC || !MC || !NC) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6136 | const SCEV *CNC = SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6137 | return std::make_pair(CNC, CNC); |
| 6138 | } |
| 6139 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6140 | uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); |
Chris Lattner | cad61e8 | 2007-04-15 19:52:49 +0000 | [diff] [blame] | 6141 | const APInt &L = LC->getValue()->getValue(); |
| 6142 | const APInt &M = MC->getValue()->getValue(); |
| 6143 | const APInt &N = NC->getValue()->getValue(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6144 | APInt Two(BitWidth, 2); |
| 6145 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6146 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6147 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6148 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6149 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6150 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 6151 | // The B coefficient is M-N/2 |
| 6152 | APInt B(M); |
| 6153 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6154 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6155 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6156 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6157 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6158 | // Compute the B^2-4ac term. |
| 6159 | APInt SqrtTerm(B); |
| 6160 | SqrtTerm *= B; |
| 6161 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6162 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6163 | if (SqrtTerm.isNegative()) { |
| 6164 | // The loop is provably infinite. |
| 6165 | const SCEV *CNC = SE.getCouldNotCompute(); |
| 6166 | return std::make_pair(CNC, CNC); |
| 6167 | } |
| 6168 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6169 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 6170 | // integer value or else APInt::sqrt() will assert. |
| 6171 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6172 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6173 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6174 | // The divisions must be performed as signed divisions. |
| 6175 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6176 | APInt TwoA(A << 1); |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6177 | if (TwoA.isMinValue()) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6178 | const SCEV *CNC = SE.getCouldNotCompute(); |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6179 | return std::make_pair(CNC, CNC); |
| 6180 | } |
| 6181 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 6182 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6183 | |
| 6184 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6185 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6186 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6187 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6188 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6189 | return std::make_pair(SE.getConstant(Solution1), |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6190 | SE.getConstant(Solution2)); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6191 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6192 | } |
| 6193 | |
| 6194 | /// HowFarToZero - Return the number of times a backedge comparing the specified |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 6195 | /// value to zero will execute. If not computable, return CouldNotCompute. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6196 | /// |
| 6197 | /// This is only used for loops with a "x != y" exit test. The exit condition is |
| 6198 | /// now expressed as a single expression, V = x-y. So the exit test is |
| 6199 | /// effectively V != 0. We know and take advantage of the fact that this |
| 6200 | /// expression only being used in a comparison by zero context. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6201 | ScalarEvolution::ExitLimit |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6202 | ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6203 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6204 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6205 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 6206 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6207 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6208 | } |
| 6209 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6210 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6211 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6212 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6213 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6214 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 6215 | // the quadratic equation to solve it. |
| 6216 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
| 6217 | std::pair<const SCEV *,const SCEV *> Roots = |
| 6218 | SolveQuadraticEquation(AddRec, *this); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6219 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 6220 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6221 | if (R1 && R2) { |
Chris Lattner | 0916921 | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 6222 | #if 0 |
David Greene | df1c497 | 2009-12-23 22:18:14 +0000 | [diff] [blame] | 6223 | dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1 |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 6224 | << " sol#2: " << *R2 << "\n"; |
Chris Lattner | 0916921 | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 6225 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6226 | // Pick the smallest positive root value. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6227 | if (ConstantInt *CB = |
Chris Lattner | 28f140a | 2011-01-09 22:58:47 +0000 | [diff] [blame] | 6228 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, |
| 6229 | R1->getValue(), |
| 6230 | R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6231 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6232 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 6233 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6234 | // We can only use this value if the chrec ends up with an exact zero |
| 6235 | // value at this index. When solving for "X*X != 5", for example, we |
| 6236 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6237 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 6238 | if (Val->isZero()) |
| 6239 | return R1; // We found a quadratic root! |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6240 | } |
| 6241 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6242 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6243 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6244 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6245 | // Otherwise we can only handle this if it is affine. |
| 6246 | if (!AddRec->isAffine()) |
| 6247 | return getCouldNotCompute(); |
| 6248 | |
| 6249 | // If this is an affine expression, the execution count of this branch is |
| 6250 | // the minimum unsigned root of the following equation: |
| 6251 | // |
| 6252 | // Start + Step*N = 0 (mod 2^BW) |
| 6253 | // |
| 6254 | // equivalent to: |
| 6255 | // |
| 6256 | // Step*N = -Start (mod 2^BW) |
| 6257 | // |
| 6258 | // where BW is the common bit width of Start and Step. |
| 6259 | |
| 6260 | // Get the initial value for the loop. |
| 6261 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 6262 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 6263 | |
| 6264 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6265 | // |
| 6266 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 6267 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 6268 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 6269 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6270 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6271 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6272 | return getCouldNotCompute(); |
| 6273 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6274 | // For positive steps (counting up until unsigned overflow): |
| 6275 | // N = -Start/Step (as unsigned) |
| 6276 | // For negative steps (counting down to zero): |
| 6277 | // N = Start/-Step |
| 6278 | // First compute the unsigned distance from zero in the direction of Step. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 6279 | bool CountDown = StepC->getValue()->getValue().isNegative(); |
| 6280 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6281 | |
| 6282 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 6283 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 6284 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6285 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
| 6286 | ConstantRange CR = getUnsignedRange(Start); |
| 6287 | const SCEV *MaxBECount; |
| 6288 | if (!CountDown && CR.getUnsignedMin().isMinValue()) |
| 6289 | // When counting up, the worst starting value is 1, not 0. |
| 6290 | MaxBECount = CR.getUnsignedMax().isMinValue() |
| 6291 | ? getConstant(APInt::getMinValue(CR.getBitWidth())) |
| 6292 | : getConstant(APInt::getMaxValue(CR.getBitWidth())); |
| 6293 | else |
| 6294 | MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() |
| 6295 | : -CR.getUnsignedMin()); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6296 | return ExitLimit(Distance, MaxBECount); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6297 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 6298 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6299 | // As a special case, handle the instance where Step is a positive power of |
| 6300 | // two. In this case, determining whether Step divides Distance evenly can be |
| 6301 | // done by counting and comparing the number of trailing zeros of Step and |
| 6302 | // Distance. |
| 6303 | if (!CountDown) { |
| 6304 | const APInt &StepV = StepC->getValue()->getValue(); |
| 6305 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 6306 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 6307 | // case is not handled as this code is guarded by !CountDown. |
| 6308 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame^] | 6309 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 6310 | // Here we've constrained the equation to be of the form |
| 6311 | // |
| 6312 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 6313 | // |
| 6314 | // where we're operating on a W bit wide integer domain and k is |
| 6315 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 6316 | // |
| 6317 | // (0) is equivalent to: |
| 6318 | // |
| 6319 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 6320 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 6321 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 6322 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 6323 | // |
| 6324 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 6325 | // by 2^(W - N). |
| 6326 | // |
| 6327 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 6328 | // |
| 6329 | // E.g. say we're solving |
| 6330 | // |
| 6331 | // 2 * Val = 2 * X (in i8) ... (3) |
| 6332 | // |
| 6333 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 6334 | // |
| 6335 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 6336 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 6337 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 6338 | // is i8 1, not i8 -127 |
| 6339 | |
| 6340 | const auto *ModuloResult = getUDivExactExpr(Distance, Step); |
| 6341 | |
| 6342 | // Since SCEV does not have a URem node, we construct one using a truncate |
| 6343 | // and a zero extend. |
| 6344 | |
| 6345 | unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); |
| 6346 | auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); |
| 6347 | auto *WideTy = Distance->getType(); |
| 6348 | |
| 6349 | return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); |
| 6350 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6351 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 6352 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6353 | // If the condition controls loop exit (the loop exits only if the expression |
| 6354 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 6355 | // compute the backedge count. In this case, the step may not divide the |
| 6356 | // distance, but we don't care because if the condition is "missed" the loop |
| 6357 | // will have undefined behavior due to wrapping. |
| 6358 | if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) { |
| 6359 | const SCEV *Exact = |
| 6360 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
| 6361 | return ExitLimit(Exact, Exact); |
| 6362 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 6363 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6364 | // Then, try to solve the above equation provided that Start is constant. |
| 6365 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) |
| 6366 | return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), |
| 6367 | -StartC->getValue()->getValue(), |
| 6368 | *this); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6369 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6370 | } |
| 6371 | |
| 6372 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 6373 | /// specified value for nonzero will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 6374 | /// CouldNotCompute |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6375 | ScalarEvolution::ExitLimit |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 6376 | ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6377 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 6378 | // handle them yet except for the trivial case. This could be expanded in the |
| 6379 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6380 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6381 | // If the value is a constant, check to see if it is known to be non-zero |
| 6382 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6383 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 6384 | if (!C->getValue()->isNullValue()) |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 6385 | return getConstant(C->getType(), 0); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6386 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6387 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6388 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6389 | // We could implement others, but I really doubt anyone writes loops like |
| 6390 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6391 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6392 | } |
| 6393 | |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6394 | /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB |
| 6395 | /// (which may not be an immediate predecessor) which has exactly one |
| 6396 | /// successor from which BB is reachable, or null if no such block is |
| 6397 | /// found. |
| 6398 | /// |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 6399 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6400 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 6401 | // If the block has a unique predecessor, then there is no path from the |
| 6402 | // predecessor to the block that does not go through the direct edge |
| 6403 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6404 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 6405 | return std::make_pair(Pred, BB); |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6406 | |
| 6407 | // A loop's header is defined to be a block that dominates the loop. |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 6408 | // If the header has a unique predecessor outside the loop, it must be |
| 6409 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6410 | if (Loop *L = LI.getLoopFor(BB)) |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 6411 | return std::make_pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6412 | |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 6413 | return std::pair<BasicBlock *, BasicBlock *>(); |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6414 | } |
| 6415 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6416 | /// HasSameValue - SCEV structural equivalence is usually sufficient for |
| 6417 | /// testing whether two expressions are equal, however for the purposes of |
| 6418 | /// looking for a condition guarding a loop, it can be useful to be a little |
| 6419 | /// more general, since a front-end may have replicated the controlling |
| 6420 | /// expression. |
| 6421 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6422 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6423 | // Quick check to see if they are the same SCEV. |
| 6424 | if (A == B) return true; |
| 6425 | |
| 6426 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 6427 | // two different instructions with the same value. Check for this case. |
| 6428 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 6429 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 6430 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 6431 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Dan Gohman | 2d08556 | 2009-08-25 17:56:57 +0000 | [diff] [blame] | 6432 | if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory()) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6433 | return true; |
| 6434 | |
| 6435 | // Otherwise assume they may have a different value. |
| 6436 | return false; |
| 6437 | } |
| 6438 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6439 | /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 6440 | /// predicate Pred. Return true iff any changes were made. |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6441 | /// |
| 6442 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6443 | const SCEV *&LHS, const SCEV *&RHS, |
| 6444 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6445 | bool Changed = false; |
| 6446 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6447 | // If we hit the max recursion limit bail out. |
| 6448 | if (Depth >= 3) |
| 6449 | return false; |
| 6450 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6451 | // Canonicalize a constant to the right side. |
| 6452 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 6453 | // Check for both operands constant. |
| 6454 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 6455 | if (ConstantExpr::getICmp(Pred, |
| 6456 | LHSC->getValue(), |
| 6457 | RHSC->getValue())->isNullValue()) |
| 6458 | goto trivially_false; |
| 6459 | else |
| 6460 | goto trivially_true; |
| 6461 | } |
| 6462 | // Otherwise swap the operands to put the constant on the right. |
| 6463 | std::swap(LHS, RHS); |
| 6464 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 6465 | Changed = true; |
| 6466 | } |
| 6467 | |
| 6468 | // If we're comparing an addrec with a value which is loop-invariant in the |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 6469 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 6470 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 6471 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 6472 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 6473 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6474 | std::swap(LHS, RHS); |
| 6475 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 6476 | Changed = true; |
| 6477 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 6478 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6479 | |
| 6480 | // If there's a constant operand, canonicalize comparisons with boundary |
| 6481 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 6482 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
| 6483 | const APInt &RA = RC->getValue()->getValue(); |
| 6484 | switch (Pred) { |
| 6485 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 6486 | case ICmpInst::ICMP_EQ: |
| 6487 | case ICmpInst::ICMP_NE: |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6488 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 6489 | if (!RA) |
| 6490 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 6491 | if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
Benjamin Kramer | 406a2db | 2012-05-30 18:42:43 +0000 | [diff] [blame] | 6492 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 6493 | ME->getOperand(0)->isAllOnesValue()) { |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6494 | RHS = AE->getOperand(1); |
| 6495 | LHS = ME->getOperand(1); |
| 6496 | Changed = true; |
| 6497 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6498 | break; |
| 6499 | case ICmpInst::ICMP_UGE: |
| 6500 | if ((RA - 1).isMinValue()) { |
| 6501 | Pred = ICmpInst::ICMP_NE; |
| 6502 | RHS = getConstant(RA - 1); |
| 6503 | Changed = true; |
| 6504 | break; |
| 6505 | } |
| 6506 | if (RA.isMaxValue()) { |
| 6507 | Pred = ICmpInst::ICMP_EQ; |
| 6508 | Changed = true; |
| 6509 | break; |
| 6510 | } |
| 6511 | if (RA.isMinValue()) goto trivially_true; |
| 6512 | |
| 6513 | Pred = ICmpInst::ICMP_UGT; |
| 6514 | RHS = getConstant(RA - 1); |
| 6515 | Changed = true; |
| 6516 | break; |
| 6517 | case ICmpInst::ICMP_ULE: |
| 6518 | if ((RA + 1).isMaxValue()) { |
| 6519 | Pred = ICmpInst::ICMP_NE; |
| 6520 | RHS = getConstant(RA + 1); |
| 6521 | Changed = true; |
| 6522 | break; |
| 6523 | } |
| 6524 | if (RA.isMinValue()) { |
| 6525 | Pred = ICmpInst::ICMP_EQ; |
| 6526 | Changed = true; |
| 6527 | break; |
| 6528 | } |
| 6529 | if (RA.isMaxValue()) goto trivially_true; |
| 6530 | |
| 6531 | Pred = ICmpInst::ICMP_ULT; |
| 6532 | RHS = getConstant(RA + 1); |
| 6533 | Changed = true; |
| 6534 | break; |
| 6535 | case ICmpInst::ICMP_SGE: |
| 6536 | if ((RA - 1).isMinSignedValue()) { |
| 6537 | Pred = ICmpInst::ICMP_NE; |
| 6538 | RHS = getConstant(RA - 1); |
| 6539 | Changed = true; |
| 6540 | break; |
| 6541 | } |
| 6542 | if (RA.isMaxSignedValue()) { |
| 6543 | Pred = ICmpInst::ICMP_EQ; |
| 6544 | Changed = true; |
| 6545 | break; |
| 6546 | } |
| 6547 | if (RA.isMinSignedValue()) goto trivially_true; |
| 6548 | |
| 6549 | Pred = ICmpInst::ICMP_SGT; |
| 6550 | RHS = getConstant(RA - 1); |
| 6551 | Changed = true; |
| 6552 | break; |
| 6553 | case ICmpInst::ICMP_SLE: |
| 6554 | if ((RA + 1).isMaxSignedValue()) { |
| 6555 | Pred = ICmpInst::ICMP_NE; |
| 6556 | RHS = getConstant(RA + 1); |
| 6557 | Changed = true; |
| 6558 | break; |
| 6559 | } |
| 6560 | if (RA.isMinSignedValue()) { |
| 6561 | Pred = ICmpInst::ICMP_EQ; |
| 6562 | Changed = true; |
| 6563 | break; |
| 6564 | } |
| 6565 | if (RA.isMaxSignedValue()) goto trivially_true; |
| 6566 | |
| 6567 | Pred = ICmpInst::ICMP_SLT; |
| 6568 | RHS = getConstant(RA + 1); |
| 6569 | Changed = true; |
| 6570 | break; |
| 6571 | case ICmpInst::ICMP_UGT: |
| 6572 | if (RA.isMinValue()) { |
| 6573 | Pred = ICmpInst::ICMP_NE; |
| 6574 | Changed = true; |
| 6575 | break; |
| 6576 | } |
| 6577 | if ((RA + 1).isMaxValue()) { |
| 6578 | Pred = ICmpInst::ICMP_EQ; |
| 6579 | RHS = getConstant(RA + 1); |
| 6580 | Changed = true; |
| 6581 | break; |
| 6582 | } |
| 6583 | if (RA.isMaxValue()) goto trivially_false; |
| 6584 | break; |
| 6585 | case ICmpInst::ICMP_ULT: |
| 6586 | if (RA.isMaxValue()) { |
| 6587 | Pred = ICmpInst::ICMP_NE; |
| 6588 | Changed = true; |
| 6589 | break; |
| 6590 | } |
| 6591 | if ((RA - 1).isMinValue()) { |
| 6592 | Pred = ICmpInst::ICMP_EQ; |
| 6593 | RHS = getConstant(RA - 1); |
| 6594 | Changed = true; |
| 6595 | break; |
| 6596 | } |
| 6597 | if (RA.isMinValue()) goto trivially_false; |
| 6598 | break; |
| 6599 | case ICmpInst::ICMP_SGT: |
| 6600 | if (RA.isMinSignedValue()) { |
| 6601 | Pred = ICmpInst::ICMP_NE; |
| 6602 | Changed = true; |
| 6603 | break; |
| 6604 | } |
| 6605 | if ((RA + 1).isMaxSignedValue()) { |
| 6606 | Pred = ICmpInst::ICMP_EQ; |
| 6607 | RHS = getConstant(RA + 1); |
| 6608 | Changed = true; |
| 6609 | break; |
| 6610 | } |
| 6611 | if (RA.isMaxSignedValue()) goto trivially_false; |
| 6612 | break; |
| 6613 | case ICmpInst::ICMP_SLT: |
| 6614 | if (RA.isMaxSignedValue()) { |
| 6615 | Pred = ICmpInst::ICMP_NE; |
| 6616 | Changed = true; |
| 6617 | break; |
| 6618 | } |
| 6619 | if ((RA - 1).isMinSignedValue()) { |
| 6620 | Pred = ICmpInst::ICMP_EQ; |
| 6621 | RHS = getConstant(RA - 1); |
| 6622 | Changed = true; |
| 6623 | break; |
| 6624 | } |
| 6625 | if (RA.isMinSignedValue()) goto trivially_false; |
| 6626 | break; |
| 6627 | } |
| 6628 | } |
| 6629 | |
| 6630 | // Check for obvious equality. |
| 6631 | if (HasSameValue(LHS, RHS)) { |
| 6632 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 6633 | goto trivially_true; |
| 6634 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 6635 | goto trivially_false; |
| 6636 | } |
| 6637 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6638 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 6639 | // adding or subtracting 1 from one of the operands. |
| 6640 | switch (Pred) { |
| 6641 | case ICmpInst::ICMP_SLE: |
| 6642 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 6643 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6644 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6645 | Pred = ICmpInst::ICMP_SLT; |
| 6646 | Changed = true; |
| 6647 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 6648 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6649 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6650 | Pred = ICmpInst::ICMP_SLT; |
| 6651 | Changed = true; |
| 6652 | } |
| 6653 | break; |
| 6654 | case ICmpInst::ICMP_SGE: |
| 6655 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 6656 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6657 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6658 | Pred = ICmpInst::ICMP_SGT; |
| 6659 | Changed = true; |
| 6660 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 6661 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6662 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6663 | Pred = ICmpInst::ICMP_SGT; |
| 6664 | Changed = true; |
| 6665 | } |
| 6666 | break; |
| 6667 | case ICmpInst::ICMP_ULE: |
| 6668 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 6669 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6670 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6671 | Pred = ICmpInst::ICMP_ULT; |
| 6672 | Changed = true; |
| 6673 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 6674 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6675 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6676 | Pred = ICmpInst::ICMP_ULT; |
| 6677 | Changed = true; |
| 6678 | } |
| 6679 | break; |
| 6680 | case ICmpInst::ICMP_UGE: |
| 6681 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 6682 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6683 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6684 | Pred = ICmpInst::ICMP_UGT; |
| 6685 | Changed = true; |
| 6686 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 6687 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6688 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6689 | Pred = ICmpInst::ICMP_UGT; |
| 6690 | Changed = true; |
| 6691 | } |
| 6692 | break; |
| 6693 | default: |
| 6694 | break; |
| 6695 | } |
| 6696 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6697 | // TODO: More simplifications are possible here. |
| 6698 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6699 | // Recursively simplify until we either hit a recursion limit or nothing |
| 6700 | // changes. |
| 6701 | if (Changed) |
| 6702 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 6703 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6704 | return Changed; |
| 6705 | |
| 6706 | trivially_true: |
| 6707 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 6708 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6709 | Pred = ICmpInst::ICMP_EQ; |
| 6710 | return true; |
| 6711 | |
| 6712 | trivially_false: |
| 6713 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 6714 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6715 | Pred = ICmpInst::ICMP_NE; |
| 6716 | return true; |
| 6717 | } |
| 6718 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6719 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 6720 | return getSignedRange(S).getSignedMax().isNegative(); |
| 6721 | } |
| 6722 | |
| 6723 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 6724 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 6725 | } |
| 6726 | |
| 6727 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 6728 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 6729 | } |
| 6730 | |
| 6731 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 6732 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 6733 | } |
| 6734 | |
| 6735 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 6736 | return isKnownNegative(S) || isKnownPositive(S); |
| 6737 | } |
| 6738 | |
| 6739 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 6740 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 6741 | // Canonicalize the inputs first. |
| 6742 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 6743 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 6744 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 6745 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 6746 | // If LHS and RHS are both addrec, both conditions must be true in |
| 6747 | // every iteration of the loop. |
| 6748 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 6749 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 6750 | bool LeftGuarded = false; |
| 6751 | bool RightGuarded = false; |
| 6752 | if (LAR) { |
| 6753 | const Loop *L = LAR->getLoop(); |
| 6754 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 6755 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 6756 | if (!RAR) return true; |
| 6757 | LeftGuarded = true; |
| 6758 | } |
| 6759 | } |
| 6760 | if (RAR) { |
| 6761 | const Loop *L = RAR->getLoop(); |
| 6762 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 6763 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 6764 | if (!LAR) return true; |
| 6765 | RightGuarded = true; |
| 6766 | } |
| 6767 | } |
| 6768 | if (LeftGuarded && RightGuarded) |
| 6769 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6770 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 6771 | // Otherwise see what can be done with known constant ranges. |
| 6772 | return isKnownPredicateWithRanges(Pred, LHS, RHS); |
| 6773 | } |
| 6774 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 6775 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 6776 | ICmpInst::Predicate Pred, |
| 6777 | bool &Increasing) { |
| 6778 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 6779 | |
| 6780 | #ifndef NDEBUG |
| 6781 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 6782 | // increasing change to a monotonically decreasing one, and vice versa. |
| 6783 | bool IncreasingSwapped; |
| 6784 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 6785 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 6786 | |
| 6787 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 6788 | if (ResultSwapped) |
| 6789 | assert(Increasing == !IncreasingSwapped && |
| 6790 | "monotonicity should flip as we flip the predicate"); |
| 6791 | #endif |
| 6792 | |
| 6793 | return Result; |
| 6794 | } |
| 6795 | |
| 6796 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 6797 | ICmpInst::Predicate Pred, |
| 6798 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 6799 | |
| 6800 | // A zero step value for LHS means the induction variable is essentially a |
| 6801 | // loop invariant value. We don't really depend on the predicate actually |
| 6802 | // flipping from false to true (for increasing predicates, and the other way |
| 6803 | // around for decreasing predicates), all we care about is that *if* the |
| 6804 | // predicate changes then it only changes from false to true. |
| 6805 | // |
| 6806 | // A zero step value in itself is not very useful, but there may be places |
| 6807 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 6808 | // as general as possible. |
| 6809 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 6810 | switch (Pred) { |
| 6811 | default: |
| 6812 | return false; // Conservative answer |
| 6813 | |
| 6814 | case ICmpInst::ICMP_UGT: |
| 6815 | case ICmpInst::ICMP_UGE: |
| 6816 | case ICmpInst::ICMP_ULT: |
| 6817 | case ICmpInst::ICMP_ULE: |
| 6818 | if (!LHS->getNoWrapFlags(SCEV::FlagNUW)) |
| 6819 | return false; |
| 6820 | |
| 6821 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 6822 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 6823 | |
| 6824 | case ICmpInst::ICMP_SGT: |
| 6825 | case ICmpInst::ICMP_SGE: |
| 6826 | case ICmpInst::ICMP_SLT: |
| 6827 | case ICmpInst::ICMP_SLE: { |
| 6828 | if (!LHS->getNoWrapFlags(SCEV::FlagNSW)) |
| 6829 | return false; |
| 6830 | |
| 6831 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 6832 | |
| 6833 | if (isKnownNonNegative(Step)) { |
| 6834 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 6835 | return true; |
| 6836 | } |
| 6837 | |
| 6838 | if (isKnownNonPositive(Step)) { |
| 6839 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 6840 | return true; |
| 6841 | } |
| 6842 | |
| 6843 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 6844 | } |
| 6845 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 6846 | } |
| 6847 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 6848 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 6849 | } |
| 6850 | |
| 6851 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 6852 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 6853 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 6854 | const SCEV *&InvariantRHS) { |
| 6855 | |
| 6856 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 6857 | if (!isLoopInvariant(RHS, L)) { |
| 6858 | if (!isLoopInvariant(LHS, L)) |
| 6859 | return false; |
| 6860 | |
| 6861 | std::swap(LHS, RHS); |
| 6862 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 6863 | } |
| 6864 | |
| 6865 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 6866 | if (!ArLHS || ArLHS->getLoop() != L) |
| 6867 | return false; |
| 6868 | |
| 6869 | bool Increasing; |
| 6870 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 6871 | return false; |
| 6872 | |
| 6873 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 6874 | // true as the loop iterates, and the backedge is control dependent on |
| 6875 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 6876 | // |
| 6877 | // * if the predicate was false in the first iteration then the predicate |
| 6878 | // is never evaluated again, since the loop exits without taking the |
| 6879 | // backedge. |
| 6880 | // * if the predicate was true in the first iteration then it will |
| 6881 | // continue to be true for all future iterations since it is |
| 6882 | // monotonically increasing. |
| 6883 | // |
| 6884 | // For both the above possibilities, we can replace the loop varying |
| 6885 | // predicate with its value on the first iteration of the loop (which is |
| 6886 | // loop invariant). |
| 6887 | // |
| 6888 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 6889 | // replacing true with false and false with true in the above two bullets. |
| 6890 | |
| 6891 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 6892 | |
| 6893 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 6894 | return false; |
| 6895 | |
| 6896 | InvariantPred = Pred; |
| 6897 | InvariantLHS = ArLHS->getStart(); |
| 6898 | InvariantRHS = RHS; |
| 6899 | return true; |
| 6900 | } |
| 6901 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 6902 | bool |
| 6903 | ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred, |
| 6904 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6905 | if (HasSameValue(LHS, RHS)) |
| 6906 | return ICmpInst::isTrueWhenEqual(Pred); |
| 6907 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 6908 | // This code is split out from isKnownPredicate because it is called from |
| 6909 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6910 | switch (Pred) { |
| 6911 | default: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 6912 | llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6913 | case ICmpInst::ICMP_SGT: |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6914 | std::swap(LHS, RHS); |
| 6915 | case ICmpInst::ICMP_SLT: { |
| 6916 | ConstantRange LHSRange = getSignedRange(LHS); |
| 6917 | ConstantRange RHSRange = getSignedRange(RHS); |
| 6918 | if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin())) |
| 6919 | return true; |
| 6920 | if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax())) |
| 6921 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6922 | break; |
| 6923 | } |
| 6924 | case ICmpInst::ICMP_SGE: |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6925 | std::swap(LHS, RHS); |
| 6926 | case ICmpInst::ICMP_SLE: { |
| 6927 | ConstantRange LHSRange = getSignedRange(LHS); |
| 6928 | ConstantRange RHSRange = getSignedRange(RHS); |
| 6929 | if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin())) |
| 6930 | return true; |
| 6931 | if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax())) |
| 6932 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6933 | break; |
| 6934 | } |
| 6935 | case ICmpInst::ICMP_UGT: |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6936 | std::swap(LHS, RHS); |
| 6937 | case ICmpInst::ICMP_ULT: { |
| 6938 | ConstantRange LHSRange = getUnsignedRange(LHS); |
| 6939 | ConstantRange RHSRange = getUnsignedRange(RHS); |
| 6940 | if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin())) |
| 6941 | return true; |
| 6942 | if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax())) |
| 6943 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6944 | break; |
| 6945 | } |
| 6946 | case ICmpInst::ICMP_UGE: |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6947 | std::swap(LHS, RHS); |
| 6948 | case ICmpInst::ICMP_ULE: { |
| 6949 | ConstantRange LHSRange = getUnsignedRange(LHS); |
| 6950 | ConstantRange RHSRange = getUnsignedRange(RHS); |
| 6951 | if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin())) |
| 6952 | return true; |
| 6953 | if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax())) |
| 6954 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6955 | break; |
| 6956 | } |
| 6957 | case ICmpInst::ICMP_NE: { |
| 6958 | if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet()) |
| 6959 | return true; |
| 6960 | if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet()) |
| 6961 | return true; |
| 6962 | |
| 6963 | const SCEV *Diff = getMinusSCEV(LHS, RHS); |
| 6964 | if (isKnownNonZero(Diff)) |
| 6965 | return true; |
| 6966 | break; |
| 6967 | } |
| 6968 | case ICmpInst::ICMP_EQ: |
Dan Gohman | 3439262 | 2009-07-20 23:54:43 +0000 | [diff] [blame] | 6969 | // The check at the top of the function catches the case where |
| 6970 | // the values are known to be equal. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6971 | break; |
| 6972 | } |
| 6973 | return false; |
| 6974 | } |
| 6975 | |
| 6976 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 6977 | /// protected by a conditional between LHS and RHS. This is used to |
| 6978 | /// to eliminate casts. |
| 6979 | bool |
| 6980 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 6981 | ICmpInst::Predicate Pred, |
| 6982 | const SCEV *LHS, const SCEV *RHS) { |
| 6983 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 6984 | // (interprocedural conditions notwithstanding). |
| 6985 | if (!L) return true; |
| 6986 | |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 6987 | if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true; |
| 6988 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 6989 | BasicBlock *Latch = L->getLoopLatch(); |
| 6990 | if (!Latch) |
| 6991 | return false; |
| 6992 | |
| 6993 | BranchInst *LoopContinuePredicate = |
| 6994 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 6995 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 6996 | isImpliedCond(Pred, LHS, RHS, |
| 6997 | LoopContinuePredicate->getCondition(), |
| 6998 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 6999 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7000 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7001 | struct ClearWalkingBEDominatingCondsOnExit { |
| 7002 | ScalarEvolution &SE; |
| 7003 | |
| 7004 | explicit ClearWalkingBEDominatingCondsOnExit(ScalarEvolution &SE) |
Hans Wennborg | 13958b7 | 2015-07-22 20:46:11 +0000 | [diff] [blame] | 7005 | : SE(SE){} |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7006 | |
| 7007 | ~ClearWalkingBEDominatingCondsOnExit() { |
| 7008 | SE.WalkingBEDominatingConds = false; |
| 7009 | } |
| 7010 | }; |
| 7011 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7012 | // We don't want more than one activation of the following loops on the stack |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7013 | // -- that can lead to O(n!) time complexity. |
| 7014 | if (WalkingBEDominatingConds) |
| 7015 | return false; |
| 7016 | |
| 7017 | WalkingBEDominatingConds = true; |
| 7018 | ClearWalkingBEDominatingCondsOnExit ClearOnExit(*this); |
| 7019 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7020 | // Check conditions due to any @llvm.assume intrinsics. |
| 7021 | for (auto &AssumeVH : AC.assumptions()) { |
| 7022 | if (!AssumeVH) |
| 7023 | continue; |
| 7024 | auto *CI = cast<CallInst>(AssumeVH); |
| 7025 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7026 | continue; |
| 7027 | |
| 7028 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7029 | return true; |
| 7030 | } |
| 7031 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7032 | // If the loop is not reachable from the entry block, we risk running into an |
| 7033 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7034 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7035 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7036 | return false; |
| 7037 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7038 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7039 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7040 | |
| 7041 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7042 | |
| 7043 | BasicBlock *BB = DTN->getBlock(); |
| 7044 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7045 | if (!PBB) |
| 7046 | continue; |
| 7047 | |
| 7048 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7049 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7050 | continue; |
| 7051 | |
| 7052 | Value *Condition = ContinuePredicate->getCondition(); |
| 7053 | |
| 7054 | // If we have an edge `E` within the loop body that dominates the only |
| 7055 | // latch, the condition guarding `E` also guards the backedge. This |
| 7056 | // reasoning works only for loops with a single latch. |
| 7057 | |
| 7058 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 7059 | if (DominatingEdge.isSingleEdge()) { |
| 7060 | // We're constructively (and conservatively) enumerating edges within the |
| 7061 | // loop body that dominate the latch. The dominator tree better agree |
| 7062 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7063 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7064 | |
| 7065 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 7066 | BB != ContinuePredicate->getSuccessor(0))) |
| 7067 | return true; |
| 7068 | } |
| 7069 | } |
| 7070 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7071 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7072 | } |
| 7073 | |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7074 | /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7075 | /// by a conditional between LHS and RHS. This is used to help avoid max |
| 7076 | /// expressions in loop trip counts, and to eliminate casts. |
| 7077 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7078 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 7079 | ICmpInst::Predicate Pred, |
| 7080 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 7081 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7082 | // (interprocedural conditions notwithstanding). |
| 7083 | if (!L) return false; |
| 7084 | |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7085 | if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true; |
| 7086 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 7087 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 7088 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7089 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7090 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 7091 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7092 | Pair.first; |
| 7093 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7094 | |
| 7095 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7096 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7097 | if (!LoopEntryPredicate || |
| 7098 | LoopEntryPredicate->isUnconditional()) |
| 7099 | continue; |
| 7100 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7101 | if (isImpliedCond(Pred, LHS, RHS, |
| 7102 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7103 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7104 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7105 | } |
| 7106 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7107 | // Check conditions due to any @llvm.assume intrinsics. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7108 | for (auto &AssumeVH : AC.assumptions()) { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 7109 | if (!AssumeVH) |
| 7110 | continue; |
| 7111 | auto *CI = cast<CallInst>(AssumeVH); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7112 | if (!DT.dominates(CI, L->getHeader())) |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7113 | continue; |
| 7114 | |
| 7115 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7116 | return true; |
| 7117 | } |
| 7118 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7119 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7120 | } |
| 7121 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7122 | /// RAII wrapper to prevent recursive application of isImpliedCond. |
| 7123 | /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are |
| 7124 | /// currently evaluating isImpliedCond. |
| 7125 | struct MarkPendingLoopPredicate { |
| 7126 | Value *Cond; |
| 7127 | DenseSet<Value*> &LoopPreds; |
| 7128 | bool Pending; |
| 7129 | |
| 7130 | MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) |
| 7131 | : Cond(C), LoopPreds(LP) { |
| 7132 | Pending = !LoopPreds.insert(Cond).second; |
| 7133 | } |
| 7134 | ~MarkPendingLoopPredicate() { |
| 7135 | if (!Pending) |
| 7136 | LoopPreds.erase(Cond); |
| 7137 | } |
| 7138 | }; |
| 7139 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7140 | /// isImpliedCond - Test whether the condition described by Pred, LHS, |
| 7141 | /// and RHS is true whenever the given Cond value evaluates to true. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7142 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7143 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7144 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7145 | bool Inverse) { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7146 | MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); |
| 7147 | if (Mark.Pending) |
| 7148 | return false; |
| 7149 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 7150 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7151 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7152 | if (BO->getOpcode() == Instruction::And) { |
| 7153 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7154 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 7155 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7156 | } else if (BO->getOpcode() == Instruction::Or) { |
| 7157 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7158 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 7159 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7160 | } |
| 7161 | } |
| 7162 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7163 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7164 | if (!ICI) return false; |
| 7165 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 7166 | // Now that we found a conditional branch that dominates the loop or controls |
| 7167 | // the loop latch. Check to see if it is the comparison we are looking for. |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7168 | ICmpInst::Predicate FoundPred; |
| 7169 | if (Inverse) |
| 7170 | FoundPred = ICI->getInversePredicate(); |
| 7171 | else |
| 7172 | FoundPred = ICI->getPredicate(); |
| 7173 | |
| 7174 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 7175 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7176 | |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 7177 | // Balance the types. |
| 7178 | if (getTypeSizeInBits(LHS->getType()) < |
| 7179 | getTypeSizeInBits(FoundLHS->getType())) { |
| 7180 | if (CmpInst::isSigned(Pred)) { |
| 7181 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 7182 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 7183 | } else { |
| 7184 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 7185 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 7186 | } |
| 7187 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7188 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 7189 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7190 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 7191 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 7192 | } else { |
| 7193 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 7194 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 7195 | } |
| 7196 | } |
| 7197 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7198 | // Canonicalize the query to match the way instcombine will have |
| 7199 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 7200 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 7201 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 7202 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 7203 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 7204 | if (FoundLHS == FoundRHS) |
| 7205 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7206 | |
| 7207 | // Check to see if we can make the LHS or RHS match. |
| 7208 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 7209 | if (isa<SCEVConstant>(RHS)) { |
| 7210 | std::swap(FoundLHS, FoundRHS); |
| 7211 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 7212 | } else { |
| 7213 | std::swap(LHS, RHS); |
| 7214 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7215 | } |
| 7216 | } |
| 7217 | |
| 7218 | // Check whether the found predicate is the same as the desired predicate. |
| 7219 | if (FoundPred == Pred) |
| 7220 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 7221 | |
| 7222 | // Check whether swapping the found predicate makes it the same as the |
| 7223 | // desired predicate. |
| 7224 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 7225 | if (isa<SCEVConstant>(RHS)) |
| 7226 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 7227 | else |
| 7228 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 7229 | RHS, LHS, FoundLHS, FoundRHS); |
| 7230 | } |
| 7231 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 7232 | // Check if we can make progress by sharpening ranges. |
| 7233 | if (FoundPred == ICmpInst::ICMP_NE && |
| 7234 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 7235 | |
| 7236 | const SCEVConstant *C = nullptr; |
| 7237 | const SCEV *V = nullptr; |
| 7238 | |
| 7239 | if (isa<SCEVConstant>(FoundLHS)) { |
| 7240 | C = cast<SCEVConstant>(FoundLHS); |
| 7241 | V = FoundRHS; |
| 7242 | } else { |
| 7243 | C = cast<SCEVConstant>(FoundRHS); |
| 7244 | V = FoundLHS; |
| 7245 | } |
| 7246 | |
| 7247 | // The guarding predicate tells us that C != V. If the known range |
| 7248 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 7249 | // range we consider has to correspond to same signedness as the |
| 7250 | // predicate we're interested in folding. |
| 7251 | |
| 7252 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 7253 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 7254 | |
| 7255 | if (Min == C->getValue()->getValue()) { |
| 7256 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 7257 | // This is true even if (Min + 1) wraps around -- in case of |
| 7258 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 7259 | |
| 7260 | APInt SharperMin = Min + 1; |
| 7261 | |
| 7262 | switch (Pred) { |
| 7263 | case ICmpInst::ICMP_SGE: |
| 7264 | case ICmpInst::ICMP_UGE: |
| 7265 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 7266 | // RHS, we're done. |
| 7267 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 7268 | getConstant(SharperMin))) |
| 7269 | return true; |
| 7270 | |
| 7271 | case ICmpInst::ICMP_SGT: |
| 7272 | case ICmpInst::ICMP_UGT: |
| 7273 | // We know from the range information that (V `Pred` Min || |
| 7274 | // V == Min). We know from the guarding condition that !(V |
| 7275 | // == Min). This gives us |
| 7276 | // |
| 7277 | // V `Pred` Min || V == Min && !(V == Min) |
| 7278 | // => V `Pred` Min |
| 7279 | // |
| 7280 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 7281 | |
| 7282 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 7283 | return true; |
| 7284 | |
| 7285 | default: |
| 7286 | // No change |
| 7287 | break; |
| 7288 | } |
| 7289 | } |
| 7290 | } |
| 7291 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7292 | // Check whether the actual condition is beyond sufficient. |
| 7293 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 7294 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7295 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7296 | return true; |
| 7297 | if (Pred == ICmpInst::ICMP_NE) |
| 7298 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 7299 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7300 | return true; |
| 7301 | |
| 7302 | // Otherwise assume the worst. |
| 7303 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7304 | } |
| 7305 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7306 | /// isImpliedCondOperands - Test whether the condition described by Pred, |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 7307 | /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7308 | /// and FoundRHS is true. |
| 7309 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 7310 | const SCEV *LHS, const SCEV *RHS, |
| 7311 | const SCEV *FoundLHS, |
| 7312 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 7313 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7314 | return true; |
| 7315 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7316 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 7317 | FoundLHS, FoundRHS) || |
| 7318 | // ~x < ~y --> x > y |
| 7319 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 7320 | getNotSCEV(FoundRHS), |
| 7321 | getNotSCEV(FoundLHS)); |
| 7322 | } |
| 7323 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7324 | |
| 7325 | /// If Expr computes ~A, return A else return nullptr |
| 7326 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 7327 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
| 7328 | if (!Add || Add->getNumOperands() != 2) return nullptr; |
| 7329 | |
| 7330 | const SCEVConstant *AddLHS = dyn_cast<SCEVConstant>(Add->getOperand(0)); |
| 7331 | if (!(AddLHS && AddLHS->getValue()->getValue().isAllOnesValue())) |
| 7332 | return nullptr; |
| 7333 | |
| 7334 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
| 7335 | if (!AddRHS || AddRHS->getNumOperands() != 2) return nullptr; |
| 7336 | |
| 7337 | const SCEVConstant *MulLHS = dyn_cast<SCEVConstant>(AddRHS->getOperand(0)); |
| 7338 | if (!(MulLHS && MulLHS->getValue()->getValue().isAllOnesValue())) |
| 7339 | return nullptr; |
| 7340 | |
| 7341 | return AddRHS->getOperand(1); |
| 7342 | } |
| 7343 | |
| 7344 | |
| 7345 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 7346 | template<typename MaxExprType> |
| 7347 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 7348 | const SCEV *Candidate) { |
| 7349 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 7350 | if (!MaxExpr) return false; |
| 7351 | |
| 7352 | auto It = std::find(MaxExpr->op_begin(), MaxExpr->op_end(), Candidate); |
| 7353 | return It != MaxExpr->op_end(); |
| 7354 | } |
| 7355 | |
| 7356 | |
| 7357 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 7358 | template<typename MaxExprType> |
| 7359 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 7360 | const SCEV *MaybeMinExpr, |
| 7361 | const SCEV *Candidate) { |
| 7362 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 7363 | if (!MaybeMaxExpr) |
| 7364 | return false; |
| 7365 | |
| 7366 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 7367 | } |
| 7368 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 7369 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 7370 | ICmpInst::Predicate Pred, |
| 7371 | const SCEV *LHS, const SCEV *RHS) { |
| 7372 | |
| 7373 | // If both sides are affine addrecs for the same loop, with equal |
| 7374 | // steps, and we know the recurrences don't wrap, then we only |
| 7375 | // need to check the predicate on the starting values. |
| 7376 | |
| 7377 | if (!ICmpInst::isRelational(Pred)) |
| 7378 | return false; |
| 7379 | |
| 7380 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7381 | if (!LAR) |
| 7382 | return false; |
| 7383 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7384 | if (!RAR) |
| 7385 | return false; |
| 7386 | if (LAR->getLoop() != RAR->getLoop()) |
| 7387 | return false; |
| 7388 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 7389 | return false; |
| 7390 | |
| 7391 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 7392 | return false; |
| 7393 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 7394 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 7395 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 7396 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 7397 | return false; |
| 7398 | |
| 7399 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 7400 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7401 | |
| 7402 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 7403 | /// expression? |
| 7404 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 7405 | ICmpInst::Predicate Pred, |
| 7406 | const SCEV *LHS, const SCEV *RHS) { |
| 7407 | switch (Pred) { |
| 7408 | default: |
| 7409 | return false; |
| 7410 | |
| 7411 | case ICmpInst::ICMP_SGE: |
| 7412 | std::swap(LHS, RHS); |
| 7413 | // fall through |
| 7414 | case ICmpInst::ICMP_SLE: |
| 7415 | return |
| 7416 | // min(A, ...) <= A |
| 7417 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 7418 | // A <= max(A, ...) |
| 7419 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 7420 | |
| 7421 | case ICmpInst::ICMP_UGE: |
| 7422 | std::swap(LHS, RHS); |
| 7423 | // fall through |
| 7424 | case ICmpInst::ICMP_ULE: |
| 7425 | return |
| 7426 | // min(A, ...) <= A |
| 7427 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 7428 | // A <= max(A, ...) |
| 7429 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 7430 | } |
| 7431 | |
| 7432 | llvm_unreachable("covered switch fell through?!"); |
| 7433 | } |
| 7434 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7435 | /// isImpliedCondOperandsHelper - Test whether the condition described by |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 7436 | /// Pred, LHS, and RHS is true whenever the condition described by Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7437 | /// FoundLHS, and FoundRHS is true. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7438 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7439 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 7440 | const SCEV *LHS, const SCEV *RHS, |
| 7441 | const SCEV *FoundLHS, |
| 7442 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7443 | auto IsKnownPredicateFull = |
| 7444 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
| 7445 | return isKnownPredicateWithRanges(Pred, LHS, RHS) || |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 7446 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
| 7447 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7448 | }; |
| 7449 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7450 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 7451 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 7452 | case ICmpInst::ICMP_EQ: |
| 7453 | case ICmpInst::ICMP_NE: |
| 7454 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 7455 | return true; |
| 7456 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7457 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 7458 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7459 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 7460 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7461 | return true; |
| 7462 | break; |
| 7463 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 7464 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7465 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 7466 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7467 | return true; |
| 7468 | break; |
| 7469 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 7470 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7471 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 7472 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7473 | return true; |
| 7474 | break; |
| 7475 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 7476 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7477 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 7478 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7479 | return true; |
| 7480 | break; |
| 7481 | } |
| 7482 | |
| 7483 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7484 | } |
| 7485 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 7486 | /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands. |
| 7487 | /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1". |
| 7488 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 7489 | const SCEV *LHS, |
| 7490 | const SCEV *RHS, |
| 7491 | const SCEV *FoundLHS, |
| 7492 | const SCEV *FoundRHS) { |
| 7493 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 7494 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 7495 | // reduce the compile time impact of this optimization. |
| 7496 | return false; |
| 7497 | |
| 7498 | const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS); |
| 7499 | if (!AddLHS || AddLHS->getOperand(1) != FoundLHS || |
| 7500 | !isa<SCEVConstant>(AddLHS->getOperand(0))) |
| 7501 | return false; |
| 7502 | |
| 7503 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getValue()->getValue(); |
| 7504 | |
| 7505 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 7506 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 7507 | ConstantRange FoundLHSRange = |
| 7508 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 7509 | |
| 7510 | // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range |
| 7511 | // for `LHS`: |
| 7512 | APInt Addend = |
| 7513 | cast<SCEVConstant>(AddLHS->getOperand(0))->getValue()->getValue(); |
| 7514 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend)); |
| 7515 | |
| 7516 | // We can also compute the range of values for `LHS` that satisfy the |
| 7517 | // consequent, "`LHS` `Pred` `RHS`": |
| 7518 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getValue()->getValue(); |
| 7519 | ConstantRange SatisfyingLHSRange = |
| 7520 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 7521 | |
| 7522 | // The antecedent implies the consequent if every value of `LHS` that |
| 7523 | // satisfies the antecedent also satisfies the consequent. |
| 7524 | return SatisfyingLHSRange.contains(LHSRange); |
| 7525 | } |
| 7526 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 7527 | // Verify if an linear IV with positive stride can overflow when in a |
| 7528 | // less-than comparison, knowing the invariant term of the comparison, the |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7529 | // stride and the knowledge of NSW/NUW flags on the recurrence. |
| 7530 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 7531 | bool IsSigned, bool NoWrap) { |
| 7532 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 7533 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7534 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 7535 | const SCEV *One = getConstant(Stride->getType(), 1); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 7536 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7537 | if (IsSigned) { |
| 7538 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 7539 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 7540 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 7541 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 7542 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7543 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 7544 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 7545 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 7546 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7547 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 7548 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 7549 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 7550 | .getUnsignedMax(); |
| 7551 | |
| 7552 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 7553 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 7554 | } |
| 7555 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 7556 | // Verify if an linear IV with negative stride can overflow when in a |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7557 | // greater-than comparison, knowing the invariant term of the comparison, |
| 7558 | // the stride and the knowledge of NSW/NUW flags on the recurrence. |
| 7559 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 7560 | bool IsSigned, bool NoWrap) { |
| 7561 | if (NoWrap) return false; |
| 7562 | |
| 7563 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 7564 | const SCEV *One = getConstant(Stride->getType(), 1); |
| 7565 | |
| 7566 | if (IsSigned) { |
| 7567 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 7568 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 7569 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 7570 | .getSignedMax(); |
| 7571 | |
| 7572 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 7573 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 7574 | } |
| 7575 | |
| 7576 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 7577 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 7578 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 7579 | .getUnsignedMax(); |
| 7580 | |
| 7581 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 7582 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 7583 | } |
| 7584 | |
| 7585 | // Compute the backedge taken count knowing the interval difference, the |
| 7586 | // stride and presence of the equality in the comparison. |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 7587 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7588 | bool Equality) { |
| 7589 | const SCEV *One = getConstant(Step->getType(), 1); |
| 7590 | Delta = Equality ? getAddExpr(Delta, Step) |
| 7591 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 7592 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 7593 | } |
| 7594 | |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 7595 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 7596 | /// specified less-than comparison will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 7597 | /// CouldNotCompute. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 7598 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7599 | /// @param ControlsExit is true when the LHS < RHS condition directly controls |
| 7600 | /// the branch (loops exits only if condition is true). In this case, we can use |
| 7601 | /// NoWrapFlags to skip overflow checks. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7602 | ScalarEvolution::ExitLimit |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7603 | ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7604 | const Loop *L, bool IsSigned, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7605 | bool ControlsExit) { |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7606 | // We handle only IV < Invariant |
| 7607 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7608 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 7609 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7610 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 7611 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7612 | // Avoid weird loops |
| 7613 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 7614 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 7615 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7616 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7617 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 7618 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7619 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 7620 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7621 | // Avoid negative or zero stride values |
| 7622 | if (!isKnownPositive(Stride)) |
| 7623 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 7624 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7625 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 7626 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 7627 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7628 | // behaviors like the case of C language. |
| 7629 | if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 7630 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 7631 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7632 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 7633 | : ICmpInst::ICMP_ULT; |
| 7634 | const SCEV *Start = IV->getStart(); |
| 7635 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 7636 | if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) { |
| 7637 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 7638 | // If we have NoWrap set, then we can assume that the increment won't |
| 7639 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 7640 | // do a max operation since we can just figure it out statically |
| 7641 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
| 7642 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue(); |
| 7643 | if (D.isNegative()) |
| 7644 | End = Start; |
| 7645 | } else |
| 7646 | End = IsSigned ? getSMaxExpr(RHS, Start) |
| 7647 | : getUMaxExpr(RHS, Start); |
| 7648 | } |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 7649 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7650 | const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 7651 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7652 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 7653 | : getUnsignedRange(Start).getUnsignedMin(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 7654 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7655 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 7656 | : getUnsignedRange(Stride).getUnsignedMin(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 7657 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7658 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 7659 | APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1) |
| 7660 | : APInt::getMaxValue(BitWidth) - (MinStride - 1); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 7661 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7662 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 7663 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 7664 | // is zero, leading to a zero maximum backedge taken count. |
| 7665 | APInt MaxEnd = |
| 7666 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 7667 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 7668 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 7669 | const SCEV *MaxBECount; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7670 | if (isa<SCEVConstant>(BECount)) |
| 7671 | MaxBECount = BECount; |
| 7672 | else |
| 7673 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
| 7674 | getConstant(MinStride), false); |
| 7675 | |
| 7676 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 7677 | MaxBECount = BECount; |
| 7678 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7679 | return ExitLimit(BECount, MaxBECount); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7680 | } |
| 7681 | |
| 7682 | ScalarEvolution::ExitLimit |
| 7683 | ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
| 7684 | const Loop *L, bool IsSigned, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7685 | bool ControlsExit) { |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7686 | // We handle only IV > Invariant |
| 7687 | if (!isLoopInvariant(RHS, L)) |
| 7688 | return getCouldNotCompute(); |
| 7689 | |
| 7690 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7691 | |
| 7692 | // Avoid weird loops |
| 7693 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 7694 | return getCouldNotCompute(); |
| 7695 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7696 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7697 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 7698 | |
| 7699 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 7700 | |
| 7701 | // Avoid negative or zero stride values |
| 7702 | if (!isKnownPositive(Stride)) |
| 7703 | return getCouldNotCompute(); |
| 7704 | |
| 7705 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 7706 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 7707 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7708 | // behaviors like the case of C language. |
| 7709 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 7710 | return getCouldNotCompute(); |
| 7711 | |
| 7712 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 7713 | : ICmpInst::ICMP_UGT; |
| 7714 | |
| 7715 | const SCEV *Start = IV->getStart(); |
| 7716 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 7717 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { |
| 7718 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 7719 | // If we have NoWrap set, then we can assume that the increment won't |
| 7720 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 7721 | // do a max operation since we can just figure it out statically |
| 7722 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
| 7723 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue(); |
| 7724 | if (!D.isNegative()) |
| 7725 | End = Start; |
| 7726 | } else |
| 7727 | End = IsSigned ? getSMinExpr(RHS, Start) |
| 7728 | : getUMinExpr(RHS, Start); |
| 7729 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7730 | |
| 7731 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 7732 | |
| 7733 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 7734 | : getUnsignedRange(Start).getUnsignedMax(); |
| 7735 | |
| 7736 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 7737 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 7738 | |
| 7739 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 7740 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 7741 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 7742 | |
| 7743 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 7744 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 7745 | // is zero, leading to a zero maximum backedge taken count. |
| 7746 | APInt MinEnd = |
| 7747 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 7748 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 7749 | |
| 7750 | |
| 7751 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 7752 | if (isa<SCEVConstant>(BECount)) |
| 7753 | MaxBECount = BECount; |
| 7754 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 7755 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 7756 | getConstant(MinStride), false); |
| 7757 | |
| 7758 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 7759 | MaxBECount = BECount; |
| 7760 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7761 | return ExitLimit(BECount, MaxBECount); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 7762 | } |
| 7763 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7764 | /// getNumIterationsInRange - Return the number of iterations of this loop that |
| 7765 | /// produce values in the specified constant range. Another way of looking at |
| 7766 | /// this is that it returns the first iteration number where the value is not in |
| 7767 | /// the condition, thus computing the exit count. If the iteration count can't |
| 7768 | /// be computed, an instance of SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7769 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7770 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7771 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7772 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7773 | |
| 7774 | // If the start is a non-zero constant, shift the range to simplify things. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7775 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 7776 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7777 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 7778 | Operands[0] = SE.getConstant(SC->getType(), 0); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7779 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 7780 | getNoWrapFlags(FlagNW)); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7781 | if (const SCEVAddRecExpr *ShiftedAddRec = |
| 7782 | dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7783 | return ShiftedAddRec->getNumIterationsInRange( |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7784 | Range.subtract(SC->getValue()->getValue()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7785 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7786 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7787 | } |
| 7788 | |
| 7789 | // The only time we can solve this is when we have all constant indices. |
| 7790 | // Otherwise, we cannot determine the overflow conditions. |
| 7791 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
| 7792 | if (!isa<SCEVConstant>(getOperand(i))) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7793 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7794 | |
| 7795 | |
| 7796 | // Okay at this point we know that all elements of the chrec are constants and |
| 7797 | // that the start element is zero. |
| 7798 | |
| 7799 | // First check to see if the range contains zero. If not, the first |
| 7800 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 7801 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 7802 | if (!Range.contains(APInt(BitWidth, 0))) |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 7803 | return SE.getConstant(getType(), 0); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7804 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7805 | if (isAffine()) { |
| 7806 | // If this is an affine expression then we have this situation: |
| 7807 | // Solve {0,+,A} in Range === Ax in Range |
| 7808 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 7809 | // We know that zero is in the range. If A is positive then we know that |
| 7810 | // the upper value of the range must be the first possible exit value. |
| 7811 | // If A is negative then the lower of the range is the last possible loop |
| 7812 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 7813 | APInt One(BitWidth,1); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 7814 | APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); |
| 7815 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7816 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 7817 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 7818 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7819 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7820 | |
| 7821 | // Evaluate at the exit value. If we really did fall out of the valid |
| 7822 | // range, then we computed our trip count, otherwise wrap around or other |
| 7823 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7824 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 7825 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7826 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7827 | |
| 7828 | // Ensure that the previous value is in the range. This is a sanity check. |
Reid Spencer | 3a7e9d8 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 7829 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7830 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7831 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7832 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7833 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7834 | } else if (isQuadratic()) { |
| 7835 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 7836 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 7837 | // terms of figuring out when zero is crossed, instead of when |
| 7838 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7839 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7840 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7841 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), |
| 7842 | // getNoWrapFlags(FlagNW) |
| 7843 | FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7844 | |
| 7845 | // Next, solve the constructed addrec |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7846 | std::pair<const SCEV *,const SCEV *> Roots = |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7847 | SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7848 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 7849 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7850 | if (R1) { |
| 7851 | // Pick the smallest positive root value. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 7852 | if (ConstantInt *CB = |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 7853 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7854 | R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 7855 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7856 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7857 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7858 | // Make sure the root is not off by one. The returned iteration should |
| 7859 | // not be in the range, but the previous one should be. When solving |
| 7860 | // for "X*X < 5", for example, we should not return a root of 2. |
| 7861 | ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7862 | R1->getValue(), |
| 7863 | SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 7864 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7865 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7866 | ConstantInt *NextVal = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7867 | ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7868 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7869 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 7870 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7871 | return SE.getConstant(NextVal); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7872 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7873 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7874 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7875 | // If R1 was not in the range, then it is a good return value. Make |
| 7876 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7877 | ConstantInt *NextVal = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7878 | ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7879 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 7880 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7881 | return R1; |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7882 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7883 | } |
| 7884 | } |
| 7885 | } |
| 7886 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7887 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7888 | } |
| 7889 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7890 | namespace { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 7891 | struct FindUndefs { |
| 7892 | bool Found; |
| 7893 | FindUndefs() : Found(false) {} |
| 7894 | |
| 7895 | bool follow(const SCEV *S) { |
| 7896 | if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { |
| 7897 | if (isa<UndefValue>(C->getValue())) |
| 7898 | Found = true; |
| 7899 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
| 7900 | if (isa<UndefValue>(C->getValue())) |
| 7901 | Found = true; |
| 7902 | } |
| 7903 | |
| 7904 | // Keep looking if we haven't found it yet. |
| 7905 | return !Found; |
| 7906 | } |
| 7907 | bool isDone() const { |
| 7908 | // Stop recursion if we have found an undef. |
| 7909 | return Found; |
| 7910 | } |
| 7911 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 7912 | } |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 7913 | |
| 7914 | // Return true when S contains at least an undef value. |
| 7915 | static inline bool |
| 7916 | containsUndefs(const SCEV *S) { |
| 7917 | FindUndefs F; |
| 7918 | SCEVTraversal<FindUndefs> ST(F); |
| 7919 | ST.visitAll(S); |
| 7920 | |
| 7921 | return F.Found; |
| 7922 | } |
| 7923 | |
| 7924 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7925 | // Collect all steps of SCEV expressions. |
| 7926 | struct SCEVCollectStrides { |
| 7927 | ScalarEvolution &SE; |
| 7928 | SmallVectorImpl<const SCEV *> &Strides; |
| 7929 | |
| 7930 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 7931 | : SE(SE), Strides(S) {} |
| 7932 | |
| 7933 | bool follow(const SCEV *S) { |
| 7934 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 7935 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 7936 | return true; |
| 7937 | } |
| 7938 | bool isDone() const { return false; } |
| 7939 | }; |
| 7940 | |
| 7941 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 7942 | struct SCEVCollectTerms { |
| 7943 | SmallVectorImpl<const SCEV *> &Terms; |
| 7944 | |
| 7945 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 7946 | : Terms(T) {} |
| 7947 | |
| 7948 | bool follow(const SCEV *S) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 7949 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 7950 | if (!containsUndefs(S)) |
| 7951 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7952 | |
| 7953 | // Stop recursion: once we collected a term, do not walk its operands. |
| 7954 | return false; |
| 7955 | } |
| 7956 | |
| 7957 | // Keep looking. |
| 7958 | return true; |
| 7959 | } |
| 7960 | bool isDone() const { return false; } |
| 7961 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 7962 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7963 | |
| 7964 | /// Find parametric terms in this SCEVAddRecExpr. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 7965 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 7966 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7967 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 7968 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 7969 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7970 | |
| 7971 | DEBUG({ |
| 7972 | dbgs() << "Strides:\n"; |
| 7973 | for (const SCEV *S : Strides) |
| 7974 | dbgs() << *S << "\n"; |
| 7975 | }); |
| 7976 | |
| 7977 | for (const SCEV *S : Strides) { |
| 7978 | SCEVCollectTerms TermCollector(Terms); |
| 7979 | visitAll(S, TermCollector); |
| 7980 | } |
| 7981 | |
| 7982 | DEBUG({ |
| 7983 | dbgs() << "Terms:\n"; |
| 7984 | for (const SCEV *T : Terms) |
| 7985 | dbgs() << *T << "\n"; |
| 7986 | }); |
| 7987 | } |
| 7988 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 7989 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7990 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 7991 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 7992 | int Last = Terms.size() - 1; |
| 7993 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 7994 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7995 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 7996 | if (Last == 0) { |
| 7997 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 7998 | SmallVector<const SCEV *, 2> Qs; |
| 7999 | for (const SCEV *Op : M->operands()) |
| 8000 | if (!isa<SCEVConstant>(Op)) |
| 8001 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8002 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8003 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8004 | } |
| 8005 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8006 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8007 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8008 | } |
| 8009 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 8010 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8011 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 8012 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 8013 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8014 | |
| 8015 | // Bail out when GCD does not evenly divide one of the terms. |
| 8016 | if (!R->isZero()) |
| 8017 | return false; |
| 8018 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 8019 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8020 | } |
| 8021 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 8022 | // Remove all SCEVConstants. |
Tobias Grosser | 1e9db7e | 2014-05-08 21:43:19 +0000 | [diff] [blame] | 8023 | Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) { |
| 8024 | return isa<SCEVConstant>(E); |
| 8025 | }), |
| 8026 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8027 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8028 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8029 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 8030 | return false; |
| 8031 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8032 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8033 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8034 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8035 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8036 | namespace { |
| 8037 | struct FindParameter { |
| 8038 | bool FoundParameter; |
| 8039 | FindParameter() : FoundParameter(false) {} |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8040 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8041 | bool follow(const SCEV *S) { |
| 8042 | if (isa<SCEVUnknown>(S)) { |
| 8043 | FoundParameter = true; |
| 8044 | // Stop recursion: we found a parameter. |
| 8045 | return false; |
| 8046 | } |
| 8047 | // Keep looking. |
| 8048 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8049 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8050 | bool isDone() const { |
| 8051 | // Stop recursion if we have found a parameter. |
| 8052 | return FoundParameter; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8053 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8054 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8055 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8056 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8057 | // Returns true when S contains at least a SCEVUnknown parameter. |
| 8058 | static inline bool |
| 8059 | containsParameters(const SCEV *S) { |
| 8060 | FindParameter F; |
| 8061 | SCEVTraversal<FindParameter> ST(F); |
| 8062 | ST.visitAll(S); |
| 8063 | |
| 8064 | return F.FoundParameter; |
| 8065 | } |
| 8066 | |
| 8067 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
| 8068 | static inline bool |
| 8069 | containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
| 8070 | for (const SCEV *T : Terms) |
| 8071 | if (containsParameters(T)) |
| 8072 | return true; |
| 8073 | return false; |
| 8074 | } |
| 8075 | |
| 8076 | // Return the number of product terms in S. |
| 8077 | static inline int numberOfTerms(const SCEV *S) { |
| 8078 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 8079 | return Expr->getNumOperands(); |
| 8080 | return 1; |
| 8081 | } |
| 8082 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8083 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 8084 | if (isa<SCEVConstant>(T)) |
| 8085 | return nullptr; |
| 8086 | |
| 8087 | if (isa<SCEVUnknown>(T)) |
| 8088 | return T; |
| 8089 | |
| 8090 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 8091 | SmallVector<const SCEV *, 2> Factors; |
| 8092 | for (const SCEV *Op : M->operands()) |
| 8093 | if (!isa<SCEVConstant>(Op)) |
| 8094 | Factors.push_back(Op); |
| 8095 | |
| 8096 | return SE.getMulExpr(Factors); |
| 8097 | } |
| 8098 | |
| 8099 | return T; |
| 8100 | } |
| 8101 | |
| 8102 | /// Return the size of an element read or written by Inst. |
| 8103 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 8104 | Type *Ty; |
| 8105 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 8106 | Ty = Store->getValueOperand()->getType(); |
| 8107 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 8108 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8109 | else |
| 8110 | return nullptr; |
| 8111 | |
| 8112 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 8113 | return getSizeOfExpr(ETy, Ty); |
| 8114 | } |
| 8115 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8116 | /// Second step of delinearization: compute the array dimensions Sizes from the |
| 8117 | /// set of Terms extracted from the memory access function of this SCEVAddRec. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8118 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 8119 | SmallVectorImpl<const SCEV *> &Sizes, |
| 8120 | const SCEV *ElementSize) const { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8121 | |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 8122 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8123 | return; |
| 8124 | |
| 8125 | // Early return when Terms do not contain parameters: we do not delinearize |
| 8126 | // non parametric SCEVs. |
| 8127 | if (!containsParameters(Terms)) |
| 8128 | return; |
| 8129 | |
| 8130 | DEBUG({ |
| 8131 | dbgs() << "Terms:\n"; |
| 8132 | for (const SCEV *T : Terms) |
| 8133 | dbgs() << *T << "\n"; |
| 8134 | }); |
| 8135 | |
| 8136 | // Remove duplicates. |
| 8137 | std::sort(Terms.begin(), Terms.end()); |
| 8138 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 8139 | |
| 8140 | // Put larger terms first. |
| 8141 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 8142 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 8143 | }); |
| 8144 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8145 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 8146 | |
| 8147 | // Divide all terms by the element size. |
| 8148 | for (const SCEV *&Term : Terms) { |
| 8149 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 8150 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8151 | Term = Q; |
| 8152 | } |
| 8153 | |
| 8154 | SmallVector<const SCEV *, 4> NewTerms; |
| 8155 | |
| 8156 | // Remove constant factors. |
| 8157 | for (const SCEV *T : Terms) |
| 8158 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 8159 | NewTerms.push_back(NewT); |
| 8160 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8161 | DEBUG({ |
| 8162 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8163 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8164 | dbgs() << *T << "\n"; |
| 8165 | }); |
| 8166 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8167 | if (NewTerms.empty() || |
| 8168 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8169 | Sizes.clear(); |
| 8170 | return; |
| 8171 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8172 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8173 | // The last element to be pushed into Sizes is the size of an element. |
| 8174 | Sizes.push_back(ElementSize); |
| 8175 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8176 | DEBUG({ |
| 8177 | dbgs() << "Sizes:\n"; |
| 8178 | for (const SCEV *S : Sizes) |
| 8179 | dbgs() << *S << "\n"; |
| 8180 | }); |
| 8181 | } |
| 8182 | |
| 8183 | /// Third step of delinearization: compute the access functions for the |
| 8184 | /// Subscripts based on the dimensions in Sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8185 | void ScalarEvolution::computeAccessFunctions( |
| 8186 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 8187 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8188 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8189 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8190 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8191 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8192 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8193 | if (auto AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
| 8194 | if (!AR->isAffine()) |
| 8195 | return; |
| 8196 | |
| 8197 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8198 | int Last = Sizes.size() - 1; |
| 8199 | for (int i = Last; i >= 0; i--) { |
| 8200 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8201 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8202 | |
| 8203 | DEBUG({ |
| 8204 | dbgs() << "Res: " << *Res << "\n"; |
| 8205 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 8206 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 8207 | dbgs() << "Quotient: " << *Q << "\n"; |
| 8208 | dbgs() << "Remainder: " << *R << "\n"; |
| 8209 | }); |
| 8210 | |
| 8211 | Res = Q; |
| 8212 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8213 | // Do not record the last subscript corresponding to the size of elements in |
| 8214 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8215 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8216 | |
| 8217 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8218 | if (isa<SCEVAddRecExpr>(R)) { |
| 8219 | Subscripts.clear(); |
| 8220 | Sizes.clear(); |
| 8221 | return; |
| 8222 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8223 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8224 | continue; |
| 8225 | } |
| 8226 | |
| 8227 | // Record the access function for the current subscript. |
| 8228 | Subscripts.push_back(R); |
| 8229 | } |
| 8230 | |
| 8231 | // Also push in last position the remainder of the last division: it will be |
| 8232 | // the access function of the innermost dimension. |
| 8233 | Subscripts.push_back(Res); |
| 8234 | |
| 8235 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 8236 | |
| 8237 | DEBUG({ |
| 8238 | dbgs() << "Subscripts:\n"; |
| 8239 | for (const SCEV *S : Subscripts) |
| 8240 | dbgs() << *S << "\n"; |
| 8241 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8242 | } |
| 8243 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8244 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 8245 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 8246 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 8247 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 8248 | /// expressions in the stride and base of a SCEV corresponding to the |
| 8249 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 8250 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 8251 | /// |
| 8252 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 8253 | /// |
| 8254 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 8255 | /// |
| 8256 | /// for (long i = 0; i < n; i++) |
| 8257 | /// for (long j = 0; j < m; j++) |
| 8258 | /// for (long k = 0; k < o; k++) |
| 8259 | /// A[i][j][k] = 1.0; |
| 8260 | /// } |
| 8261 | /// |
| 8262 | /// the delinearization input is the following AddRec SCEV: |
| 8263 | /// |
| 8264 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 8265 | /// |
| 8266 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 8267 | /// because it appears as an offset that does not divide any of the strides in |
| 8268 | /// the loops: |
| 8269 | /// |
| 8270 | /// CHECK: Base offset: %A |
| 8271 | /// |
| 8272 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 8273 | /// the array as these are the multiples by which the strides are happening: |
| 8274 | /// |
| 8275 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 8276 | /// |
| 8277 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 8278 | /// no strides that would help identifying the size of the last dimension: when |
| 8279 | /// the array has been statically allocated, one could compute the size of that |
| 8280 | /// dimension by dividing the overall size of the array by the size of the known |
| 8281 | /// dimensions: %m * %o * 8. |
| 8282 | /// |
| 8283 | /// Finally delinearize provides the access functions for the array reference |
| 8284 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 8285 | /// |
| 8286 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 8287 | /// |
| 8288 | /// The testcases are checking the output of a function pass: |
| 8289 | /// DelinearizationPass that walks through all loads and stores of a function |
| 8290 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 8291 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 8292 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8293 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8294 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 8295 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8296 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8297 | // First step: collect parametric terms. |
| 8298 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8299 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8300 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8301 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8302 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8303 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8304 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8305 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 8306 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8307 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8308 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8309 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8310 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8311 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8312 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8313 | if (Subscripts.empty()) |
| 8314 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8315 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8316 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8317 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8318 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 8319 | for (const SCEV *S : Sizes) |
| 8320 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8321 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 8322 | dbgs() << "\nArrayRef"; |
| 8323 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8324 | dbgs() << "[" << *S << "]"; |
| 8325 | dbgs() << "\n"; |
| 8326 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8327 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8328 | |
| 8329 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8330 | // SCEVCallbackVH Class Implementation |
| 8331 | //===----------------------------------------------------------------------===// |
| 8332 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 8333 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 8334 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8335 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 8336 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 8337 | SE->ValueExprMap.erase(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8338 | // this now dangles! |
| 8339 | } |
| 8340 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 8341 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 8342 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 8343 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8344 | // Forget all the expressions associated with users of the old value, |
| 8345 | // so that future queries will recompute the expressions using the new |
| 8346 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 8347 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 8348 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 8349 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8350 | while (!Worklist.empty()) { |
| 8351 | User *U = Worklist.pop_back_val(); |
| 8352 | // Deleting the Old value will cause this to dangle. Postpone |
| 8353 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 8354 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8355 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 8356 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 8357 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8358 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 8359 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 8360 | SE->ValueExprMap.erase(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 8361 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8362 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 8363 | // Delete the Old value. |
| 8364 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 8365 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 8366 | SE->ValueExprMap.erase(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 8367 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8368 | } |
| 8369 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 8370 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8371 | : CallbackVH(V), SE(se) {} |
| 8372 | |
| 8373 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8374 | // ScalarEvolution Class Implementation |
| 8375 | //===----------------------------------------------------------------------===// |
| 8376 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8377 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
| 8378 | AssumptionCache &AC, DominatorTree &DT, |
| 8379 | LoopInfo &LI) |
| 8380 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
| 8381 | CouldNotCompute(new SCEVCouldNotCompute()), |
| 8382 | WalkingBEDominatingConds(false), ValuesAtScopes(64), LoopDispositions(64), |
| 8383 | BlockDispositions(64), FirstUnknown(nullptr) {} |
| 8384 | |
| 8385 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
| 8386 | : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), |
| 8387 | CouldNotCompute(std::move(Arg.CouldNotCompute)), |
| 8388 | ValueExprMap(std::move(Arg.ValueExprMap)), |
| 8389 | WalkingBEDominatingConds(false), |
| 8390 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
| 8391 | ConstantEvolutionLoopExitValue( |
| 8392 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 8393 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 8394 | LoopDispositions(std::move(Arg.LoopDispositions)), |
| 8395 | BlockDispositions(std::move(Arg.BlockDispositions)), |
| 8396 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 8397 | SignedRanges(std::move(Arg.SignedRanges)), |
| 8398 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
| 8399 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 8400 | FirstUnknown(Arg.FirstUnknown) { |
| 8401 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 8402 | } |
| 8403 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8404 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 8405 | // Iterate through all the SCEVUnknown instances and call their |
| 8406 | // destructors, so that they release their references to their values. |
| 8407 | for (SCEVUnknown *U = FirstUnknown; U; U = U->Next) |
| 8408 | U->~SCEVUnknown(); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 8409 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 8410 | |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 8411 | ValueExprMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8412 | |
| 8413 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 8414 | // that a loop had multiple computable exits. |
| 8415 | for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = |
| 8416 | BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); |
| 8417 | I != E; ++I) { |
| 8418 | I->second.clear(); |
| 8419 | } |
| 8420 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8421 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 8422 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8423 | } |
| 8424 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 8425 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 8426 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8427 | } |
| 8428 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 8429 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8430 | const Loop *L) { |
| 8431 | // Print all inner loops first |
| 8432 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 8433 | PrintLoopInfo(OS, SE, *I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8434 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8435 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 8436 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8437 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 8438 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 8439 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 8440 | L->getExitBlocks(ExitBlocks); |
| 8441 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 8442 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8443 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 8444 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 8445 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8446 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 8447 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8448 | } |
| 8449 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8450 | OS << "\n" |
| 8451 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 8452 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8453 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 8454 | |
| 8455 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 8456 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
| 8457 | } else { |
| 8458 | OS << "Unpredictable max backedge-taken count. "; |
| 8459 | } |
| 8460 | |
| 8461 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8462 | } |
| 8463 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8464 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8465 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 8466 | // out SCEV values of all instructions that are interesting. Doing |
| 8467 | // this potentially causes it to create new SCEV objects though, |
| 8468 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 8469 | // observable from outside the class though, so casting away the |
| 8470 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 8471 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8472 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8473 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8474 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8475 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8476 | for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) |
Dan Gohman | d18dc2c | 2010-05-03 17:03:23 +0000 | [diff] [blame] | 8477 | if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) { |
Dan Gohman | fda3c4a | 2009-07-13 23:03:05 +0000 | [diff] [blame] | 8478 | OS << *I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 8479 | OS << " --> "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8480 | const SCEV *SV = SE.getSCEV(&*I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8481 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 8482 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 8483 | OS << " U: "; |
| 8484 | SE.getUnsignedRange(SV).print(OS); |
| 8485 | OS << " S: "; |
| 8486 | SE.getSignedRange(SV).print(OS); |
| 8487 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8488 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8489 | const Loop *L = LI.getLoopFor((*I).getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 8490 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8491 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 8492 | if (AtUse != SV) { |
| 8493 | OS << " --> "; |
| 8494 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 8495 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 8496 | OS << " U: "; |
| 8497 | SE.getUnsignedRange(AtUse).print(OS); |
| 8498 | OS << " S: "; |
| 8499 | SE.getSignedRange(AtUse).print(OS); |
| 8500 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 8501 | } |
| 8502 | |
| 8503 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 8504 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8505 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8506 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8507 | OS << "<<Unknown>>"; |
| 8508 | } else { |
| 8509 | OS << *ExitValue; |
| 8510 | } |
| 8511 | } |
| 8512 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8513 | OS << "\n"; |
| 8514 | } |
| 8515 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8516 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8517 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 8518 | OS << "\n"; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8519 | for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 8520 | PrintLoopInfo(OS, &SE, *I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8521 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 8522 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8523 | ScalarEvolution::LoopDisposition |
| 8524 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 8525 | auto &Values = LoopDispositions[S]; |
| 8526 | for (auto &V : Values) { |
| 8527 | if (V.getPointer() == L) |
| 8528 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 8529 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 8530 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8531 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 8532 | auto &Values2 = LoopDispositions[S]; |
| 8533 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 8534 | if (V.getPointer() == L) { |
| 8535 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 8536 | break; |
| 8537 | } |
| 8538 | } |
| 8539 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8540 | } |
| 8541 | |
| 8542 | ScalarEvolution::LoopDisposition |
| 8543 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 8544 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8545 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8546 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8547 | case scTruncate: |
| 8548 | case scZeroExtend: |
| 8549 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8550 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8551 | case scAddRecExpr: { |
| 8552 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 8553 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8554 | // If L is the addrec's loop, it's computable. |
| 8555 | if (AR->getLoop() == L) |
| 8556 | return LoopComputable; |
| 8557 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8558 | // Add recurrences are never invariant in the function-body (null loop). |
| 8559 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8560 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8561 | |
| 8562 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 8563 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8564 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8565 | |
| 8566 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 8567 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8568 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8569 | |
| 8570 | // This recurrence is variant w.r.t. L if any of its operands |
| 8571 | // are variant. |
| 8572 | for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end(); |
| 8573 | I != E; ++I) |
| 8574 | if (!isLoopInvariant(*I, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8575 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8576 | |
| 8577 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8578 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8579 | } |
| 8580 | case scAddExpr: |
| 8581 | case scMulExpr: |
| 8582 | case scUMaxExpr: |
| 8583 | case scSMaxExpr: { |
| 8584 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8585 | bool HasVarying = false; |
| 8586 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 8587 | I != E; ++I) { |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8588 | LoopDisposition D = getLoopDisposition(*I, L); |
| 8589 | if (D == LoopVariant) |
| 8590 | return LoopVariant; |
| 8591 | if (D == LoopComputable) |
| 8592 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8593 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8594 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8595 | } |
| 8596 | case scUDivExpr: { |
| 8597 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8598 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 8599 | if (LD == LoopVariant) |
| 8600 | return LoopVariant; |
| 8601 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 8602 | if (RD == LoopVariant) |
| 8603 | return LoopVariant; |
| 8604 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 8605 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8606 | } |
| 8607 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8608 | // All non-instruction values are loop invariant. All instructions are loop |
| 8609 | // invariant if they are not contained in the specified loop. |
| 8610 | // Instructions are never considered invariant in the function body |
| 8611 | // (null loop) because they are defined within the "loop". |
| 8612 | if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
| 8613 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 8614 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8615 | case scCouldNotCompute: |
| 8616 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8617 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 8618 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 8619 | } |
| 8620 | |
| 8621 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 8622 | return getLoopDisposition(S, L) == LoopInvariant; |
| 8623 | } |
| 8624 | |
| 8625 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 8626 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 8627 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8628 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8629 | ScalarEvolution::BlockDisposition |
| 8630 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 8631 | auto &Values = BlockDispositions[S]; |
| 8632 | for (auto &V : Values) { |
| 8633 | if (V.getPointer() == BB) |
| 8634 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 8635 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 8636 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8637 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 8638 | auto &Values2 = BlockDispositions[S]; |
| 8639 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 8640 | if (V.getPointer() == BB) { |
| 8641 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 8642 | break; |
| 8643 | } |
| 8644 | } |
| 8645 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8646 | } |
| 8647 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8648 | ScalarEvolution::BlockDisposition |
| 8649 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 8650 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8651 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8652 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8653 | case scTruncate: |
| 8654 | case scZeroExtend: |
| 8655 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8656 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8657 | case scAddRecExpr: { |
| 8658 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8659 | // to test for proper dominance too, because the instruction which |
| 8660 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 8661 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8662 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8663 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8664 | return DoesNotDominateBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8665 | } |
| 8666 | // FALL THROUGH into SCEVNAryExpr handling. |
| 8667 | case scAddExpr: |
| 8668 | case scMulExpr: |
| 8669 | case scUMaxExpr: |
| 8670 | case scSMaxExpr: { |
| 8671 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8672 | bool Proper = true; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8673 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8674 | I != E; ++I) { |
| 8675 | BlockDisposition D = getBlockDisposition(*I, BB); |
| 8676 | if (D == DoesNotDominateBlock) |
| 8677 | return DoesNotDominateBlock; |
| 8678 | if (D == DominatesBlock) |
| 8679 | Proper = false; |
| 8680 | } |
| 8681 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8682 | } |
| 8683 | case scUDivExpr: { |
| 8684 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8685 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 8686 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 8687 | if (LD == DoesNotDominateBlock) |
| 8688 | return DoesNotDominateBlock; |
| 8689 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 8690 | if (RD == DoesNotDominateBlock) |
| 8691 | return DoesNotDominateBlock; |
| 8692 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 8693 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8694 | } |
| 8695 | case scUnknown: |
| 8696 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8697 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 8698 | if (I->getParent() == BB) |
| 8699 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8700 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8701 | return ProperlyDominatesBlock; |
| 8702 | return DoesNotDominateBlock; |
| 8703 | } |
| 8704 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8705 | case scCouldNotCompute: |
| 8706 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8707 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 8708 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8709 | } |
| 8710 | |
| 8711 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 8712 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 8713 | } |
| 8714 | |
| 8715 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 8716 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 8717 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 8718 | |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 8719 | namespace { |
| 8720 | // Search for a SCEV expression node within an expression tree. |
| 8721 | // Implements SCEVTraversal::Visitor. |
| 8722 | struct SCEVSearch { |
| 8723 | const SCEV *Node; |
| 8724 | bool IsFound; |
| 8725 | |
| 8726 | SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} |
| 8727 | |
| 8728 | bool follow(const SCEV *S) { |
| 8729 | IsFound |= (S == Node); |
| 8730 | return !IsFound; |
| 8731 | } |
| 8732 | bool isDone() const { return IsFound; } |
| 8733 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8734 | } |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 8735 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 8736 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 8737 | SCEVSearch Search(Op); |
| 8738 | visitAll(S, Search); |
| 8739 | return Search.IsFound; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 8740 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 8741 | |
| 8742 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 8743 | ValuesAtScopes.erase(S); |
| 8744 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 8745 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 8746 | UnsignedRanges.erase(S); |
| 8747 | SignedRanges.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 8748 | |
| 8749 | for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = |
| 8750 | BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) { |
| 8751 | BackedgeTakenInfo &BEInfo = I->second; |
| 8752 | if (BEInfo.hasOperand(S, this)) { |
| 8753 | BEInfo.clear(); |
| 8754 | BackedgeTakenCounts.erase(I++); |
| 8755 | } |
| 8756 | else |
| 8757 | ++I; |
| 8758 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 8759 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8760 | |
| 8761 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 8762 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 8763 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 8764 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 8765 | size_t Pos = 0; |
| 8766 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 8767 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 8768 | Pos += To.size(); |
| 8769 | } |
| 8770 | } |
| 8771 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8772 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 8773 | static void |
| 8774 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
| 8775 | for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) { |
| 8776 | getLoopBackedgeTakenCounts(*I, Map, SE); // recurse. |
| 8777 | |
| 8778 | std::string &S = Map[L]; |
| 8779 | if (S.empty()) { |
| 8780 | raw_string_ostream OS(S); |
| 8781 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 8782 | |
| 8783 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 8784 | replaceSubString(OS.str(), "false", "0"); |
| 8785 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 8786 | // FIXME: Remove this when SCEV gets smarter about them. |
| 8787 | replaceSubString(OS.str(), "<nw>", ""); |
| 8788 | replaceSubString(OS.str(), "<nsw>", ""); |
| 8789 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8790 | } |
| 8791 | } |
| 8792 | } |
| 8793 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8794 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8795 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 8796 | |
| 8797 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 8798 | // FIXME: It would be much better to store actual values instead of strings, |
| 8799 | // but SCEV pointers will change if we drop the caches. |
| 8800 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8801 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8802 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 8803 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8804 | // Gather stringified backedge taken counts for all loops using a fresh |
| 8805 | // ScalarEvolution object. |
| 8806 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
| 8807 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 8808 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8809 | |
| 8810 | // Now compare whether they're the same with and without caches. This allows |
| 8811 | // verifying that no pass changed the cache. |
| 8812 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 8813 | "New loops suddenly appeared!"); |
| 8814 | |
| 8815 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 8816 | OldE = BackedgeDumpsOld.end(), |
| 8817 | NewI = BackedgeDumpsNew.begin(); |
| 8818 | OldI != OldE; ++OldI, ++NewI) { |
| 8819 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 8820 | |
| 8821 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 8822 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 8823 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8824 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 8825 | // usually not harmful. |
| 8826 | if (OldI->second != NewI->second && |
| 8827 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 8828 | NewI->second.find("undef") == std::string::npos && |
| 8829 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8830 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 8831 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8832 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 8833 | << "' changed from '" << OldI->second |
| 8834 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 8835 | std::abort(); |
| 8836 | } |
| 8837 | } |
| 8838 | |
| 8839 | // TODO: Verify more things. |
| 8840 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8841 | |
| 8842 | char ScalarEvolutionAnalysis::PassID; |
| 8843 | |
| 8844 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
| 8845 | AnalysisManager<Function> *AM) { |
| 8846 | return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F), |
| 8847 | AM->getResult<AssumptionAnalysis>(F), |
| 8848 | AM->getResult<DominatorTreeAnalysis>(F), |
| 8849 | AM->getResult<LoopAnalysis>(F)); |
| 8850 | } |
| 8851 | |
| 8852 | PreservedAnalyses |
| 8853 | ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) { |
| 8854 | AM->getResult<ScalarEvolutionAnalysis>(F).print(OS); |
| 8855 | return PreservedAnalyses::all(); |
| 8856 | } |
| 8857 | |
| 8858 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 8859 | "Scalar Evolution Analysis", false, true) |
| 8860 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 8861 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 8862 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 8863 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 8864 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 8865 | "Scalar Evolution Analysis", false, true) |
| 8866 | char ScalarEvolutionWrapperPass::ID = 0; |
| 8867 | |
| 8868 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 8869 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 8870 | } |
| 8871 | |
| 8872 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 8873 | SE.reset(new ScalarEvolution( |
| 8874 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 8875 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 8876 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 8877 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 8878 | return false; |
| 8879 | } |
| 8880 | |
| 8881 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 8882 | |
| 8883 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 8884 | SE->print(OS); |
| 8885 | } |
| 8886 | |
| 8887 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 8888 | if (!VerifySCEV) |
| 8889 | return; |
| 8890 | |
| 8891 | SE->verify(); |
| 8892 | } |
| 8893 | |
| 8894 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 8895 | AU.setPreservesAll(); |
| 8896 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
| 8897 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 8898 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 8899 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 8900 | } |