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" |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 86 | #include "llvm/IR/PatternMatch.h" |
Chris Lattner | 996795b | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 87 | #include "llvm/Support/CommandLine.h" |
David Greene | 2330f78 | 2009-12-23 22:58:38 +0000 | [diff] [blame] | 88 | #include "llvm/Support/Debug.h" |
Torok Edwin | 56d0659 | 2009-07-11 20:10:48 +0000 | [diff] [blame] | 89 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | 0a1e993 | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 90 | #include "llvm/Support/MathExtras.h" |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 91 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 92 | #include "llvm/Support/SaveAndRestore.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 93 | #include <algorithm> |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 94 | using namespace llvm; |
| 95 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 96 | #define DEBUG_TYPE "scalar-evolution" |
| 97 | |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 98 | STATISTIC(NumArrayLenItCounts, |
| 99 | "Number of trip counts computed with array length"); |
| 100 | STATISTIC(NumTripCountsComputed, |
| 101 | "Number of loops with predictable loop counts"); |
| 102 | STATISTIC(NumTripCountsNotComputed, |
| 103 | "Number of loops without predictable loop counts"); |
| 104 | STATISTIC(NumBruteForceTripCountsComputed, |
| 105 | "Number of loops with trip counts computed by force"); |
| 106 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 107 | static cl::opt<unsigned> |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 108 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 109 | cl::desc("Maximum number of iterations SCEV will " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 110 | "symbolically execute a constant " |
| 111 | "derived loop"), |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 112 | cl::init(100)); |
| 113 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 114 | // FIXME: Enable this with XDEBUG when the test suite is clean. |
| 115 | static cl::opt<bool> |
| 116 | VerifySCEV("verify-scev", |
| 117 | cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 118 | static cl::opt<bool> |
| 119 | VerifySCEVMap("verify-scev-maps", |
| 120 | cl::desc("Verify no dangling value in ScalarEvolution's" |
| 121 | "ExprValueMap (slow)")); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 122 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 123 | //===----------------------------------------------------------------------===// |
| 124 | // SCEV class definitions |
| 125 | //===----------------------------------------------------------------------===// |
| 126 | |
| 127 | //===----------------------------------------------------------------------===// |
| 128 | // Implementation of the SCEV class. |
| 129 | // |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 130 | |
Davide Italiano | 2071f4c | 2015-10-25 19:55:24 +0000 | [diff] [blame] | 131 | LLVM_DUMP_METHOD |
| 132 | void SCEV::dump() const { |
| 133 | print(dbgs()); |
| 134 | dbgs() << '\n'; |
| 135 | } |
| 136 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 137 | void SCEV::print(raw_ostream &OS) const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 138 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 139 | case scConstant: |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 140 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 141 | return; |
| 142 | case scTruncate: { |
| 143 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); |
| 144 | const SCEV *Op = Trunc->getOperand(); |
| 145 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " |
| 146 | << *Trunc->getType() << ")"; |
| 147 | return; |
| 148 | } |
| 149 | case scZeroExtend: { |
| 150 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); |
| 151 | const SCEV *Op = ZExt->getOperand(); |
| 152 | OS << "(zext " << *Op->getType() << " " << *Op << " to " |
| 153 | << *ZExt->getType() << ")"; |
| 154 | return; |
| 155 | } |
| 156 | case scSignExtend: { |
| 157 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); |
| 158 | const SCEV *Op = SExt->getOperand(); |
| 159 | OS << "(sext " << *Op->getType() << " " << *Op << " to " |
| 160 | << *SExt->getType() << ")"; |
| 161 | return; |
| 162 | } |
| 163 | case scAddRecExpr: { |
| 164 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); |
| 165 | OS << "{" << *AR->getOperand(0); |
| 166 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) |
| 167 | OS << ",+," << *AR->getOperand(i); |
| 168 | OS << "}<"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 169 | if (AR->hasNoUnsignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 170 | OS << "nuw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 171 | if (AR->hasNoSignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 172 | OS << "nsw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 173 | if (AR->hasNoSelfWrap() && |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 174 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) |
| 175 | OS << "nw><"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 176 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 177 | OS << ">"; |
| 178 | return; |
| 179 | } |
| 180 | case scAddExpr: |
| 181 | case scMulExpr: |
| 182 | case scUMaxExpr: |
| 183 | case scSMaxExpr: { |
| 184 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 185 | const char *OpStr = nullptr; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 186 | switch (NAry->getSCEVType()) { |
| 187 | case scAddExpr: OpStr = " + "; break; |
| 188 | case scMulExpr: OpStr = " * "; break; |
| 189 | case scUMaxExpr: OpStr = " umax "; break; |
| 190 | case scSMaxExpr: OpStr = " smax "; break; |
| 191 | } |
| 192 | OS << "("; |
| 193 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 194 | I != E; ++I) { |
| 195 | OS << **I; |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 196 | if (std::next(I) != E) |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 197 | OS << OpStr; |
| 198 | } |
| 199 | OS << ")"; |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 200 | switch (NAry->getSCEVType()) { |
| 201 | case scAddExpr: |
| 202 | case scMulExpr: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 203 | if (NAry->hasNoUnsignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 204 | OS << "<nuw>"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 205 | if (NAry->hasNoSignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 206 | OS << "<nsw>"; |
| 207 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 208 | return; |
| 209 | } |
| 210 | case scUDivExpr: { |
| 211 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); |
| 212 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; |
| 213 | return; |
| 214 | } |
| 215 | case scUnknown: { |
| 216 | const SCEVUnknown *U = cast<SCEVUnknown>(this); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 217 | Type *AllocTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 218 | if (U->isSizeOf(AllocTy)) { |
| 219 | OS << "sizeof(" << *AllocTy << ")"; |
| 220 | return; |
| 221 | } |
| 222 | if (U->isAlignOf(AllocTy)) { |
| 223 | OS << "alignof(" << *AllocTy << ")"; |
| 224 | return; |
| 225 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 226 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 227 | Type *CTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 228 | Constant *FieldNo; |
| 229 | if (U->isOffsetOf(CTy, FieldNo)) { |
| 230 | OS << "offsetof(" << *CTy << ", "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 231 | FieldNo->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 232 | OS << ")"; |
| 233 | return; |
| 234 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 235 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 236 | // Otherwise just print it normally. |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 237 | U->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 238 | return; |
| 239 | } |
| 240 | case scCouldNotCompute: |
| 241 | OS << "***COULDNOTCOMPUTE***"; |
| 242 | return; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 243 | } |
| 244 | llvm_unreachable("Unknown SCEV kind!"); |
| 245 | } |
| 246 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 247 | Type *SCEV::getType() const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 248 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 249 | case scConstant: |
| 250 | return cast<SCEVConstant>(this)->getType(); |
| 251 | case scTruncate: |
| 252 | case scZeroExtend: |
| 253 | case scSignExtend: |
| 254 | return cast<SCEVCastExpr>(this)->getType(); |
| 255 | case scAddRecExpr: |
| 256 | case scMulExpr: |
| 257 | case scUMaxExpr: |
| 258 | case scSMaxExpr: |
| 259 | return cast<SCEVNAryExpr>(this)->getType(); |
| 260 | case scAddExpr: |
| 261 | return cast<SCEVAddExpr>(this)->getType(); |
| 262 | case scUDivExpr: |
| 263 | return cast<SCEVUDivExpr>(this)->getType(); |
| 264 | case scUnknown: |
| 265 | return cast<SCEVUnknown>(this)->getType(); |
| 266 | case scCouldNotCompute: |
| 267 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 268 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 269 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 270 | } |
| 271 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 272 | bool SCEV::isZero() const { |
| 273 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 274 | return SC->getValue()->isZero(); |
| 275 | return false; |
| 276 | } |
| 277 | |
Dan Gohman | ba7f6d8 | 2009-05-18 15:22:39 +0000 | [diff] [blame] | 278 | bool SCEV::isOne() const { |
| 279 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 280 | return SC->getValue()->isOne(); |
| 281 | return false; |
| 282 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 283 | |
Dan Gohman | 18a96bb | 2009-06-24 00:30:26 +0000 | [diff] [blame] | 284 | bool SCEV::isAllOnesValue() const { |
| 285 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 286 | return SC->getValue()->isAllOnesValue(); |
| 287 | return false; |
| 288 | } |
| 289 | |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 290 | /// isNonConstantNegative - Return true if the specified scev is negated, but |
| 291 | /// not a constant. |
| 292 | bool SCEV::isNonConstantNegative() const { |
| 293 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); |
| 294 | if (!Mul) return false; |
| 295 | |
| 296 | // If there is a constant factor, it will be first. |
| 297 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); |
| 298 | if (!SC) return false; |
| 299 | |
| 300 | // Return true if the value is negative, this matches things like (-42 * V). |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 301 | return SC->getAPInt().isNegative(); |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 302 | } |
| 303 | |
Owen Anderson | 04052ec | 2009-06-22 21:57:23 +0000 | [diff] [blame] | 304 | SCEVCouldNotCompute::SCEVCouldNotCompute() : |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 305 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 306 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 307 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 308 | return S->getSCEVType() == scCouldNotCompute; |
| 309 | } |
| 310 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 311 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 312 | FoldingSetNodeID ID; |
| 313 | ID.AddInteger(scConstant); |
| 314 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 315 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 316 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 317 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 318 | UniqueSCEVs.InsertNode(S, IP); |
| 319 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 320 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 321 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 322 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 323 | return getConstant(ConstantInt::get(getContext(), Val)); |
Dan Gohman | 0a76e7f | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 324 | } |
| 325 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 326 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 327 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { |
| 328 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); |
Dan Gohman | a029cbe | 2010-04-21 16:04:04 +0000 | [diff] [blame] | 329 | return getConstant(ConstantInt::get(ITy, V, isSigned)); |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 330 | } |
| 331 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 332 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 333 | unsigned SCEVTy, const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 334 | : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 335 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 336 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 337 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 338 | : SCEVCastExpr(ID, scTruncate, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 339 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 340 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 341 | "Cannot truncate non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 342 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 343 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 344 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 345 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 346 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 347 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 348 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 349 | "Cannot zero extend non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 350 | } |
| 351 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 352 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 353 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 354 | : SCEVCastExpr(ID, scSignExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 355 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 356 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 357 | "Cannot sign extend non-integer value!"); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 358 | } |
| 359 | |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 360 | void SCEVUnknown::deleted() { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 361 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 362 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 363 | |
| 364 | // Remove this SCEVUnknown from the uniquing map. |
| 365 | SE->UniqueSCEVs.RemoveNode(this); |
| 366 | |
| 367 | // Release the value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 368 | setValPtr(nullptr); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 369 | } |
| 370 | |
| 371 | void SCEVUnknown::allUsesReplacedWith(Value *New) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 372 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 373 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 374 | |
| 375 | // Remove this SCEVUnknown from the uniquing map. |
| 376 | SE->UniqueSCEVs.RemoveNode(this); |
| 377 | |
| 378 | // Update this SCEVUnknown to point to the new value. This is needed |
| 379 | // because there may still be outstanding SCEVs which still point to |
| 380 | // this SCEVUnknown. |
| 381 | setValPtr(New); |
| 382 | } |
| 383 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 384 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 385 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 386 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 387 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 388 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 389 | CE->getOperand(0)->isNullValue() && |
| 390 | CE->getNumOperands() == 2) |
| 391 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) |
| 392 | if (CI->isOne()) { |
| 393 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) |
| 394 | ->getElementType(); |
| 395 | return true; |
| 396 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 397 | |
| 398 | return false; |
| 399 | } |
| 400 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 401 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 402 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 403 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 404 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 405 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 406 | CE->getOperand(0)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 407 | Type *Ty = |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 408 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 409 | if (StructType *STy = dyn_cast<StructType>(Ty)) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 410 | if (!STy->isPacked() && |
| 411 | CE->getNumOperands() == 3 && |
| 412 | CE->getOperand(1)->isNullValue()) { |
| 413 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) |
| 414 | if (CI->isOne() && |
| 415 | STy->getNumElements() == 2 && |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 416 | STy->getElementType(0)->isIntegerTy(1)) { |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 417 | AllocTy = STy->getElementType(1); |
| 418 | return true; |
| 419 | } |
| 420 | } |
| 421 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 422 | |
| 423 | return false; |
| 424 | } |
| 425 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 426 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 427 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 428 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 429 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
| 430 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 431 | CE->getNumOperands() == 3 && |
| 432 | CE->getOperand(0)->isNullValue() && |
| 433 | CE->getOperand(1)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 434 | Type *Ty = |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 435 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
| 436 | // Ignore vector types here so that ScalarEvolutionExpander doesn't |
| 437 | // emit getelementptrs that index into vectors. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 438 | if (Ty->isStructTy() || Ty->isArrayTy()) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 439 | CTy = Ty; |
| 440 | FieldNo = CE->getOperand(2); |
| 441 | return true; |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | return false; |
| 446 | } |
| 447 | |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 448 | //===----------------------------------------------------------------------===// |
| 449 | // SCEV Utilities |
| 450 | //===----------------------------------------------------------------------===// |
| 451 | |
| 452 | namespace { |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 453 | /// SCEVComplexityCompare - Return true if the complexity of the LHS is less |
| 454 | /// than the complexity of the RHS. This comparator is used to canonicalize |
| 455 | /// expressions. |
| 456 | class SCEVComplexityCompare { |
| 457 | const LoopInfo *const LI; |
| 458 | public: |
| 459 | explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 460 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 461 | // Return true or false if LHS is less than, or at least RHS, respectively. |
| 462 | bool operator()(const SCEV *LHS, const SCEV *RHS) const { |
| 463 | return compare(LHS, RHS) < 0; |
| 464 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 465 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 466 | // Return negative, zero, or positive, if LHS is less than, equal to, or |
| 467 | // greater than RHS, respectively. A three-way result allows recursive |
| 468 | // comparisons to be more efficient. |
| 469 | int compare(const SCEV *LHS, const SCEV *RHS) const { |
| 470 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. |
| 471 | if (LHS == RHS) |
| 472 | return 0; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 473 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 474 | // Primarily, sort the SCEVs by their getSCEVType(). |
| 475 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); |
| 476 | if (LType != RType) |
| 477 | return (int)LType - (int)RType; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 478 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 479 | // Aside from the getSCEVType() ordering, the particular ordering |
| 480 | // isn't very important except that it's beneficial to be consistent, |
| 481 | // so that (a + b) and (b + a) don't end up as different expressions. |
| 482 | switch (static_cast<SCEVTypes>(LType)) { |
| 483 | case scUnknown: { |
| 484 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); |
| 485 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 486 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 487 | // Sort SCEVUnknown values with some loose heuristics. TODO: This is |
| 488 | // not as complete as it could be. |
| 489 | const Value *LV = LU->getValue(), *RV = RU->getValue(); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 490 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 491 | // Order pointer values after integer values. This helps SCEVExpander |
| 492 | // form GEPs. |
| 493 | bool LIsPointer = LV->getType()->isPointerTy(), |
| 494 | RIsPointer = RV->getType()->isPointerTy(); |
| 495 | if (LIsPointer != RIsPointer) |
| 496 | return (int)LIsPointer - (int)RIsPointer; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 497 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 498 | // Compare getValueID values. |
| 499 | unsigned LID = LV->getValueID(), |
| 500 | RID = RV->getValueID(); |
| 501 | if (LID != RID) |
| 502 | return (int)LID - (int)RID; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 503 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 504 | // Sort arguments by their position. |
| 505 | if (const Argument *LA = dyn_cast<Argument>(LV)) { |
| 506 | const Argument *RA = cast<Argument>(RV); |
| 507 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); |
| 508 | return (int)LArgNo - (int)RArgNo; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 509 | } |
| 510 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 511 | // For instructions, compare their loop depth, and their operand |
| 512 | // count. This is pretty loose. |
| 513 | if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { |
| 514 | const Instruction *RInst = cast<Instruction>(RV); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 515 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 516 | // Compare loop depths. |
| 517 | const BasicBlock *LParent = LInst->getParent(), |
| 518 | *RParent = RInst->getParent(); |
| 519 | if (LParent != RParent) { |
| 520 | unsigned LDepth = LI->getLoopDepth(LParent), |
| 521 | RDepth = LI->getLoopDepth(RParent); |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 522 | if (LDepth != RDepth) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 523 | return (int)LDepth - (int)RDepth; |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 524 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 525 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 526 | // Compare the number of operands. |
| 527 | unsigned LNumOps = LInst->getNumOperands(), |
| 528 | RNumOps = RInst->getNumOperands(); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 529 | return (int)LNumOps - (int)RNumOps; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 530 | } |
| 531 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 532 | return 0; |
| 533 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 534 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 535 | case scConstant: { |
| 536 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); |
| 537 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); |
| 538 | |
| 539 | // Compare constant values. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 540 | const APInt &LA = LC->getAPInt(); |
| 541 | const APInt &RA = RC->getAPInt(); |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 542 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); |
| 543 | if (LBitWidth != RBitWidth) |
| 544 | return (int)LBitWidth - (int)RBitWidth; |
| 545 | return LA.ult(RA) ? -1 : 1; |
| 546 | } |
| 547 | |
| 548 | case scAddRecExpr: { |
| 549 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); |
| 550 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); |
| 551 | |
| 552 | // Compare addrec loop depths. |
| 553 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); |
| 554 | if (LLoop != RLoop) { |
| 555 | unsigned LDepth = LLoop->getLoopDepth(), |
| 556 | RDepth = RLoop->getLoopDepth(); |
| 557 | if (LDepth != RDepth) |
| 558 | return (int)LDepth - (int)RDepth; |
| 559 | } |
| 560 | |
| 561 | // Addrec complexity grows with operand count. |
| 562 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); |
| 563 | if (LNumOps != RNumOps) |
| 564 | return (int)LNumOps - (int)RNumOps; |
| 565 | |
| 566 | // Lexicographically compare. |
| 567 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 568 | long X = compare(LA->getOperand(i), RA->getOperand(i)); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 569 | if (X != 0) |
| 570 | return X; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 571 | } |
| 572 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 573 | return 0; |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 574 | } |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 575 | |
| 576 | case scAddExpr: |
| 577 | case scMulExpr: |
| 578 | case scSMaxExpr: |
| 579 | case scUMaxExpr: { |
| 580 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); |
| 581 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); |
| 582 | |
| 583 | // Lexicographically compare n-ary expressions. |
| 584 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); |
| 585 | if (LNumOps != RNumOps) |
| 586 | return (int)LNumOps - (int)RNumOps; |
| 587 | |
| 588 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 589 | if (i >= RNumOps) |
| 590 | return 1; |
| 591 | long X = compare(LC->getOperand(i), RC->getOperand(i)); |
| 592 | if (X != 0) |
| 593 | return X; |
| 594 | } |
| 595 | return (int)LNumOps - (int)RNumOps; |
| 596 | } |
| 597 | |
| 598 | case scUDivExpr: { |
| 599 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); |
| 600 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); |
| 601 | |
| 602 | // Lexicographically compare udiv expressions. |
| 603 | long X = compare(LC->getLHS(), RC->getLHS()); |
| 604 | if (X != 0) |
| 605 | return X; |
| 606 | return compare(LC->getRHS(), RC->getRHS()); |
| 607 | } |
| 608 | |
| 609 | case scTruncate: |
| 610 | case scZeroExtend: |
| 611 | case scSignExtend: { |
| 612 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); |
| 613 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); |
| 614 | |
| 615 | // Compare cast expressions by operand. |
| 616 | return compare(LC->getOperand(), RC->getOperand()); |
| 617 | } |
| 618 | |
| 619 | case scCouldNotCompute: |
| 620 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
| 621 | } |
| 622 | llvm_unreachable("Unknown SCEV kind!"); |
| 623 | } |
| 624 | }; |
| 625 | } // end anonymous namespace |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 626 | |
| 627 | /// GroupByComplexity - Given a list of SCEV objects, order them by their |
| 628 | /// complexity, and group objects of the same complexity together by value. |
| 629 | /// When this routine is finished, we know that any duplicates in the vector are |
| 630 | /// consecutive and that complexity is monotonically increasing. |
| 631 | /// |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 632 | /// 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] | 633 | /// results from this routine. In other words, we don't want the results of |
| 634 | /// this to depend on where the addresses of various SCEV objects happened to |
| 635 | /// land in memory. |
| 636 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 637 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 638 | LoopInfo *LI) { |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 639 | if (Ops.size() < 2) return; // Noop |
| 640 | if (Ops.size() == 2) { |
| 641 | // This is the common case, which also happens to be trivially simple. |
| 642 | // Special case it. |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 643 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; |
| 644 | if (SCEVComplexityCompare(LI)(RHS, LHS)) |
| 645 | std::swap(LHS, RHS); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 646 | return; |
| 647 | } |
| 648 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 649 | // Do the rough sort by complexity. |
| 650 | std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); |
| 651 | |
| 652 | // Now that we are sorted by complexity, group elements of the same |
| 653 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 654 | // be extremely short in practice. Note that we take this approach because we |
| 655 | // do not want to depend on the addresses of the objects we are grouping. |
| 656 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
| 657 | const SCEV *S = Ops[i]; |
| 658 | unsigned Complexity = S->getSCEVType(); |
| 659 | |
| 660 | // If there are any objects of the same complexity and same value as this |
| 661 | // one, group them. |
| 662 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 663 | if (Ops[j] == S) { // Found a duplicate. |
| 664 | // Move it to immediately after i'th element. |
| 665 | std::swap(Ops[i+1], Ops[j]); |
| 666 | ++i; // no need to rescan it. |
| 667 | if (i == e-2) return; // Done! |
| 668 | } |
| 669 | } |
| 670 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 671 | } |
| 672 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 673 | // Returns the size of the SCEV S. |
| 674 | static inline int sizeOfSCEV(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 675 | struct FindSCEVSize { |
| 676 | int Size; |
| 677 | FindSCEVSize() : Size(0) {} |
| 678 | |
| 679 | bool follow(const SCEV *S) { |
| 680 | ++Size; |
| 681 | // Keep looking at all operands of S. |
| 682 | return true; |
| 683 | } |
| 684 | bool isDone() const { |
| 685 | return false; |
| 686 | } |
| 687 | }; |
| 688 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 689 | FindSCEVSize F; |
| 690 | SCEVTraversal<FindSCEVSize> ST(F); |
| 691 | ST.visitAll(S); |
| 692 | return F.Size; |
| 693 | } |
| 694 | |
| 695 | namespace { |
| 696 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 697 | struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 698 | public: |
| 699 | // Computes the Quotient and Remainder of the division of Numerator by |
| 700 | // Denominator. |
| 701 | static void divide(ScalarEvolution &SE, const SCEV *Numerator, |
| 702 | const SCEV *Denominator, const SCEV **Quotient, |
| 703 | const SCEV **Remainder) { |
| 704 | assert(Numerator && Denominator && "Uninitialized SCEV"); |
| 705 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 706 | SCEVDivision D(SE, Numerator, Denominator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 707 | |
| 708 | // Check for the trivial case here to avoid having to check for it in the |
| 709 | // rest of the code. |
| 710 | if (Numerator == Denominator) { |
| 711 | *Quotient = D.One; |
| 712 | *Remainder = D.Zero; |
| 713 | return; |
| 714 | } |
| 715 | |
| 716 | if (Numerator->isZero()) { |
| 717 | *Quotient = D.Zero; |
| 718 | *Remainder = D.Zero; |
| 719 | return; |
| 720 | } |
| 721 | |
Brendon Cahoon | a57cc8b | 2015-04-20 16:03:28 +0000 | [diff] [blame] | 722 | // A simple case when N/1. The quotient is N. |
| 723 | if (Denominator->isOne()) { |
| 724 | *Quotient = Numerator; |
| 725 | *Remainder = D.Zero; |
| 726 | return; |
| 727 | } |
| 728 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 729 | // Split the Denominator when it is a product. |
| 730 | if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) { |
| 731 | const SCEV *Q, *R; |
| 732 | *Quotient = Numerator; |
| 733 | for (const SCEV *Op : T->operands()) { |
| 734 | divide(SE, *Quotient, Op, &Q, &R); |
| 735 | *Quotient = Q; |
| 736 | |
| 737 | // Bail out when the Numerator is not divisible by one of the terms of |
| 738 | // the Denominator. |
| 739 | if (!R->isZero()) { |
| 740 | *Quotient = D.Zero; |
| 741 | *Remainder = Numerator; |
| 742 | return; |
| 743 | } |
| 744 | } |
| 745 | *Remainder = D.Zero; |
| 746 | return; |
| 747 | } |
| 748 | |
| 749 | D.visit(Numerator); |
| 750 | *Quotient = D.Quotient; |
| 751 | *Remainder = D.Remainder; |
| 752 | } |
| 753 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 754 | // Except in the trivial case described above, we do not know how to divide |
| 755 | // Expr by Denominator for the following functions with empty implementation. |
| 756 | void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} |
| 757 | void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} |
| 758 | void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} |
| 759 | void visitUDivExpr(const SCEVUDivExpr *Numerator) {} |
| 760 | void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} |
| 761 | void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} |
| 762 | void visitUnknown(const SCEVUnknown *Numerator) {} |
| 763 | void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} |
| 764 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 765 | void visitConstant(const SCEVConstant *Numerator) { |
| 766 | if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 767 | APInt NumeratorVal = Numerator->getAPInt(); |
| 768 | APInt DenominatorVal = D->getAPInt(); |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 769 | uint32_t NumeratorBW = NumeratorVal.getBitWidth(); |
| 770 | uint32_t DenominatorBW = DenominatorVal.getBitWidth(); |
| 771 | |
| 772 | if (NumeratorBW > DenominatorBW) |
| 773 | DenominatorVal = DenominatorVal.sext(NumeratorBW); |
| 774 | else if (NumeratorBW < DenominatorBW) |
| 775 | NumeratorVal = NumeratorVal.sext(DenominatorBW); |
| 776 | |
| 777 | APInt QuotientVal(NumeratorVal.getBitWidth(), 0); |
| 778 | APInt RemainderVal(NumeratorVal.getBitWidth(), 0); |
| 779 | APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); |
| 780 | Quotient = SE.getConstant(QuotientVal); |
| 781 | Remainder = SE.getConstant(RemainderVal); |
| 782 | return; |
| 783 | } |
| 784 | } |
| 785 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 786 | void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { |
| 787 | const SCEV *StartQ, *StartR, *StepQ, *StepR; |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 788 | if (!Numerator->isAffine()) |
| 789 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 790 | divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); |
| 791 | divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); |
Brendon Cahoon | f9751ad | 2015-04-22 15:06:40 +0000 | [diff] [blame] | 792 | // Bail out if the types do not match. |
| 793 | Type *Ty = Denominator->getType(); |
| 794 | if (Ty != StartQ->getType() || Ty != StartR->getType() || |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 795 | Ty != StepQ->getType() || Ty != StepR->getType()) |
| 796 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 797 | Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), |
| 798 | Numerator->getNoWrapFlags()); |
| 799 | Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), |
| 800 | Numerator->getNoWrapFlags()); |
| 801 | } |
| 802 | |
| 803 | void visitAddExpr(const SCEVAddExpr *Numerator) { |
| 804 | SmallVector<const SCEV *, 2> Qs, Rs; |
| 805 | Type *Ty = Denominator->getType(); |
| 806 | |
| 807 | for (const SCEV *Op : Numerator->operands()) { |
| 808 | const SCEV *Q, *R; |
| 809 | divide(SE, Op, Denominator, &Q, &R); |
| 810 | |
| 811 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 812 | if (Ty != Q->getType() || Ty != R->getType()) |
| 813 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 814 | |
| 815 | Qs.push_back(Q); |
| 816 | Rs.push_back(R); |
| 817 | } |
| 818 | |
| 819 | if (Qs.size() == 1) { |
| 820 | Quotient = Qs[0]; |
| 821 | Remainder = Rs[0]; |
| 822 | return; |
| 823 | } |
| 824 | |
| 825 | Quotient = SE.getAddExpr(Qs); |
| 826 | Remainder = SE.getAddExpr(Rs); |
| 827 | } |
| 828 | |
| 829 | void visitMulExpr(const SCEVMulExpr *Numerator) { |
| 830 | SmallVector<const SCEV *, 2> Qs; |
| 831 | Type *Ty = Denominator->getType(); |
| 832 | |
| 833 | bool FoundDenominatorTerm = false; |
| 834 | for (const SCEV *Op : Numerator->operands()) { |
| 835 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 836 | if (Ty != Op->getType()) |
| 837 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 838 | |
| 839 | if (FoundDenominatorTerm) { |
| 840 | Qs.push_back(Op); |
| 841 | continue; |
| 842 | } |
| 843 | |
| 844 | // Check whether Denominator divides one of the product operands. |
| 845 | const SCEV *Q, *R; |
| 846 | divide(SE, Op, Denominator, &Q, &R); |
| 847 | if (!R->isZero()) { |
| 848 | Qs.push_back(Op); |
| 849 | continue; |
| 850 | } |
| 851 | |
| 852 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 853 | if (Ty != Q->getType()) |
| 854 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 855 | |
| 856 | FoundDenominatorTerm = true; |
| 857 | Qs.push_back(Q); |
| 858 | } |
| 859 | |
| 860 | if (FoundDenominatorTerm) { |
| 861 | Remainder = Zero; |
| 862 | if (Qs.size() == 1) |
| 863 | Quotient = Qs[0]; |
| 864 | else |
| 865 | Quotient = SE.getMulExpr(Qs); |
| 866 | return; |
| 867 | } |
| 868 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 869 | if (!isa<SCEVUnknown>(Denominator)) |
| 870 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 871 | |
| 872 | // The Remainder is obtained by replacing Denominator by 0 in Numerator. |
| 873 | ValueToValueMap RewriteMap; |
| 874 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 875 | cast<SCEVConstant>(Zero)->getValue(); |
| 876 | Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 877 | |
| 878 | if (Remainder->isZero()) { |
| 879 | // The Quotient is obtained by replacing Denominator by 1 in Numerator. |
| 880 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 881 | cast<SCEVConstant>(One)->getValue(); |
| 882 | Quotient = |
| 883 | SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 884 | return; |
| 885 | } |
| 886 | |
| 887 | // Quotient is (Numerator - Remainder) divided by Denominator. |
| 888 | const SCEV *Q, *R; |
| 889 | const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 890 | // This SCEV does not seem to simplify: fail the division here. |
| 891 | if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) |
| 892 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 893 | divide(SE, Diff, Denominator, &Q, &R); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 894 | if (R != Zero) |
| 895 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 896 | Quotient = Q; |
| 897 | } |
| 898 | |
| 899 | private: |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 900 | SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, |
| 901 | const SCEV *Denominator) |
| 902 | : SE(S), Denominator(Denominator) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 903 | Zero = SE.getZero(Denominator->getType()); |
| 904 | One = SE.getOne(Denominator->getType()); |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 905 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 906 | // We generally do not know how to divide Expr by Denominator. We |
| 907 | // initialize the division to a "cannot divide" state to simplify the rest |
| 908 | // of the code. |
| 909 | cannotDivide(Numerator); |
| 910 | } |
| 911 | |
| 912 | // Convenience function for giving up on the division. We set the quotient to |
| 913 | // be equal to zero and the remainder to be equal to the numerator. |
| 914 | void cannotDivide(const SCEV *Numerator) { |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 915 | Quotient = Zero; |
| 916 | Remainder = Numerator; |
| 917 | } |
| 918 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 919 | ScalarEvolution &SE; |
| 920 | const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; |
David Majnemer | 32b8ccf | 2014-11-16 20:35:19 +0000 | [diff] [blame] | 921 | }; |
| 922 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 923 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 924 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 925 | //===----------------------------------------------------------------------===// |
| 926 | // Simple SCEV method implementations |
| 927 | //===----------------------------------------------------------------------===// |
| 928 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 929 | /// BinomialCoefficient - Compute BC(It, K). The result has width W. |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 930 | /// Assume, K > 0. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 931 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 932 | ScalarEvolution &SE, |
Nick Lewycky | 702cf1e | 2011-09-06 06:39:54 +0000 | [diff] [blame] | 933 | Type *ResultTy) { |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 934 | // Handle the simplest case efficiently. |
| 935 | if (K == 1) |
| 936 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 937 | |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 938 | // We are using the following formula for BC(It, K): |
| 939 | // |
| 940 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 941 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 942 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 943 | // overflow. Hence, we must assure that the result of our computation is |
| 944 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 945 | // safe in modular arithmetic. |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 946 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 947 | // 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] | 948 | // 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] | 949 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 950 | // exponentiation: |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 951 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 952 | // 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] | 953 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 954 | // This formula is trivially equivalent to the previous formula. However, |
| 955 | // this formula can be implemented much more efficiently. The trick is that |
| 956 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 957 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 958 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 959 | // width W. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 960 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 961 | // The next issue is how to safely do the division by 2^T. The way this |
| 962 | // is done is by doing the multiplication step at a width of at least W + T |
| 963 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 964 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 965 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 966 | // truncated out after the division by 2^T. |
| 967 | // |
| 968 | // In comparison to just directly using the first formula, this technique |
| 969 | // is much more efficient; using the first formula requires W * K bits, |
| 970 | // but this formula less than W + K bits. Also, the first formula requires |
| 971 | // a division step, whereas this formula only requires multiplies and shifts. |
| 972 | // |
| 973 | // It doesn't matter whether the subtraction step is done in the calculation |
| 974 | // width or the input iteration count's width; if the subtraction overflows, |
| 975 | // the result must be zero anyway. We prefer here to do it in the width of |
| 976 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 977 | // isn't smart enough to ignore the overflow, which leads to much less |
| 978 | // efficient code if the width of the subtraction is wider than the native |
| 979 | // register width. |
| 980 | // |
| 981 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 982 | // the multiplication; for example, K=2 can be calculated as |
| 983 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 984 | // extra arithmetic, so it's not an obvious win, and it gets |
| 985 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 986 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 987 | // Protection from insane SCEVs; this bound is conservative, |
| 988 | // but it probably doesn't matter. |
| 989 | if (K > 1000) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 990 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 991 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 992 | unsigned W = SE.getTypeSizeInBits(ResultTy); |
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 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 995 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 996 | // Other overflow doesn't matter because we only care about the bottom |
| 997 | // W bits of the result. |
| 998 | APInt OddFactorial(W, 1); |
| 999 | unsigned T = 1; |
| 1000 | for (unsigned i = 3; i <= K; ++i) { |
| 1001 | APInt Mult(W, i); |
| 1002 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 1003 | T += TwoFactors; |
| 1004 | Mult = Mult.lshr(TwoFactors); |
| 1005 | OddFactorial *= Mult; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1006 | } |
Nick Lewycky | ed169d5 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 1007 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1008 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 21add8f | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 1009 | unsigned CalculationBits = W + T; |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1010 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1011 | // Calculate 2^T, at width T+W. |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 1012 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1013 | |
| 1014 | // Calculate the multiplicative inverse of K! / 2^T; |
| 1015 | // this multiplication factor will perform the exact division by |
| 1016 | // K! / 2^T. |
| 1017 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 1018 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 1019 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 1020 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 1021 | |
| 1022 | // Calculate the product, at width T+W |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1023 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1024 | CalculationBits); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1025 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1026 | for (unsigned i = 1; i != K; ++i) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1027 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1028 | Dividend = SE.getMulExpr(Dividend, |
| 1029 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 1030 | } |
| 1031 | |
| 1032 | // Divide by 2^T |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1033 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1034 | |
| 1035 | // Truncate the result, and divide by K! / 2^T. |
| 1036 | |
| 1037 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 1038 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1039 | } |
| 1040 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1041 | /// evaluateAtIteration - Return the value of this chain of recurrences at |
| 1042 | /// the specified iteration number. We can evaluate this recurrence by |
| 1043 | /// multiplying each element in the chain by the binomial coefficient |
| 1044 | /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: |
| 1045 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1046 | /// 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] | 1047 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1048 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1049 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1050 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1051 | ScalarEvolution &SE) const { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1052 | const SCEV *Result = getStart(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1053 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1054 | // The computation is correct in the face of overflow provided that the |
| 1055 | // multiplication is performed _after_ the evaluation of the binomial |
| 1056 | // coefficient. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1057 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); |
Nick Lewycky | 707663e | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 1058 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 1059 | return Coeff; |
| 1060 | |
| 1061 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1062 | } |
| 1063 | return Result; |
| 1064 | } |
| 1065 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1066 | //===----------------------------------------------------------------------===// |
| 1067 | // SCEV Expression folder implementations |
| 1068 | //===----------------------------------------------------------------------===// |
| 1069 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1070 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1071 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1072 | assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1073 | "This is not a truncating conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1074 | assert(isSCEVable(Ty) && |
| 1075 | "This is not a conversion to a SCEVable type!"); |
| 1076 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1077 | |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1078 | FoldingSetNodeID ID; |
| 1079 | ID.AddInteger(scTruncate); |
| 1080 | ID.AddPointer(Op); |
| 1081 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1082 | void *IP = nullptr; |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1083 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1084 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1085 | // Fold if the operand is constant. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1086 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 8d7576e | 2009-06-24 00:38:39 +0000 | [diff] [blame] | 1087 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1088 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1089 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1090 | // trunc(trunc(x)) --> trunc(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1091 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1092 | return getTruncateExpr(ST->getOperand(), Ty); |
| 1093 | |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1094 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1095 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1096 | return getTruncateOrSignExtend(SS->getOperand(), Ty); |
| 1097 | |
| 1098 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1099 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1100 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty); |
| 1101 | |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1102 | // 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] | 1103 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1104 | if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1105 | SmallVector<const SCEV *, 4> Operands; |
| 1106 | bool hasTrunc = false; |
| 1107 | for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1108 | const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1109 | if (!isa<SCEVCastExpr>(SA->getOperand(i))) |
| 1110 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1111 | Operands.push_back(S); |
| 1112 | } |
| 1113 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1114 | return getAddExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1115 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1116 | } |
| 1117 | |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1118 | // 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] | 1119 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1120 | if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { |
| 1121 | SmallVector<const SCEV *, 4> Operands; |
| 1122 | bool hasTrunc = false; |
| 1123 | for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1124 | const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1125 | if (!isa<SCEVCastExpr>(SM->getOperand(i))) |
| 1126 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1127 | Operands.push_back(S); |
| 1128 | } |
| 1129 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1130 | return getMulExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1131 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1132 | } |
| 1133 | |
Dan Gohman | 5a728c9 | 2009-06-18 16:24:47 +0000 | [diff] [blame] | 1134 | // 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] | 1135 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1136 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 1137 | for (const SCEV *Op : AddRec->operands()) |
| 1138 | Operands.push_back(getTruncateExpr(Op, Ty)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1139 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1140 | } |
| 1141 | |
Dan Gohman | 89dd42a | 2010-06-25 18:47:08 +0000 | [diff] [blame] | 1142 | // The cast wasn't folded; create an explicit cast node. We can reuse |
| 1143 | // the existing insert position since if we get here, we won't have |
| 1144 | // made any changes which would invalidate it. |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1145 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), |
| 1146 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1147 | UniqueSCEVs.InsertNode(S, IP); |
| 1148 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1149 | } |
| 1150 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1151 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1152 | // signed overflow as long as the value of the recurrence within the |
| 1153 | // loop does not exceed this limit before incrementing. |
| 1154 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, |
| 1155 | ICmpInst::Predicate *Pred, |
| 1156 | ScalarEvolution *SE) { |
| 1157 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1158 | if (SE->isKnownPositive(Step)) { |
| 1159 | *Pred = ICmpInst::ICMP_SLT; |
| 1160 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - |
| 1161 | SE->getSignedRange(Step).getSignedMax()); |
| 1162 | } |
| 1163 | if (SE->isKnownNegative(Step)) { |
| 1164 | *Pred = ICmpInst::ICMP_SGT; |
| 1165 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - |
| 1166 | SE->getSignedRange(Step).getSignedMin()); |
| 1167 | } |
| 1168 | return nullptr; |
| 1169 | } |
| 1170 | |
| 1171 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1172 | // unsigned overflow as long as the value of the recurrence within the loop does |
| 1173 | // not exceed this limit before incrementing. |
| 1174 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, |
| 1175 | ICmpInst::Predicate *Pred, |
| 1176 | ScalarEvolution *SE) { |
| 1177 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1178 | *Pred = ICmpInst::ICMP_ULT; |
| 1179 | |
| 1180 | return SE->getConstant(APInt::getMinValue(BitWidth) - |
| 1181 | SE->getUnsignedRange(Step).getUnsignedMax()); |
| 1182 | } |
| 1183 | |
| 1184 | namespace { |
| 1185 | |
| 1186 | struct ExtendOpTraitsBase { |
| 1187 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); |
| 1188 | }; |
| 1189 | |
| 1190 | // Used to make code generic over signed and unsigned overflow. |
| 1191 | template <typename ExtendOp> struct ExtendOpTraits { |
| 1192 | // Members present: |
| 1193 | // |
| 1194 | // static const SCEV::NoWrapFlags WrapType; |
| 1195 | // |
| 1196 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; |
| 1197 | // |
| 1198 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1199 | // ICmpInst::Predicate *Pred, |
| 1200 | // ScalarEvolution *SE); |
| 1201 | }; |
| 1202 | |
| 1203 | template <> |
| 1204 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { |
| 1205 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; |
| 1206 | |
| 1207 | static const GetExtendExprTy GetExtendExpr; |
| 1208 | |
| 1209 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1210 | ICmpInst::Predicate *Pred, |
| 1211 | ScalarEvolution *SE) { |
| 1212 | return getSignedOverflowLimitForStep(Step, Pred, SE); |
| 1213 | } |
| 1214 | }; |
| 1215 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1216 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1217 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; |
| 1218 | |
| 1219 | template <> |
| 1220 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { |
| 1221 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; |
| 1222 | |
| 1223 | static const GetExtendExprTy GetExtendExpr; |
| 1224 | |
| 1225 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1226 | ICmpInst::Predicate *Pred, |
| 1227 | ScalarEvolution *SE) { |
| 1228 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); |
| 1229 | } |
| 1230 | }; |
| 1231 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1232 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1233 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1234 | } |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1235 | |
| 1236 | // The recurrence AR has been shown to have no signed/unsigned wrap or something |
| 1237 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as |
| 1238 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This |
| 1239 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + |
| 1240 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the |
| 1241 | // expression "Step + sext/zext(PreIncAR)" is congruent with |
| 1242 | // "sext/zext(PostIncAR)" |
| 1243 | template <typename ExtendOpTy> |
| 1244 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, |
| 1245 | ScalarEvolution *SE) { |
| 1246 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1247 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1248 | |
| 1249 | const Loop *L = AR->getLoop(); |
| 1250 | const SCEV *Start = AR->getStart(); |
| 1251 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 1252 | |
| 1253 | // Check for a simple looking step prior to loop entry. |
| 1254 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); |
| 1255 | if (!SA) |
| 1256 | return nullptr; |
| 1257 | |
| 1258 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV |
| 1259 | // subtraction is expensive. For this purpose, perform a quick and dirty |
| 1260 | // difference, by checking for Step in the operand list. |
| 1261 | SmallVector<const SCEV *, 4> DiffOps; |
| 1262 | for (const SCEV *Op : SA->operands()) |
| 1263 | if (Op != Step) |
| 1264 | DiffOps.push_back(Op); |
| 1265 | |
| 1266 | if (DiffOps.size() == SA->getNumOperands()) |
| 1267 | return nullptr; |
| 1268 | |
| 1269 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + |
| 1270 | // `Step`: |
| 1271 | |
| 1272 | // 1. NSW/NUW flags on the step increment. |
Sanjoy Das | 0714e3e | 2015-10-23 06:33:47 +0000 | [diff] [blame] | 1273 | auto PreStartFlags = |
| 1274 | ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); |
| 1275 | const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1276 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( |
| 1277 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); |
| 1278 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1279 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies |
| 1280 | // "S+X does not sign/unsign-overflow". |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1281 | // |
| 1282 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1283 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 1284 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && |
| 1285 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1286 | return PreStart; |
| 1287 | |
| 1288 | // 2. Direct overflow check on the step operation's expression. |
| 1289 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1290 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); |
| 1291 | const SCEV *OperandExtendedStart = |
| 1292 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), |
| 1293 | (SE->*GetExtendExpr)(Step, WideTy)); |
| 1294 | if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { |
| 1295 | if (PreAR && AR->getNoWrapFlags(WrapType)) { |
| 1296 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW |
| 1297 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then |
| 1298 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. |
| 1299 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); |
| 1300 | } |
| 1301 | return PreStart; |
| 1302 | } |
| 1303 | |
| 1304 | // 3. Loop precondition. |
| 1305 | ICmpInst::Predicate Pred; |
| 1306 | const SCEV *OverflowLimit = |
| 1307 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); |
| 1308 | |
| 1309 | if (OverflowLimit && |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1310 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1311 | return PreStart; |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1312 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1313 | return nullptr; |
| 1314 | } |
| 1315 | |
| 1316 | // Get the normalized zero or sign extended expression for this AddRec's Start. |
| 1317 | template <typename ExtendOpTy> |
| 1318 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, |
| 1319 | ScalarEvolution *SE) { |
| 1320 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1321 | |
| 1322 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); |
| 1323 | if (!PreStart) |
| 1324 | return (SE->*GetExtendExpr)(AR->getStart(), Ty); |
| 1325 | |
| 1326 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), |
| 1327 | (SE->*GetExtendExpr)(PreStart, Ty)); |
| 1328 | } |
| 1329 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1330 | // Try to prove away overflow by looking at "nearby" add recurrences. A |
| 1331 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it |
| 1332 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. |
| 1333 | // |
| 1334 | // Formally: |
| 1335 | // |
| 1336 | // {S,+,X} == {S-T,+,X} + T |
| 1337 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) |
| 1338 | // |
| 1339 | // If ({S-T,+,X} + T) does not overflow ... (1) |
| 1340 | // |
| 1341 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) |
| 1342 | // |
| 1343 | // If {S-T,+,X} does not overflow ... (2) |
| 1344 | // |
| 1345 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) |
| 1346 | // == {Ext(S-T)+Ext(T),+,Ext(X)} |
| 1347 | // |
| 1348 | // If (S-T)+T does not overflow ... (3) |
| 1349 | // |
| 1350 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} |
| 1351 | // == {Ext(S),+,Ext(X)} == LHS |
| 1352 | // |
| 1353 | // Thus, if (1), (2) and (3) are true for some T, then |
| 1354 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} |
| 1355 | // |
| 1356 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) |
| 1357 | // does not overflow" restricted to the 0th iteration. Therefore we only need |
| 1358 | // to check for (1) and (2). |
| 1359 | // |
| 1360 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T |
| 1361 | // is `Delta` (defined below). |
| 1362 | // |
| 1363 | template <typename ExtendOpTy> |
| 1364 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, |
| 1365 | const SCEV *Step, |
| 1366 | const Loop *L) { |
| 1367 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1368 | |
| 1369 | // We restrict `Start` to a constant to prevent SCEV from spending too much |
| 1370 | // time here. It is correct (but more expensive) to continue with a |
| 1371 | // non-constant `Start` and do a general SCEV subtraction to compute |
| 1372 | // `PreStart` below. |
| 1373 | // |
| 1374 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); |
| 1375 | if (!StartC) |
| 1376 | return false; |
| 1377 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1378 | APInt StartAI = StartC->getAPInt(); |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1379 | |
| 1380 | for (unsigned Delta : {-2, -1, 1, 2}) { |
| 1381 | const SCEV *PreStart = getConstant(StartAI - Delta); |
| 1382 | |
Sanjoy Das | 4280110 | 2015-10-23 06:57:21 +0000 | [diff] [blame] | 1383 | FoldingSetNodeID ID; |
| 1384 | ID.AddInteger(scAddRecExpr); |
| 1385 | ID.AddPointer(PreStart); |
| 1386 | ID.AddPointer(Step); |
| 1387 | ID.AddPointer(L); |
| 1388 | void *IP = nullptr; |
| 1389 | const auto *PreAR = |
| 1390 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 1391 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1392 | // Give up if we don't already have the add recurrence we need because |
| 1393 | // actually constructing an add recurrence is relatively expensive. |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1394 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) |
| 1395 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); |
| 1396 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 1397 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( |
| 1398 | DeltaS, &Pred, this); |
| 1399 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) |
| 1400 | return true; |
| 1401 | } |
| 1402 | } |
| 1403 | |
| 1404 | return false; |
| 1405 | } |
| 1406 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1407 | const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1408 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1409 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1410 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1411 | assert(isSCEVable(Ty) && |
| 1412 | "This is not a conversion to a SCEVable type!"); |
| 1413 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1414 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1415 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1416 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1417 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1418 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1419 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1420 | // zext(zext(x)) --> zext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1421 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1422 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1423 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1424 | // Before doing any expensive analysis, check to see if we've already |
| 1425 | // computed a SCEV for this Op and Ty. |
| 1426 | FoldingSetNodeID ID; |
| 1427 | ID.AddInteger(scZeroExtend); |
| 1428 | ID.AddPointer(Op); |
| 1429 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1430 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1431 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1432 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1433 | // zext(trunc(x)) --> zext(x) or x or trunc(x) |
| 1434 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1435 | // It's possible the bits taken off by the truncate were all zero bits. If |
| 1436 | // so, we should be able to simplify this further. |
| 1437 | const SCEV *X = ST->getOperand(); |
| 1438 | ConstantRange CR = getUnsignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1439 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1440 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1441 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1442 | CR.zextOrTrunc(NewBits))) |
| 1443 | return getTruncateOrZeroExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1444 | } |
| 1445 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1446 | // 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] | 1447 | // 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] | 1448 | // operands (often constants). This allows analysis of something like |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1449 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1450 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1451 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1452 | const SCEV *Start = AR->getStart(); |
| 1453 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1454 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1455 | const Loop *L = AR->getLoop(); |
| 1456 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1457 | if (!AR->hasNoUnsignedWrap()) { |
| 1458 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1459 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1460 | } |
| 1461 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1462 | // If we have special knowledge that this addrec won't overflow, |
| 1463 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1464 | if (AR->hasNoUnsignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1465 | return getAddRecExpr( |
| 1466 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1467 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1468 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1469 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1470 | // Note that this serves two purposes: It filters out loops that are |
| 1471 | // simply not analyzable, and it covers the case where this code is |
| 1472 | // being called from within backedge-taken count analysis, such that |
| 1473 | // attempting to ask for the backedge-taken count would likely result |
| 1474 | // in infinite recursion. In the later case, the analysis code will |
| 1475 | // cope with a conservative value, and it will take care to purge |
| 1476 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1477 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1478 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1479 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1480 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1481 | |
| 1482 | // Check whether the backedge-taken count can be losslessly casted to |
| 1483 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1484 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1485 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1486 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1487 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1488 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1489 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1490 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1491 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1492 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1493 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1494 | const SCEV *WideMaxBECount = |
| 1495 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1496 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1497 | getAddExpr(WideStart, |
| 1498 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1499 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1500 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1501 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1502 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1503 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1504 | return getAddRecExpr( |
| 1505 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1506 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1507 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1508 | // Similar to above, only this time treat the step value as signed. |
| 1509 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1510 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1511 | getAddExpr(WideStart, |
| 1512 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1513 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1514 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1515 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1516 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1517 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1518 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1519 | return getAddRecExpr( |
| 1520 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1521 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1522 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1523 | } |
| 1524 | |
| 1525 | // If the backedge is guarded by a comparison with the pre-inc value |
| 1526 | // the addrec is safe. Also, if the entry is guarded by a comparison |
| 1527 | // with the start value and the backedge is guarded by a comparison |
| 1528 | // with the post-inc value, the addrec is safe. |
| 1529 | if (isKnownPositive(Step)) { |
| 1530 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1531 | getUnsignedRange(Step).getUnsignedMax()); |
| 1532 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1533 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1534 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1535 | AR->getPostIncExpr(*this), N))) { |
| 1536 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1537 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1538 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1539 | return getAddRecExpr( |
| 1540 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1541 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1542 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1543 | } else if (isKnownNegative(Step)) { |
| 1544 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1545 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1546 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1547 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1548 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1549 | AR->getPostIncExpr(*this), N))) { |
| 1550 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1551 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1552 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1553 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1554 | return getAddRecExpr( |
| 1555 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1556 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1557 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1558 | } |
| 1559 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1560 | |
| 1561 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1562 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1563 | return getAddRecExpr( |
| 1564 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1565 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1566 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1567 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1568 | |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1569 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1570 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1571 | if (SA->hasNoUnsignedWrap()) { |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1572 | // If the addition does not unsign overflow then we can, by definition, |
| 1573 | // commute the zero extension with the addition operation. |
| 1574 | SmallVector<const SCEV *, 4> Ops; |
| 1575 | for (const auto *Op : SA->operands()) |
| 1576 | Ops.push_back(getZeroExtendExpr(Op, Ty)); |
| 1577 | return getAddExpr(Ops, SCEV::FlagNUW); |
| 1578 | } |
| 1579 | } |
| 1580 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1581 | // The cast wasn't folded; create an explicit cast node. |
| 1582 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1583 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1584 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1585 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1586 | UniqueSCEVs.InsertNode(S, IP); |
| 1587 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1588 | } |
| 1589 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1590 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1591 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1592 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1593 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1594 | assert(isSCEVable(Ty) && |
| 1595 | "This is not a conversion to a SCEVable type!"); |
| 1596 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1597 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1598 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1599 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1600 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1601 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1602 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1603 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1604 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1605 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1606 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1607 | // sext(zext(x)) --> zext(x) |
| 1608 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1609 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1610 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1611 | // Before doing any expensive analysis, check to see if we've already |
| 1612 | // computed a SCEV for this Op and Ty. |
| 1613 | FoldingSetNodeID ID; |
| 1614 | ID.AddInteger(scSignExtend); |
| 1615 | ID.AddPointer(Op); |
| 1616 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1617 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1618 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1619 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1620 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1621 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1622 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1623 | // so, we should be able to simplify this further. |
| 1624 | const SCEV *X = ST->getOperand(); |
| 1625 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1626 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1627 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1628 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1629 | CR.sextOrTrunc(NewBits))) |
| 1630 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1631 | } |
| 1632 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1633 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1634 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1635 | if (SA->getNumOperands() == 2) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1636 | auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1637 | auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1638 | if (SMul && SC1) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1639 | if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1640 | const APInt &C1 = SC1->getAPInt(); |
| 1641 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1642 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1643 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1644 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1645 | getSignExtendExpr(SMul, Ty)); |
| 1646 | } |
| 1647 | } |
| 1648 | } |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1649 | |
| 1650 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1651 | if (SA->hasNoSignedWrap()) { |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1652 | // If the addition does not sign overflow then we can, by definition, |
| 1653 | // commute the sign extension with the addition operation. |
| 1654 | SmallVector<const SCEV *, 4> Ops; |
| 1655 | for (const auto *Op : SA->operands()) |
| 1656 | Ops.push_back(getSignExtendExpr(Op, Ty)); |
| 1657 | return getAddExpr(Ops, SCEV::FlagNSW); |
| 1658 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1659 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1660 | // 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] | 1661 | // 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] | 1662 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1663 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1664 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1665 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1666 | const SCEV *Start = AR->getStart(); |
| 1667 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1668 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1669 | const Loop *L = AR->getLoop(); |
| 1670 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1671 | if (!AR->hasNoSignedWrap()) { |
| 1672 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1673 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1674 | } |
| 1675 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1676 | // If we have special knowledge that this addrec won't overflow, |
| 1677 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1678 | if (AR->hasNoSignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1679 | return getAddRecExpr( |
| 1680 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1681 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1682 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1683 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1684 | // Note that this serves two purposes: It filters out loops that are |
| 1685 | // simply not analyzable, and it covers the case where this code is |
| 1686 | // being called from within backedge-taken count analysis, such that |
| 1687 | // attempting to ask for the backedge-taken count would likely result |
| 1688 | // in infinite recursion. In the later case, the analysis code will |
| 1689 | // cope with a conservative value, and it will take care to purge |
| 1690 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1691 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1692 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1693 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1694 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1695 | |
| 1696 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1697 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1698 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1699 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1700 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1701 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1702 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1703 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1704 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1705 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1706 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1707 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1708 | const SCEV *WideMaxBECount = |
| 1709 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1710 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1711 | getAddExpr(WideStart, |
| 1712 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1713 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1714 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1715 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1716 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1717 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1718 | return getAddRecExpr( |
| 1719 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1720 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1721 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1722 | // Similar to above, only this time treat the step value as unsigned. |
| 1723 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1724 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1725 | getAddExpr(WideStart, |
| 1726 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1727 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1728 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1729 | // If AR wraps around then |
| 1730 | // |
| 1731 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1732 | // => SAdd != OperandExtendedAdd |
| 1733 | // |
| 1734 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1735 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1736 | |
| 1737 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1738 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1739 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1740 | return getAddRecExpr( |
| 1741 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1742 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1743 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1744 | } |
| 1745 | |
| 1746 | // If the backedge is guarded by a comparison with the pre-inc value |
| 1747 | // the addrec is safe. Also, if the entry is guarded by a comparison |
| 1748 | // with the start value and the backedge is guarded by a comparison |
| 1749 | // with the post-inc value, the addrec is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1750 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1751 | const SCEV *OverflowLimit = |
| 1752 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1753 | if (OverflowLimit && |
| 1754 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1755 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1756 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1757 | OverflowLimit)))) { |
| 1758 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1759 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1760 | return getAddRecExpr( |
| 1761 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1762 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1763 | } |
| 1764 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1765 | // If Start and Step are constants, check if we can apply this |
| 1766 | // transformation: |
| 1767 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1768 | auto *SC1 = dyn_cast<SCEVConstant>(Start); |
| 1769 | auto *SC2 = dyn_cast<SCEVConstant>(Step); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1770 | if (SC1 && SC2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1771 | const APInt &C1 = SC1->getAPInt(); |
| 1772 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1773 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1774 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1775 | Start = getSignExtendExpr(Start, Ty); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1776 | const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, |
| 1777 | AR->getNoWrapFlags()); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1778 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1779 | } |
| 1780 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1781 | |
| 1782 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1783 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1784 | return getAddRecExpr( |
| 1785 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1786 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1787 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1788 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1789 | |
Sanjoy Das | 11ef606 | 2016-03-03 18:31:23 +0000 | [diff] [blame] | 1790 | // If the input value is provably positive and we could not simplify |
| 1791 | // away the sext build a zext instead. |
| 1792 | if (isKnownNonNegative(Op)) |
| 1793 | return getZeroExtendExpr(Op, Ty); |
| 1794 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1795 | // The cast wasn't folded; create an explicit cast node. |
| 1796 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1797 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1798 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1799 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1800 | UniqueSCEVs.InsertNode(S, IP); |
| 1801 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1802 | } |
| 1803 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1804 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1805 | /// unspecified bits out to the given type. |
| 1806 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1807 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1808 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1809 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1810 | "This is not an extending conversion!"); |
| 1811 | assert(isSCEVable(Ty) && |
| 1812 | "This is not a conversion to a SCEVable type!"); |
| 1813 | Ty = getEffectiveSCEVType(Ty); |
| 1814 | |
| 1815 | // Sign-extend negative constants. |
| 1816 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1817 | if (SC->getAPInt().isNegative()) |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1818 | return getSignExtendExpr(Op, Ty); |
| 1819 | |
| 1820 | // Peel off a truncate cast. |
| 1821 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1822 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1823 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1824 | return getAnyExtendExpr(NewOp, Ty); |
| 1825 | return getTruncateOrNoop(NewOp, Ty); |
| 1826 | } |
| 1827 | |
| 1828 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1829 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1830 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1831 | return ZExt; |
| 1832 | |
| 1833 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1834 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1835 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1836 | return SExt; |
| 1837 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1838 | // Force the cast to be folded into the operands of an addrec. |
| 1839 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1840 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1841 | for (const SCEV *Op : AR->operands()) |
| 1842 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1843 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1844 | } |
| 1845 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1846 | // If the expression is obviously signed, use the sext cast value. |
| 1847 | if (isa<SCEVSMaxExpr>(Op)) |
| 1848 | return SExt; |
| 1849 | |
| 1850 | // Absent any other information, use the zext cast value. |
| 1851 | return ZExt; |
| 1852 | } |
| 1853 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1854 | /// CollectAddOperandsWithScales - Process the given Ops list, which is |
| 1855 | /// a list of operands to be added under the given scale, update the given |
| 1856 | /// map. This is a helper function for getAddRecExpr. As an example of |
| 1857 | /// what it does, given a sequence of operands that would form an add |
| 1858 | /// expression like this: |
| 1859 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1860 | /// 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] | 1861 | /// |
| 1862 | /// where A and B are constants, update the map with these values: |
| 1863 | /// |
| 1864 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1865 | /// |
| 1866 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1867 | /// This will allow getAddRecExpr to produce this: |
| 1868 | /// |
| 1869 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1870 | /// |
| 1871 | /// This form often exposes folding opportunities that are hidden in |
| 1872 | /// the original operand list. |
| 1873 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1874 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1875 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1876 | /// the common case where no interesting opportunities are present, and |
| 1877 | /// is also used as a check to avoid infinite recursion. |
| 1878 | /// |
| 1879 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1880 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1881 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1882 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1883 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1884 | const APInt &Scale, |
| 1885 | ScalarEvolution &SE) { |
| 1886 | bool Interesting = false; |
| 1887 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1888 | // Iterate over the add operands. They are sorted, with constants first. |
| 1889 | unsigned i = 0; |
| 1890 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1891 | ++i; |
| 1892 | // Pull a buried constant out to the outside. |
| 1893 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1894 | Interesting = true; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1895 | AccumulatedConstant += Scale * C->getAPInt(); |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1896 | } |
| 1897 | |
| 1898 | // Next comes everything else. We're especially interested in multiplies |
| 1899 | // here, but they're in the middle, so just visit the rest with one loop. |
| 1900 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1901 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 1902 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 1903 | APInt NewScale = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1904 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1905 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 1906 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1907 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1908 | Interesting |= |
| 1909 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1910 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1911 | NewScale, SE); |
| 1912 | } else { |
| 1913 | // A multiplication of a constant with some other value. Update |
| 1914 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1915 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 1916 | const SCEV *Key = SE.getMulExpr(MulOps); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1917 | auto Pair = M.insert({Key, NewScale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1918 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1919 | NewOps.push_back(Pair.first->first); |
| 1920 | } else { |
| 1921 | Pair.first->second += NewScale; |
| 1922 | // The map already had an entry for this value, which may indicate |
| 1923 | // a folding opportunity. |
| 1924 | Interesting = true; |
| 1925 | } |
| 1926 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1927 | } else { |
| 1928 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1929 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1930 | M.insert({Ops[i], Scale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1931 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1932 | NewOps.push_back(Pair.first->first); |
| 1933 | } else { |
| 1934 | Pair.first->second += Scale; |
| 1935 | // The map already had an entry for this value, which may indicate |
| 1936 | // a folding opportunity. |
| 1937 | Interesting = true; |
| 1938 | } |
| 1939 | } |
| 1940 | } |
| 1941 | |
| 1942 | return Interesting; |
| 1943 | } |
| 1944 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1945 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 1946 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 1947 | // can't-overflow flags for the operation if possible. |
| 1948 | static SCEV::NoWrapFlags |
| 1949 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 1950 | const SmallVectorImpl<const SCEV *> &Ops, |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1951 | SCEV::NoWrapFlags Flags) { |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1952 | using namespace std::placeholders; |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1953 | typedef OverflowingBinaryOperator OBO; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1954 | |
| 1955 | bool CanAnalyze = |
| 1956 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 1957 | (void)CanAnalyze; |
| 1958 | assert(CanAnalyze && "don't call from other places!"); |
| 1959 | |
| 1960 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 1961 | SCEV::NoWrapFlags SignOrUnsignWrap = |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1962 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1963 | |
| 1964 | // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. |
Sanjoy Das | 9b0015f | 2015-11-29 23:40:57 +0000 | [diff] [blame] | 1965 | auto IsKnownNonNegative = [&](const SCEV *S) { |
| 1966 | return SE->isKnownNonNegative(S); |
| 1967 | }; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1968 | |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 1969 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1970 | Flags = |
| 1971 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1972 | |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1973 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
| 1974 | |
| 1975 | if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && |
| 1976 | Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { |
| 1977 | |
| 1978 | // (A + C) --> (A + C)<nsw> if the addition does not sign overflow |
| 1979 | // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow |
| 1980 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1981 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1982 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 1983 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 1984 | Instruction::Add, C, OBO::NoSignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1985 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) |
| 1986 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 1987 | } |
| 1988 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 1989 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 1990 | Instruction::Add, C, OBO::NoUnsignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1991 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) |
| 1992 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 1993 | } |
| 1994 | } |
| 1995 | |
| 1996 | return Flags; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1997 | } |
| 1998 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 1999 | /// getAddExpr - Get a canonical add expression, or something simpler if |
| 2000 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2001 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2002 | SCEV::NoWrapFlags Flags) { |
| 2003 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 2004 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2005 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2006 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2007 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2008 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2009 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 2010 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2011 | "SCEVAddExpr operand types don't match!"); |
| 2012 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2013 | |
| 2014 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2015 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2016 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2017 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
| 2018 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2019 | // If there are any constants, fold them together. |
| 2020 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2021 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2022 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2023 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2024 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2025 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2026 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 2027 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2028 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2029 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2030 | } |
| 2031 | |
| 2032 | // 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] | 2033 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2034 | Ops.erase(Ops.begin()); |
| 2035 | --Idx; |
| 2036 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2037 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2038 | if (Ops.size() == 1) return Ops[0]; |
| 2039 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2040 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2041 | // Okay, check to see if the same value occurs in the operand list more than |
| 2042 | // once. If so, merge them together into an multiply expression. Since we |
| 2043 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2044 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2045 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2046 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2047 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2048 | // Scan ahead to count how many equal operands there are. |
| 2049 | unsigned Count = 2; |
| 2050 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2051 | ++Count; |
| 2052 | // Merge the values into a multiply. |
| 2053 | const SCEV *Scale = getConstant(Ty, Count); |
| 2054 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2055 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2056 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2057 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2058 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2059 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2060 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2061 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2062 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2063 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2064 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2065 | // Check for truncates. If all the operands are truncated from the same |
| 2066 | // type, see if factoring out the truncate would permit the result to be |
| 2067 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2068 | // if the contents of the resulting outer trunc fold to something simple. |
| 2069 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2070 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2071 | Type *DstType = Trunc->getType(); |
| 2072 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2073 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2074 | bool Ok = true; |
| 2075 | // Check all the operands to see if they can be represented in the |
| 2076 | // source type of the truncate. |
| 2077 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2078 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2079 | if (T->getOperand()->getType() != SrcType) { |
| 2080 | Ok = false; |
| 2081 | break; |
| 2082 | } |
| 2083 | LargeOps.push_back(T->getOperand()); |
| 2084 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2085 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2086 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2087 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2088 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2089 | if (const SCEVTruncateExpr *T = |
| 2090 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2091 | if (T->getOperand()->getType() != SrcType) { |
| 2092 | Ok = false; |
| 2093 | break; |
| 2094 | } |
| 2095 | LargeMulOps.push_back(T->getOperand()); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2096 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2097 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2098 | } else { |
| 2099 | Ok = false; |
| 2100 | break; |
| 2101 | } |
| 2102 | } |
| 2103 | if (Ok) |
| 2104 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2105 | } else { |
| 2106 | Ok = false; |
| 2107 | break; |
| 2108 | } |
| 2109 | } |
| 2110 | if (Ok) { |
| 2111 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2112 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2113 | // If it folds to something simple, use it. Otherwise, don't. |
| 2114 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2115 | return getTruncateExpr(Fold, DstType); |
| 2116 | } |
| 2117 | } |
| 2118 | |
| 2119 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2120 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2121 | ++Idx; |
| 2122 | |
| 2123 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2124 | if (Idx < Ops.size()) { |
| 2125 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2126 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2127 | // If we have an add, expand the add operands onto the end of the operands |
| 2128 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2129 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2130 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2131 | DeletedAdd = true; |
| 2132 | } |
| 2133 | |
| 2134 | // If we deleted at least one add, we added operands to the end of the list, |
| 2135 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2136 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2137 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2138 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2139 | } |
| 2140 | |
| 2141 | // Skip over the add expression until we get to a multiply. |
| 2142 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2143 | ++Idx; |
| 2144 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2145 | // Check to see if there are any folding opportunities present with |
| 2146 | // operands multiplied by constant values. |
| 2147 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2148 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2149 | DenseMap<const SCEV *, APInt> M; |
| 2150 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2151 | APInt AccumulatedConstant(BitWidth, 0); |
| 2152 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2153 | Ops.data(), Ops.size(), |
| 2154 | APInt(BitWidth, 1), *this)) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 2155 | struct APIntCompare { |
| 2156 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 2157 | return LHS.ult(RHS); |
| 2158 | } |
| 2159 | }; |
| 2160 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2161 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2162 | // re-generate the operands list. Group the operands by constant scale, |
| 2163 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2164 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2165 | for (const SCEV *NewOp : NewOps) |
| 2166 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2167 | // Re-generate the operands list. |
| 2168 | Ops.clear(); |
| 2169 | if (AccumulatedConstant != 0) |
| 2170 | Ops.push_back(getConstant(AccumulatedConstant)); |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2171 | for (auto &MulOp : MulOpLists) |
| 2172 | if (MulOp.first != 0) |
| 2173 | Ops.push_back(getMulExpr(getConstant(MulOp.first), |
| 2174 | getAddExpr(MulOp.second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2175 | if (Ops.empty()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2176 | return getZero(Ty); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2177 | if (Ops.size() == 1) |
| 2178 | return Ops[0]; |
| 2179 | return getAddExpr(Ops); |
| 2180 | } |
| 2181 | } |
| 2182 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2183 | // If we are adding something to a multiply expression, make sure the |
| 2184 | // something is not already an operand of the multiply. If so, merge it into |
| 2185 | // the multiply. |
| 2186 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2187 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2188 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2189 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2190 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2191 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2192 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2193 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2194 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2195 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2196 | if (Mul->getNumOperands() != 2) { |
| 2197 | // If the multiply has more than two operands, we must get the |
| 2198 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2199 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2200 | Mul->op_begin()+MulOp); |
| 2201 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2202 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2203 | } |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2204 | const SCEV *One = getOne(Ty); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2205 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2206 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2207 | if (Ops.size() == 2) return OuterMul; |
| 2208 | if (AddOp < Idx) { |
| 2209 | Ops.erase(Ops.begin()+AddOp); |
| 2210 | Ops.erase(Ops.begin()+Idx-1); |
| 2211 | } else { |
| 2212 | Ops.erase(Ops.begin()+Idx); |
| 2213 | Ops.erase(Ops.begin()+AddOp-1); |
| 2214 | } |
| 2215 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2216 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2217 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2218 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2219 | // Check this multiply against other multiplies being added together. |
| 2220 | for (unsigned OtherMulIdx = Idx+1; |
| 2221 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2222 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2223 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2224 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2225 | // together. |
| 2226 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2227 | OMulOp != e; ++OMulOp) |
| 2228 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2229 | // 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] | 2230 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2231 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2232 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2233 | Mul->op_begin()+MulOp); |
| 2234 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2235 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2236 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2237 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2238 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2239 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2240 | OtherMul->op_begin()+OMulOp); |
| 2241 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2242 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2243 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2244 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2245 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2246 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2247 | Ops.erase(Ops.begin()+Idx); |
| 2248 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2249 | Ops.push_back(OuterMul); |
| 2250 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2251 | } |
| 2252 | } |
| 2253 | } |
| 2254 | } |
| 2255 | |
| 2256 | // If there are any add recurrences in the operands list, see if any other |
| 2257 | // added values are loop invariant. If so, we can fold them into the |
| 2258 | // recurrence. |
| 2259 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2260 | ++Idx; |
| 2261 | |
| 2262 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2263 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2264 | // Scan all of the other operands to this add and add them to the vector if |
| 2265 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2266 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2267 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2268 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2269 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2270 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2271 | LIOps.push_back(Ops[i]); |
| 2272 | Ops.erase(Ops.begin()+i); |
| 2273 | --i; --e; |
| 2274 | } |
| 2275 | |
| 2276 | // If we found some loop invariants, fold them into the recurrence. |
| 2277 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2278 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2279 | LIOps.push_back(AddRec->getStart()); |
| 2280 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2281 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2282 | AddRec->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2283 | AddRecOps[0] = getAddExpr(LIOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2284 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2285 | // 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] | 2286 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2287 | // Always propagate NW. |
| 2288 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2289 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2290 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2291 | // If all of the other operands were loop invariant, we are done. |
| 2292 | if (Ops.size() == 1) return NewRec; |
| 2293 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2294 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2295 | for (unsigned i = 0;; ++i) |
| 2296 | if (Ops[i] == AddRec) { |
| 2297 | Ops[i] = NewRec; |
| 2298 | break; |
| 2299 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2300 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2301 | } |
| 2302 | |
| 2303 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2304 | // there are multiple AddRec's with the same loop induction variable being |
| 2305 | // added together. If so, we can fold them. |
| 2306 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2307 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2308 | ++OtherIdx) |
| 2309 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2310 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2311 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2312 | AddRec->op_end()); |
| 2313 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2314 | ++OtherIdx) |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2315 | if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2316 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2317 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2318 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2319 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2320 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2321 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2322 | break; |
| 2323 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2324 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2325 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2326 | } |
| 2327 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2328 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2329 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2330 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2331 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2332 | } |
| 2333 | |
| 2334 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2335 | // next one. |
| 2336 | } |
| 2337 | |
| 2338 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2339 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2340 | FoldingSetNodeID ID; |
| 2341 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2342 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2343 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2344 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2345 | SCEVAddExpr *S = |
| 2346 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2347 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2348 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2349 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2350 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2351 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2352 | UniqueSCEVs.InsertNode(S, IP); |
| 2353 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2354 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2355 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2356 | } |
| 2357 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2358 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2359 | uint64_t k = i*j; |
| 2360 | if (j > 1 && k / j != i) Overflow = true; |
| 2361 | return k; |
| 2362 | } |
| 2363 | |
| 2364 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2365 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2366 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2367 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2368 | // We use the multiplicative formula: |
| 2369 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2370 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2371 | // (k-n)th term of the denominator. This division will always produce an |
| 2372 | // integral result, and helps reduce the chance of overflow in the |
| 2373 | // intermediate computations. However, we can still overflow even when the |
| 2374 | // final result would fit. |
| 2375 | |
| 2376 | if (n == 0 || n == k) return 1; |
| 2377 | if (k > n) return 0; |
| 2378 | |
| 2379 | if (k > n/2) |
| 2380 | k = n-k; |
| 2381 | |
| 2382 | uint64_t r = 1; |
| 2383 | for (uint64_t i = 1; i <= k; ++i) { |
| 2384 | r = umul_ov(r, n-(i-1), Overflow); |
| 2385 | r /= i; |
| 2386 | } |
| 2387 | return r; |
| 2388 | } |
| 2389 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2390 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2391 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2392 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2393 | SmallVector<const SCEV *, 4> Ops; |
| 2394 | Ops.push_back(StartExpr); |
| 2395 | while (!Ops.empty()) { |
| 2396 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2397 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2398 | return true; |
| 2399 | |
| 2400 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2401 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2402 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2403 | } |
| 2404 | } |
| 2405 | return false; |
| 2406 | } |
| 2407 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2408 | /// getMulExpr - Get a canonical multiply expression, or something simpler if |
| 2409 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2410 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2411 | SCEV::NoWrapFlags Flags) { |
| 2412 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2413 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2414 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2415 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2416 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2417 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2418 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2419 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2420 | "SCEVMulExpr operand types don't match!"); |
| 2421 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2422 | |
| 2423 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2424 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2425 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2426 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
| 2427 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2428 | // If there are any constants, fold them together. |
| 2429 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2430 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2431 | |
| 2432 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2433 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2434 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2435 | // If any of Add's ops are Adds or Muls with a constant, |
| 2436 | // apply this transformation as well. |
| 2437 | if (Add->getNumOperands() == 2) |
| 2438 | if (containsConstantSomewhere(Add)) |
| 2439 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2440 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2441 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2442 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2443 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2444 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2445 | ConstantInt *Fold = |
| 2446 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2447 | Ops[0] = getConstant(Fold); |
| 2448 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2449 | if (Ops.size() == 1) return Ops[0]; |
| 2450 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2451 | } |
| 2452 | |
| 2453 | // If we are left with a constant one being multiplied, strip it off. |
| 2454 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2455 | Ops.erase(Ops.begin()); |
| 2456 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2457 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2458 | // If we have a multiply of zero, it will always be zero. |
| 2459 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2460 | } else if (Ops[0]->isAllOnesValue()) { |
| 2461 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2462 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2463 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2464 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2465 | SmallVector<const SCEV *, 4> NewOps; |
| 2466 | bool AnyFolded = false; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2467 | for (const SCEV *AddOp : Add->operands()) { |
| 2468 | const SCEV *Mul = getMulExpr(Ops[0], AddOp); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2469 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2470 | NewOps.push_back(Mul); |
| 2471 | } |
| 2472 | if (AnyFolded) |
| 2473 | return getAddExpr(NewOps); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2474 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2475 | // Negation preserves a recurrence's no self-wrap property. |
| 2476 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2477 | for (const SCEV *AddRecOp : AddRec->operands()) |
| 2478 | Operands.push_back(getMulExpr(Ops[0], AddRecOp)); |
| 2479 | |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2480 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2481 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2482 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2483 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2484 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2485 | |
| 2486 | if (Ops.size() == 1) |
| 2487 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2488 | } |
| 2489 | |
| 2490 | // Skip over the add expression until we get to a multiply. |
| 2491 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2492 | ++Idx; |
| 2493 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2494 | // If there are mul operands inline them all into this expression. |
| 2495 | if (Idx < Ops.size()) { |
| 2496 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2497 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2498 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2499 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2500 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2501 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2502 | DeletedMul = true; |
| 2503 | } |
| 2504 | |
| 2505 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2506 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2507 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2508 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2509 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2510 | } |
| 2511 | |
| 2512 | // If there are any add recurrences in the operands list, see if any other |
| 2513 | // added values are loop invariant. If so, we can fold them into the |
| 2514 | // recurrence. |
| 2515 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2516 | ++Idx; |
| 2517 | |
| 2518 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2519 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2520 | // Scan all of the other operands to this mul and add them to the vector if |
| 2521 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2522 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2523 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2524 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2525 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2526 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2527 | LIOps.push_back(Ops[i]); |
| 2528 | Ops.erase(Ops.begin()+i); |
| 2529 | --i; --e; |
| 2530 | } |
| 2531 | |
| 2532 | // If we found some loop invariants, fold them into the recurrence. |
| 2533 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2534 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2535 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2536 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2537 | const SCEV *Scale = getMulExpr(LIOps); |
| 2538 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2539 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2540 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2541 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2542 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2543 | // |
| 2544 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2545 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2546 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2547 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2548 | |
| 2549 | // If all of the other operands were loop invariant, we are done. |
| 2550 | if (Ops.size() == 1) return NewRec; |
| 2551 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2552 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2553 | for (unsigned i = 0;; ++i) |
| 2554 | if (Ops[i] == AddRec) { |
| 2555 | Ops[i] = NewRec; |
| 2556 | break; |
| 2557 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2558 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2559 | } |
| 2560 | |
| 2561 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2562 | // there are multiple AddRec's with the same loop induction variable being |
| 2563 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2564 | |
| 2565 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2566 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2567 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2568 | // ]]],+,...up to x=2n}. |
| 2569 | // Note that the arguments to choose() are always integers with values |
| 2570 | // known at compile time, never SCEV objects. |
| 2571 | // |
| 2572 | // The implementation avoids pointless extra computations when the two |
| 2573 | // addrec's are of different length (mathematically, it's equivalent to |
| 2574 | // an infinite stream of zeros on the right). |
| 2575 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2576 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2577 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2578 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2579 | const SCEVAddRecExpr *OtherAddRec = |
| 2580 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2581 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2582 | continue; |
| 2583 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2584 | bool Overflow = false; |
| 2585 | Type *Ty = AddRec->getType(); |
| 2586 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2587 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2588 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2589 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2590 | const SCEV *Term = getZero(Ty); |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2591 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2592 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2593 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2594 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2595 | z < ze && !Overflow; ++z) { |
| 2596 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2597 | uint64_t Coeff; |
| 2598 | if (LargerThan64Bits) |
| 2599 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2600 | else |
| 2601 | Coeff = Coeff1*Coeff2; |
| 2602 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2603 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2604 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2605 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2606 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2607 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2608 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2609 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2610 | if (!Overflow) { |
| 2611 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2612 | SCEV::FlagAnyWrap); |
| 2613 | if (Ops.size() == 2) return NewAddRec; |
| 2614 | Ops[Idx] = NewAddRec; |
| 2615 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2616 | OpsModified = true; |
| 2617 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2618 | if (!AddRec) |
| 2619 | break; |
| 2620 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2621 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2622 | if (OpsModified) |
| 2623 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2624 | |
| 2625 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2626 | // next one. |
| 2627 | } |
| 2628 | |
| 2629 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2630 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2631 | FoldingSetNodeID ID; |
| 2632 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2633 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2634 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2635 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2636 | SCEVMulExpr *S = |
| 2637 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2638 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2639 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2640 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2641 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2642 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2643 | UniqueSCEVs.InsertNode(S, IP); |
| 2644 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2645 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2646 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2647 | } |
| 2648 | |
Andreas Bolka | 7a5c8db | 2009-08-07 22:55:26 +0000 | [diff] [blame] | 2649 | /// getUDivExpr - Get a canonical unsigned division expression, or something |
| 2650 | /// simpler if possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2651 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2652 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2653 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2654 | getEffectiveSCEVType(RHS->getType()) && |
| 2655 | "SCEVUDivExpr operand types don't match!"); |
| 2656 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2657 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2658 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2659 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2660 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2661 | // try to analyze it, because the resolution chosen here may differ from |
| 2662 | // the resolution chosen in other parts of the compiler. |
| 2663 | if (!RHSC->getValue()->isZero()) { |
| 2664 | // Determine if the division can be folded into the operands of |
| 2665 | // its operands. |
| 2666 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2667 | Type *Ty = LHS->getType(); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2668 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2669 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2670 | // For non-power-of-two values, effectively round the value up to the |
| 2671 | // nearest power of two. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2672 | if (!RHSC->getAPInt().isPowerOf2()) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2673 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2674 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2675 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2676 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2677 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2678 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2679 | // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2680 | const APInt &StepInt = Step->getAPInt(); |
| 2681 | const APInt &DivInt = RHSC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2682 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2683 | getZeroExtendExpr(AR, ExtTy) == |
| 2684 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2685 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2686 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2687 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2688 | for (const SCEV *Op : AR->operands()) |
| 2689 | Operands.push_back(getUDivExpr(Op, RHS)); |
| 2690 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2691 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2692 | /// Get a canonical UDivExpr for a recurrence. |
| 2693 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2694 | // We can currently only fold X%N if X is constant. |
| 2695 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2696 | if (StartC && !DivInt.urem(StepInt) && |
| 2697 | getZeroExtendExpr(AR, ExtTy) == |
| 2698 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2699 | getZeroExtendExpr(Step, ExtTy), |
| 2700 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2701 | const APInt &StartInt = StartC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2702 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2703 | if (StartRem != 0) |
| 2704 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2705 | AR->getLoop(), SCEV::FlagNW); |
| 2706 | } |
| 2707 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2708 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2709 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2710 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2711 | for (const SCEV *Op : M->operands()) |
| 2712 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2713 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2714 | // Find an operand that's safely divisible. |
| 2715 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2716 | const SCEV *Op = M->getOperand(i); |
| 2717 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2718 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2719 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2720 | M->op_end()); |
| 2721 | Operands[i] = Div; |
| 2722 | return getMulExpr(Operands); |
| 2723 | } |
| 2724 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2725 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2726 | // (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] | 2727 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2728 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2729 | for (const SCEV *Op : A->operands()) |
| 2730 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2731 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2732 | Operands.clear(); |
| 2733 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2734 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2735 | if (isa<SCEVUDivExpr>(Op) || |
| 2736 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2737 | break; |
| 2738 | Operands.push_back(Op); |
| 2739 | } |
| 2740 | if (Operands.size() == A->getNumOperands()) |
| 2741 | return getAddExpr(Operands); |
| 2742 | } |
| 2743 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2744 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2745 | // Fold if both operands are constant. |
| 2746 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2747 | Constant *LHSCV = LHSC->getValue(); |
| 2748 | Constant *RHSCV = RHSC->getValue(); |
| 2749 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2750 | RHSCV))); |
| 2751 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2752 | } |
| 2753 | } |
| 2754 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2755 | FoldingSetNodeID ID; |
| 2756 | ID.AddInteger(scUDivExpr); |
| 2757 | ID.AddPointer(LHS); |
| 2758 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2759 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2760 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2761 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2762 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2763 | UniqueSCEVs.InsertNode(S, IP); |
| 2764 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2765 | } |
| 2766 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2767 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2768 | APInt A = C1->getAPInt().abs(); |
| 2769 | APInt B = C2->getAPInt().abs(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2770 | uint32_t ABW = A.getBitWidth(); |
| 2771 | uint32_t BBW = B.getBitWidth(); |
| 2772 | |
| 2773 | if (ABW > BBW) |
| 2774 | B = B.zext(ABW); |
| 2775 | else if (ABW < BBW) |
| 2776 | A = A.zext(BBW); |
| 2777 | |
| 2778 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2779 | } |
| 2780 | |
| 2781 | /// getUDivExactExpr - Get a canonical unsigned division expression, or |
| 2782 | /// something simpler if possible. There is no representation for an exact udiv |
| 2783 | /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS. |
| 2784 | /// We can't do this when it's not exact because the udiv may be clearing bits. |
| 2785 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2786 | const SCEV *RHS) { |
| 2787 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2788 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2789 | // end of this file for inspiration. |
| 2790 | |
| 2791 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2792 | if (!Mul) |
| 2793 | return getUDivExpr(LHS, RHS); |
| 2794 | |
| 2795 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2796 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2797 | // first element of the mulexpr. |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2798 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2799 | if (LHSCst == RHSCst) { |
| 2800 | SmallVector<const SCEV *, 2> Operands; |
| 2801 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2802 | return getMulExpr(Operands); |
| 2803 | } |
| 2804 | |
| 2805 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2806 | // that there's a factor provided by one of the other terms. We need to |
| 2807 | // check. |
| 2808 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2809 | if (!Factor.isIntN(1)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2810 | LHSCst = |
| 2811 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); |
| 2812 | RHSCst = |
| 2813 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2814 | SmallVector<const SCEV *, 2> Operands; |
| 2815 | Operands.push_back(LHSCst); |
| 2816 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2817 | LHS = getMulExpr(Operands); |
| 2818 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2819 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2820 | if (!Mul) |
| 2821 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2822 | } |
| 2823 | } |
| 2824 | } |
| 2825 | |
| 2826 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2827 | if (Mul->getOperand(i) == RHS) { |
| 2828 | SmallVector<const SCEV *, 2> Operands; |
| 2829 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2830 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2831 | return getMulExpr(Operands); |
| 2832 | } |
| 2833 | } |
| 2834 | |
| 2835 | return getUDivExpr(LHS, RHS); |
| 2836 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2837 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2838 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2839 | /// Simplify the expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2840 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2841 | const Loop *L, |
| 2842 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2843 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2844 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2845 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2846 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2847 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2848 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2849 | } |
| 2850 | |
| 2851 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2852 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2853 | } |
| 2854 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2855 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2856 | /// Simplify the expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2857 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2858 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2859 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2860 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2861 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2862 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2863 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2864 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2865 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2866 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2867 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2868 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2869 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2870 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2871 | if (Operands.back()->isZero()) { |
| 2872 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2873 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2874 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2875 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2876 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2877 | // use that information to infer NUW and NSW flags. However, computing a |
| 2878 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2879 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2880 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2881 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2882 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2883 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2884 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2885 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2886 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2887 | if (L->contains(NestedLoop) |
| 2888 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2889 | : (!NestedLoop->contains(L) && |
| 2890 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2891 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2892 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2893 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2894 | // AddRecs require their operands be loop-invariant with respect to their |
| 2895 | // loops. Don't perform this transformation if it would break this |
| 2896 | // requirement. |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2897 | bool AllInvariant = all_of( |
| 2898 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2899 | |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2900 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2901 | // Create a recurrence for the outer loop with the same step size. |
| 2902 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2903 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 2904 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2905 | SCEV::NoWrapFlags OuterFlags = |
| 2906 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2907 | |
| 2908 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2909 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { |
| 2910 | return isLoopInvariant(Op, NestedLoop); |
| 2911 | }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2912 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2913 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2914 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2915 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2916 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 2917 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2918 | SCEV::NoWrapFlags InnerFlags = |
| 2919 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2920 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 2921 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2922 | } |
| 2923 | // Reset Operands to its original state. |
| 2924 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2925 | } |
| 2926 | } |
| 2927 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 2928 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 2929 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2930 | FoldingSetNodeID ID; |
| 2931 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2932 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 2933 | ID.AddPointer(Operands[i]); |
| 2934 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2935 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2936 | SCEVAddRecExpr *S = |
| 2937 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2938 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2939 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 2940 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2941 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 2942 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2943 | UniqueSCEVs.InsertNode(S, IP); |
| 2944 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2945 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2946 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2947 | } |
| 2948 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2949 | const SCEV * |
| 2950 | ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, |
| 2951 | const SmallVectorImpl<const SCEV *> &IndexExprs, |
| 2952 | bool InBounds) { |
| 2953 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 2954 | // because SCEV::getType() preserves the address space. |
| 2955 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 2956 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 2957 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 2958 | // 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] | 2959 | // context. This can be fixed similarly to how these flags are handled for |
| 2960 | // adds. |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2961 | SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 2962 | |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2963 | const SCEV *TotalOffset = getZero(IntPtrTy); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2964 | // The address space is unimportant. The first thing we do on CurTy is getting |
| 2965 | // its element type. |
| 2966 | Type *CurTy = PointerType::getUnqual(PointeeType); |
| 2967 | for (const SCEV *IndexExpr : IndexExprs) { |
| 2968 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 2969 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 2970 | // For a struct, add the member offset. |
| 2971 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 2972 | unsigned FieldNo = Index->getZExtValue(); |
| 2973 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 2974 | |
| 2975 | // Add the field offset to the running total offset. |
| 2976 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 2977 | |
| 2978 | // Update CurTy to the type of the field at Index. |
| 2979 | CurTy = STy->getTypeAtIndex(Index); |
| 2980 | } else { |
| 2981 | // Update CurTy to its element type. |
| 2982 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 2983 | // For an array, add the element offset, explicitly scaled. |
| 2984 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 2985 | // Getelementptr indices are signed. |
| 2986 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 2987 | |
| 2988 | // Multiply the index by the element size to compute the element offset. |
| 2989 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 2990 | |
| 2991 | // Add the element offset to the running total offset. |
| 2992 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 2993 | } |
| 2994 | } |
| 2995 | |
| 2996 | // Add the total offset from all the GEP indices to the base. |
| 2997 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 2998 | } |
| 2999 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3000 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 3001 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3002 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3003 | Ops.push_back(LHS); |
| 3004 | Ops.push_back(RHS); |
| 3005 | return getSMaxExpr(Ops); |
| 3006 | } |
| 3007 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3008 | const SCEV * |
| 3009 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3010 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 3011 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3012 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3013 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3014 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3015 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3016 | "SCEVSMaxExpr operand types don't match!"); |
| 3017 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3018 | |
| 3019 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3020 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3021 | |
| 3022 | // If there are any constants, fold them together. |
| 3023 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3024 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3025 | ++Idx; |
| 3026 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3027 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3028 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3029 | ConstantInt *Fold = ConstantInt::get( |
| 3030 | getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3031 | Ops[0] = getConstant(Fold); |
| 3032 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3033 | if (Ops.size() == 1) return Ops[0]; |
| 3034 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3035 | } |
| 3036 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3037 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3038 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3039 | Ops.erase(Ops.begin()); |
| 3040 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3041 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3042 | // If we have an smax with a constant maximum-int, it will always be |
| 3043 | // maximum-int. |
| 3044 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3045 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3046 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3047 | if (Ops.size() == 1) return Ops[0]; |
| 3048 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3049 | |
| 3050 | // Find the first SMax |
| 3051 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3052 | ++Idx; |
| 3053 | |
| 3054 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3055 | // onto our operand list, and recurse to simplify. |
| 3056 | if (Idx < Ops.size()) { |
| 3057 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3058 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3059 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3060 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3061 | DeletedSMax = true; |
| 3062 | } |
| 3063 | |
| 3064 | if (DeletedSMax) |
| 3065 | return getSMaxExpr(Ops); |
| 3066 | } |
| 3067 | |
| 3068 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3069 | // so, delete one. Since we sorted the list, these values are required to |
| 3070 | // be adjacent. |
| 3071 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3072 | // X smax Y smax Y --> X smax Y |
| 3073 | // X smax Y --> X, if X is always greater than Y |
| 3074 | if (Ops[i] == Ops[i+1] || |
| 3075 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3076 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3077 | --i; --e; |
| 3078 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3079 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3080 | --i; --e; |
| 3081 | } |
| 3082 | |
| 3083 | if (Ops.size() == 1) return Ops[0]; |
| 3084 | |
| 3085 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3086 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3087 | // 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] | 3088 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3089 | FoldingSetNodeID ID; |
| 3090 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3091 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3092 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3093 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3094 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3095 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3096 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3097 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3098 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3099 | UniqueSCEVs.InsertNode(S, IP); |
| 3100 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3101 | } |
| 3102 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3103 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3104 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3105 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3106 | Ops.push_back(LHS); |
| 3107 | Ops.push_back(RHS); |
| 3108 | return getUMaxExpr(Ops); |
| 3109 | } |
| 3110 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3111 | const SCEV * |
| 3112 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3113 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3114 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3115 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3116 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3117 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3118 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3119 | "SCEVUMaxExpr operand types don't match!"); |
| 3120 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3121 | |
| 3122 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3123 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3124 | |
| 3125 | // If there are any constants, fold them together. |
| 3126 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3127 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3128 | ++Idx; |
| 3129 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3130 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3131 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3132 | ConstantInt *Fold = ConstantInt::get( |
| 3133 | getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3134 | Ops[0] = getConstant(Fold); |
| 3135 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3136 | if (Ops.size() == 1) return Ops[0]; |
| 3137 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3138 | } |
| 3139 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3140 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3141 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3142 | Ops.erase(Ops.begin()); |
| 3143 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3144 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3145 | // If we have an umax with a constant maximum-int, it will always be |
| 3146 | // maximum-int. |
| 3147 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3148 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3149 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3150 | if (Ops.size() == 1) return Ops[0]; |
| 3151 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3152 | |
| 3153 | // Find the first UMax |
| 3154 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3155 | ++Idx; |
| 3156 | |
| 3157 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3158 | // onto our operand list, and recurse to simplify. |
| 3159 | if (Idx < Ops.size()) { |
| 3160 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3161 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3162 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3163 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3164 | DeletedUMax = true; |
| 3165 | } |
| 3166 | |
| 3167 | if (DeletedUMax) |
| 3168 | return getUMaxExpr(Ops); |
| 3169 | } |
| 3170 | |
| 3171 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3172 | // so, delete one. Since we sorted the list, these values are required to |
| 3173 | // be adjacent. |
| 3174 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3175 | // X umax Y umax Y --> X umax Y |
| 3176 | // X umax Y --> X, if X is always greater than Y |
| 3177 | if (Ops[i] == Ops[i+1] || |
| 3178 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3179 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3180 | --i; --e; |
| 3181 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3182 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3183 | --i; --e; |
| 3184 | } |
| 3185 | |
| 3186 | if (Ops.size() == 1) return Ops[0]; |
| 3187 | |
| 3188 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3189 | |
| 3190 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3191 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3192 | FoldingSetNodeID ID; |
| 3193 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3194 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3195 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3196 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3197 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3198 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3199 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3200 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3201 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3202 | UniqueSCEVs.InsertNode(S, IP); |
| 3203 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3204 | } |
| 3205 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3206 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3207 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3208 | // ~smax(~x, ~y) == smin(x, y). |
| 3209 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3210 | } |
| 3211 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3212 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3213 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3214 | // ~umax(~x, ~y) == umin(x, y) |
| 3215 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3216 | } |
| 3217 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3218 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3219 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3220 | // constant expression and then folding it back into a ConstantInt. |
| 3221 | // This is just a compile-time optimization. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3222 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3223 | } |
| 3224 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3225 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3226 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3227 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3228 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3229 | // constant expression and then folding it back into a ConstantInt. |
| 3230 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3231 | return getConstant( |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3232 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3233 | } |
| 3234 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3235 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3236 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3237 | // here. createSCEV only calls getUnknown after checking for all other |
| 3238 | // interesting possibilities, and any other code that calls getUnknown |
| 3239 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3240 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3241 | FoldingSetNodeID ID; |
| 3242 | ID.AddInteger(scUnknown); |
| 3243 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3244 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3245 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3246 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3247 | "Stale SCEVUnknown in uniquing map!"); |
| 3248 | return S; |
| 3249 | } |
| 3250 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3251 | FirstUnknown); |
| 3252 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3253 | UniqueSCEVs.InsertNode(S, IP); |
| 3254 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3255 | } |
| 3256 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3257 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3258 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3259 | // |
| 3260 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3261 | /// isSCEVable - Test if values of the given type are analyzable within |
| 3262 | /// the SCEV framework. This primarily includes integer types, and it |
| 3263 | /// can optionally include pointer types if the ScalarEvolution class |
| 3264 | /// has access to target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3265 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3266 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3267 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3268 | } |
| 3269 | |
| 3270 | /// getTypeSizeInBits - Return the size in bits of the specified type, |
| 3271 | /// for which isSCEVable must return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3272 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3273 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3274 | return getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3275 | } |
| 3276 | |
| 3277 | /// getEffectiveSCEVType - Return a type with the same bitwidth as |
| 3278 | /// the given type and which represents how SCEV will treat the given |
| 3279 | /// type, for which isSCEVable must return true. For pointer types, |
| 3280 | /// this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3281 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3282 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3283 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3284 | if (Ty->isIntegerTy()) |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3285 | return Ty; |
| 3286 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3287 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3288 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3289 | return getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3290 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3291 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3292 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3293 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3294 | } |
| 3295 | |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 3296 | |
| 3297 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3298 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3299 | // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne |
| 3300 | // is set iff if find such SCEVUnknown. |
| 3301 | // |
| 3302 | struct FindInvalidSCEVUnknown { |
| 3303 | bool FindOne; |
| 3304 | FindInvalidSCEVUnknown() { FindOne = false; } |
| 3305 | bool follow(const SCEV *S) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 3306 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3307 | case scConstant: |
| 3308 | return false; |
| 3309 | case scUnknown: |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3310 | if (!cast<SCEVUnknown>(S)->getValue()) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3311 | FindOne = true; |
| 3312 | return false; |
| 3313 | default: |
| 3314 | return true; |
| 3315 | } |
| 3316 | } |
| 3317 | bool isDone() const { return FindOne; } |
| 3318 | }; |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3319 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3320 | FindInvalidSCEVUnknown F; |
| 3321 | SCEVTraversal<FindInvalidSCEVUnknown> ST(F); |
| 3322 | ST.visitAll(S); |
| 3323 | |
| 3324 | return !F.FindOne; |
| 3325 | } |
| 3326 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3327 | namespace { |
| 3328 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3329 | // a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set |
| 3330 | // iff if such sub scAddRecExpr type SCEV is found. |
| 3331 | struct FindAddRecurrence { |
| 3332 | bool FoundOne; |
| 3333 | FindAddRecurrence() : FoundOne(false) {} |
| 3334 | |
| 3335 | bool follow(const SCEV *S) { |
| 3336 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
| 3337 | case scAddRecExpr: |
| 3338 | FoundOne = true; |
| 3339 | case scConstant: |
| 3340 | case scUnknown: |
| 3341 | case scCouldNotCompute: |
| 3342 | return false; |
| 3343 | default: |
| 3344 | return true; |
| 3345 | } |
| 3346 | } |
| 3347 | bool isDone() const { return FoundOne; } |
| 3348 | }; |
| 3349 | } |
| 3350 | |
| 3351 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { |
| 3352 | HasRecMapType::iterator I = HasRecMap.find_as(S); |
| 3353 | if (I != HasRecMap.end()) |
| 3354 | return I->second; |
| 3355 | |
| 3356 | FindAddRecurrence F; |
| 3357 | SCEVTraversal<FindAddRecurrence> ST(F); |
| 3358 | ST.visitAll(S); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3359 | HasRecMap.insert({S, F.FoundOne}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3360 | return F.FoundOne; |
| 3361 | } |
| 3362 | |
| 3363 | /// getSCEVValues - Return the Value set from S. |
| 3364 | SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) { |
| 3365 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); |
| 3366 | if (SI == ExprValueMap.end()) |
| 3367 | return nullptr; |
| 3368 | #ifndef NDEBUG |
| 3369 | if (VerifySCEVMap) { |
| 3370 | // Check there is no dangling Value in the set returned. |
| 3371 | for (const auto &VE : SI->second) |
| 3372 | assert(ValueExprMap.count(VE)); |
| 3373 | } |
| 3374 | #endif |
| 3375 | return &SI->second; |
| 3376 | } |
| 3377 | |
| 3378 | /// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap. |
| 3379 | /// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S), |
| 3380 | /// eraseValueFromMap should be used instead to ensure whenever V->S is removed |
| 3381 | /// from ValueExprMap, V is also removed from the set of ExprValueMap[S]. |
| 3382 | void ScalarEvolution::eraseValueFromMap(Value *V) { |
| 3383 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3384 | if (I != ValueExprMap.end()) { |
| 3385 | const SCEV *S = I->second; |
| 3386 | SetVector<Value *> *SV = getSCEVValues(S); |
| 3387 | // Remove V from the set of ExprValueMap[S] |
| 3388 | if (SV) |
| 3389 | SV->remove(V); |
| 3390 | ValueExprMap.erase(V); |
| 3391 | } |
| 3392 | } |
| 3393 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3394 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 3395 | /// expression and create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3396 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3397 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3398 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3399 | const SCEV *S = getExistingSCEV(V); |
| 3400 | if (S == nullptr) { |
| 3401 | S = createSCEV(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3402 | // During PHI resolution, it is possible to create two SCEVs for the same |
| 3403 | // V, so it is needed to double check whether V->S is inserted into |
| 3404 | // ValueExprMap before insert S->V into ExprValueMap. |
| 3405 | std::pair<ValueExprMapType::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3406 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3407 | if (Pair.second) |
| 3408 | ExprValueMap[S].insert(V); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3409 | } |
| 3410 | return S; |
| 3411 | } |
| 3412 | |
| 3413 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3414 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3415 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3416 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3417 | if (I != ValueExprMap.end()) { |
| 3418 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3419 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3420 | return S; |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3421 | forgetMemoizedResults(S); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3422 | ValueExprMap.erase(I); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3423 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3424 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3425 | } |
| 3426 | |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3427 | /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V |
| 3428 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3429 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3430 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3431 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3432 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3433 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3434 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3435 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3436 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3437 | return getMulExpr( |
| 3438 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3439 | } |
| 3440 | |
| 3441 | /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3442 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3443 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3444 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3445 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3446 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3447 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3448 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3449 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3450 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3451 | return getMinusSCEV(AllOnes, V); |
| 3452 | } |
| 3453 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3454 | /// 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] | 3455 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3456 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3457 | // Fast path: X - X --> 0. |
| 3458 | if (LHS == RHS) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3459 | return getZero(LHS->getType()); |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3460 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3461 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3462 | // makes it so that we cannot make much use of NUW. |
| 3463 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3464 | const bool RHSIsNotMinSigned = |
| 3465 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3466 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3467 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3468 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3469 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3470 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3471 | // (-1)*RHS, we need to prove that RHS != M. |
| 3472 | // |
| 3473 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3474 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3475 | // either by proving that RHS > M or that LHS >= 0. |
| 3476 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3477 | AddFlags = SCEV::FlagNSW; |
| 3478 | } |
| 3479 | } |
| 3480 | |
| 3481 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3482 | // RHS is NSW and LHS >= 0. |
| 3483 | // |
| 3484 | // The difficulty here is that the NSW flag may have been proven |
| 3485 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3486 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3487 | // larger scope than intended. |
| 3488 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3489 | |
| 3490 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3491 | } |
| 3492 | |
| 3493 | /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3494 | /// input value to the specified type. If the type must be extended, it is zero |
| 3495 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3496 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3497 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3498 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3499 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3500 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3501 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3502 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3503 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3504 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3505 | return getTruncateExpr(V, Ty); |
| 3506 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3507 | } |
| 3508 | |
| 3509 | /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3510 | /// input value to the specified type. If the type must be extended, it is sign |
| 3511 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3512 | const SCEV * |
| 3513 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3514 | Type *Ty) { |
| 3515 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3516 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3517 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3518 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3519 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3520 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3521 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3522 | return getTruncateExpr(V, Ty); |
| 3523 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3524 | } |
| 3525 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3526 | /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3527 | /// input value to the specified type. If the type must be extended, it is zero |
| 3528 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3529 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3530 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3531 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3532 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3533 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3534 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3535 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3536 | "getNoopOrZeroExtend cannot truncate!"); |
| 3537 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3538 | return V; // No conversion |
| 3539 | return getZeroExtendExpr(V, Ty); |
| 3540 | } |
| 3541 | |
| 3542 | /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3543 | /// input value to the specified type. If the type must be extended, it is sign |
| 3544 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3545 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3546 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3547 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3548 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3549 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3550 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3551 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3552 | "getNoopOrSignExtend cannot truncate!"); |
| 3553 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3554 | return V; // No conversion |
| 3555 | return getSignExtendExpr(V, Ty); |
| 3556 | } |
| 3557 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3558 | /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of |
| 3559 | /// the input value to the specified type. If the type must be extended, |
| 3560 | /// it is extended with unspecified bits. The conversion must not be |
| 3561 | /// narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3562 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3563 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3564 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3565 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3566 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3567 | "Cannot noop or any extend with non-integer arguments!"); |
| 3568 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3569 | "getNoopOrAnyExtend cannot truncate!"); |
| 3570 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3571 | return V; // No conversion |
| 3572 | return getAnyExtendExpr(V, Ty); |
| 3573 | } |
| 3574 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3575 | /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the |
| 3576 | /// input value to the specified type. The conversion must not be widening. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3577 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3578 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3579 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3580 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3581 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3582 | "Cannot truncate or noop with non-integer arguments!"); |
| 3583 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3584 | "getTruncateOrNoop cannot extend!"); |
| 3585 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3586 | return V; // No conversion |
| 3587 | return getTruncateExpr(V, Ty); |
| 3588 | } |
| 3589 | |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3590 | /// getUMaxFromMismatchedTypes - Promote the operands to the wider of |
| 3591 | /// the types using zero-extension, and then perform a umax operation |
| 3592 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3593 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3594 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3595 | const SCEV *PromotedLHS = LHS; |
| 3596 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3597 | |
| 3598 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3599 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3600 | else |
| 3601 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3602 | |
| 3603 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3604 | } |
| 3605 | |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3606 | /// getUMinFromMismatchedTypes - Promote the operands to the wider of |
| 3607 | /// the types using zero-extension, and then perform a umin operation |
| 3608 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3609 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3610 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3611 | const SCEV *PromotedLHS = LHS; |
| 3612 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3613 | |
| 3614 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3615 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3616 | else |
| 3617 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3618 | |
| 3619 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3620 | } |
| 3621 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3622 | /// getPointerBase - Transitively follow the chain of pointer-type operands |
| 3623 | /// until reaching a SCEV that does not have a single pointer operand. This |
| 3624 | /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, |
| 3625 | /// but corner cases do exist. |
| 3626 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { |
| 3627 | // A pointer operand may evaluate to a nonpointer expression, such as null. |
| 3628 | if (!V->getType()->isPointerTy()) |
| 3629 | return V; |
| 3630 | |
| 3631 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { |
| 3632 | return getPointerBase(Cast->getOperand()); |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3633 | } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3634 | const SCEV *PtrOp = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3635 | for (const SCEV *NAryOp : NAry->operands()) { |
| 3636 | if (NAryOp->getType()->isPointerTy()) { |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3637 | // Cannot find the base of an expression with multiple pointer operands. |
| 3638 | if (PtrOp) |
| 3639 | return V; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3640 | PtrOp = NAryOp; |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3641 | } |
| 3642 | } |
| 3643 | if (!PtrOp) |
| 3644 | return V; |
| 3645 | return getPointerBase(PtrOp); |
| 3646 | } |
| 3647 | return V; |
| 3648 | } |
| 3649 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3650 | /// PushDefUseChildren - Push users of the given Instruction |
| 3651 | /// onto the given Worklist. |
| 3652 | static void |
| 3653 | PushDefUseChildren(Instruction *I, |
| 3654 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3655 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3656 | for (User *U : I->users()) |
| 3657 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3658 | } |
| 3659 | |
| 3660 | /// ForgetSymbolicValue - This looks up computed SCEV values for all |
| 3661 | /// instructions that depend on the given instruction and removes them from |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3662 | /// the ValueExprMapType map if they reference SymName. This is used during PHI |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3663 | /// resolution. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3664 | void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3665 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3666 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3667 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3668 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3669 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3670 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3671 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3672 | if (!Visited.insert(I).second) |
| 3673 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3674 | |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 3675 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3676 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3677 | const SCEV *Old = It->second; |
| 3678 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3679 | // Short-circuit the def-use traversal if the symbolic name |
| 3680 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3681 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3682 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3683 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3684 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3685 | // structure, it's a PHI that's in the progress of being computed |
| 3686 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3687 | // additional loop trip count information isn't going to change anything. |
| 3688 | // In the second case, createNodeForPHI will perform the necessary |
| 3689 | // updates on its own when it gets to that point. In the third, we do |
| 3690 | // want to forget the SCEVUnknown. |
| 3691 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3692 | !isa<SCEVUnknown>(Old) || |
| 3693 | (I != PN && Old == SymName)) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3694 | forgetMemoizedResults(Old); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3695 | ValueExprMap.erase(It); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3696 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3697 | } |
| 3698 | |
| 3699 | PushDefUseChildren(I, Worklist); |
| 3700 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3701 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3702 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3703 | namespace { |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3704 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { |
| 3705 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3706 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3707 | ScalarEvolution &SE) { |
| 3708 | SCEVInitRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3709 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3710 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3711 | } |
| 3712 | |
| 3713 | SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) |
| 3714 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3715 | |
| 3716 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3717 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3718 | Valid = false; |
| 3719 | return Expr; |
| 3720 | } |
| 3721 | |
| 3722 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3723 | // Only allow AddRecExprs for this loop. |
| 3724 | if (Expr->getLoop() == L) |
| 3725 | return Expr->getStart(); |
| 3726 | Valid = false; |
| 3727 | return Expr; |
| 3728 | } |
| 3729 | |
| 3730 | bool isValid() { return Valid; } |
| 3731 | |
| 3732 | private: |
| 3733 | const Loop *L; |
| 3734 | bool Valid; |
| 3735 | }; |
| 3736 | |
| 3737 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { |
| 3738 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3739 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3740 | ScalarEvolution &SE) { |
| 3741 | SCEVShiftRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3742 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3743 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3744 | } |
| 3745 | |
| 3746 | SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) |
| 3747 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3748 | |
| 3749 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3750 | // Only allow AddRecExprs for this loop. |
| 3751 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3752 | Valid = false; |
| 3753 | return Expr; |
| 3754 | } |
| 3755 | |
| 3756 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3757 | if (Expr->getLoop() == L && Expr->isAffine()) |
| 3758 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); |
| 3759 | Valid = false; |
| 3760 | return Expr; |
| 3761 | } |
| 3762 | bool isValid() { return Valid; } |
| 3763 | |
| 3764 | private: |
| 3765 | const Loop *L; |
| 3766 | bool Valid; |
| 3767 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3768 | } // end anonymous namespace |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3769 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 3770 | SCEV::NoWrapFlags |
| 3771 | ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { |
| 3772 | if (!AR->isAffine()) |
| 3773 | return SCEV::FlagAnyWrap; |
| 3774 | |
| 3775 | typedef OverflowingBinaryOperator OBO; |
| 3776 | SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; |
| 3777 | |
| 3778 | if (!AR->hasNoSignedWrap()) { |
| 3779 | ConstantRange AddRecRange = getSignedRange(AR); |
| 3780 | ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); |
| 3781 | |
| 3782 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3783 | Instruction::Add, IncRange, OBO::NoSignedWrap); |
| 3784 | if (NSWRegion.contains(AddRecRange)) |
| 3785 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); |
| 3786 | } |
| 3787 | |
| 3788 | if (!AR->hasNoUnsignedWrap()) { |
| 3789 | ConstantRange AddRecRange = getUnsignedRange(AR); |
| 3790 | ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); |
| 3791 | |
| 3792 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3793 | Instruction::Add, IncRange, OBO::NoUnsignedWrap); |
| 3794 | if (NUWRegion.contains(AddRecRange)) |
| 3795 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); |
| 3796 | } |
| 3797 | |
| 3798 | return Result; |
| 3799 | } |
| 3800 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3801 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { |
| 3802 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 3803 | if (!L || L->getHeader() != PN->getParent()) |
| 3804 | return nullptr; |
| 3805 | |
| 3806 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 3807 | // this phi as an addrec if it has a unique entry value and a unique |
| 3808 | // backedge value. |
| 3809 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
| 3810 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 3811 | Value *V = PN->getIncomingValue(i); |
| 3812 | if (L->contains(PN->getIncomingBlock(i))) { |
| 3813 | if (!BEValueV) { |
| 3814 | BEValueV = V; |
| 3815 | } else if (BEValueV != V) { |
| 3816 | BEValueV = nullptr; |
| 3817 | break; |
| 3818 | } |
| 3819 | } else if (!StartValueV) { |
| 3820 | StartValueV = V; |
| 3821 | } else if (StartValueV != V) { |
| 3822 | StartValueV = nullptr; |
| 3823 | break; |
| 3824 | } |
| 3825 | } |
| 3826 | if (BEValueV && StartValueV) { |
| 3827 | // While we are analyzing this PHI node, handle its value symbolically. |
| 3828 | const SCEV *SymbolicName = getUnknown(PN); |
| 3829 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
| 3830 | "PHI node already processed?"); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3831 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3832 | |
| 3833 | // Using this symbolic name for the PHI, analyze the value coming around |
| 3834 | // the back-edge. |
| 3835 | const SCEV *BEValue = getSCEV(BEValueV); |
| 3836 | |
| 3837 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 3838 | // has a special value for the first iteration of the loop. |
| 3839 | |
| 3840 | // If the value coming around the backedge is an add with the symbolic |
| 3841 | // value we just inserted, then we found a simple induction variable! |
| 3842 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 3843 | // If there is a single occurrence of the symbolic value, replace it |
| 3844 | // with a recurrence. |
| 3845 | unsigned FoundIndex = Add->getNumOperands(); |
| 3846 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3847 | if (Add->getOperand(i) == SymbolicName) |
| 3848 | if (FoundIndex == e) { |
| 3849 | FoundIndex = i; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3850 | break; |
| 3851 | } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3852 | |
| 3853 | if (FoundIndex != Add->getNumOperands()) { |
| 3854 | // Create an add with everything but the specified operand. |
| 3855 | SmallVector<const SCEV *, 8> Ops; |
| 3856 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3857 | if (i != FoundIndex) |
| 3858 | Ops.push_back(Add->getOperand(i)); |
| 3859 | const SCEV *Accum = getAddExpr(Ops); |
| 3860 | |
| 3861 | // This is not a valid addrec if the step amount is varying each |
| 3862 | // loop iteration, but is not itself an addrec in this loop. |
| 3863 | if (isLoopInvariant(Accum, L) || |
| 3864 | (isa<SCEVAddRecExpr>(Accum) && |
| 3865 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 3866 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 3867 | |
| 3868 | // If the increment doesn't overflow, then neither the addrec nor |
| 3869 | // the post-increment will overflow. |
| 3870 | if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) { |
| 3871 | if (OBO->getOperand(0) == PN) { |
| 3872 | if (OBO->hasNoUnsignedWrap()) |
| 3873 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 3874 | if (OBO->hasNoSignedWrap()) |
| 3875 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 3876 | } |
| 3877 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
| 3878 | // If the increment is an inbounds GEP, then we know the address |
| 3879 | // space cannot be wrapped around. We cannot make any guarantee |
| 3880 | // about signed or unsigned overflow because pointers are |
| 3881 | // unsigned but we may have a negative index from the base |
| 3882 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 3883 | // indices form a positive value. |
| 3884 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
| 3885 | Flags = setFlags(Flags, SCEV::FlagNW); |
| 3886 | |
| 3887 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 3888 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 3889 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 3890 | } |
| 3891 | |
| 3892 | // We cannot transfer nuw and nsw flags from subtraction |
| 3893 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 3894 | // for instance. |
| 3895 | } |
| 3896 | |
| 3897 | const SCEV *StartVal = getSCEV(StartValueV); |
| 3898 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
| 3899 | |
| 3900 | // Since the no-wrap flags are on the increment, they apply to the |
| 3901 | // post-incremented value as well. |
| 3902 | if (isLoopInvariant(Accum, L)) |
| 3903 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); |
| 3904 | |
| 3905 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 3906 | // to be symbolic. We now need to go back and purge all of the |
| 3907 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3908 | forgetSymbolicName(PN, SymbolicName); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3909 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
| 3910 | return PHISCEV; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3911 | } |
| 3912 | } |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3913 | } else { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3914 | // Otherwise, this could be a loop like this: |
| 3915 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 3916 | // In this case, j = {1,+,1} and BEValue is j. |
| 3917 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 3918 | // i really is an addrec evolution. |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3919 | // |
| 3920 | // We can generalize this saying that i is the shifted value of BEValue |
| 3921 | // by one iteration: |
| 3922 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) |
| 3923 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); |
| 3924 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); |
| 3925 | if (Shifted != getCouldNotCompute() && |
| 3926 | Start != getCouldNotCompute()) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3927 | const SCEV *StartVal = getSCEV(StartValueV); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3928 | if (Start == StartVal) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3929 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 3930 | // to be symbolic. We now need to go back and purge all of the |
| 3931 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3932 | forgetSymbolicName(PN, SymbolicName); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3933 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; |
| 3934 | return Shifted; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3935 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3936 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3937 | } |
Tobias Grosser | 934fcf4 | 2016-02-21 18:50:09 +0000 | [diff] [blame] | 3938 | |
| 3939 | // Remove the temporary PHI node SCEV that has been inserted while intending |
| 3940 | // to create an AddRecExpr for this PHI node. We can not keep this temporary |
| 3941 | // as it will prevent later (possibly simpler) SCEV expressions to be added |
| 3942 | // to the ValueExprMap. |
| 3943 | ValueExprMap.erase(PN); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3944 | } |
| 3945 | |
| 3946 | return nullptr; |
| 3947 | } |
| 3948 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3949 | // Checks if the SCEV S is available at BB. S is considered available at BB |
| 3950 | // if S can be materialized at BB without introducing a fault. |
| 3951 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, |
| 3952 | BasicBlock *BB) { |
| 3953 | struct CheckAvailable { |
| 3954 | bool TraversalDone = false; |
| 3955 | bool Available = true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3956 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3957 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) |
| 3958 | BasicBlock *BB = nullptr; |
| 3959 | DominatorTree &DT; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3960 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3961 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) |
| 3962 | : L(L), BB(BB), DT(DT) {} |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3963 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3964 | bool setUnavailable() { |
| 3965 | TraversalDone = true; |
| 3966 | Available = false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3967 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3968 | } |
| 3969 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3970 | bool follow(const SCEV *S) { |
| 3971 | switch (S->getSCEVType()) { |
| 3972 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: |
| 3973 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: |
Sanjoy Das | bb5ffc5 | 2015-10-24 05:37:28 +0000 | [diff] [blame] | 3974 | // These expressions are available if their operand(s) is/are. |
| 3975 | return true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3976 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3977 | case scAddRecExpr: { |
| 3978 | // We allow add recurrences that are on the loop BB is in, or some |
| 3979 | // outer loop. This guarantees availability because the value of the |
| 3980 | // add recurrence at BB is simply the "current" value of the induction |
| 3981 | // variable. We can relax this in the future; for instance an add |
| 3982 | // recurrence on a sibling dominating loop is also available at BB. |
| 3983 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); |
| 3984 | if (L && (ARLoop == L || ARLoop->contains(L))) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3985 | return true; |
| 3986 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3987 | return setUnavailable(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3988 | } |
| 3989 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3990 | case scUnknown: { |
| 3991 | // For SCEVUnknown, we check for simple dominance. |
| 3992 | const auto *SU = cast<SCEVUnknown>(S); |
| 3993 | Value *V = SU->getValue(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3994 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3995 | if (isa<Argument>(V)) |
| 3996 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3997 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3998 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) |
| 3999 | return false; |
| 4000 | |
| 4001 | return setUnavailable(); |
| 4002 | } |
| 4003 | |
| 4004 | case scUDivExpr: |
| 4005 | case scCouldNotCompute: |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 4006 | // We do not try to smart about these at all. |
| 4007 | return setUnavailable(); |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4008 | } |
| 4009 | llvm_unreachable("switch should be fully covered!"); |
| 4010 | } |
| 4011 | |
| 4012 | bool isDone() { return TraversalDone; } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4013 | }; |
| 4014 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4015 | CheckAvailable CA(L, BB, DT); |
| 4016 | SCEVTraversal<CheckAvailable> ST(CA); |
| 4017 | |
| 4018 | ST.visitAll(S); |
| 4019 | return CA.Available; |
| 4020 | } |
| 4021 | |
| 4022 | // Try to match a control flow sequence that branches out at BI and merges back |
| 4023 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful |
| 4024 | // match. |
| 4025 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, |
| 4026 | Value *&C, Value *&LHS, Value *&RHS) { |
| 4027 | C = BI->getCondition(); |
| 4028 | |
| 4029 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); |
| 4030 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); |
| 4031 | |
| 4032 | if (!LeftEdge.isSingleEdge()) |
| 4033 | return false; |
| 4034 | |
| 4035 | assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); |
| 4036 | |
| 4037 | Use &LeftUse = Merge->getOperandUse(0); |
| 4038 | Use &RightUse = Merge->getOperandUse(1); |
| 4039 | |
| 4040 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { |
| 4041 | LHS = LeftUse; |
| 4042 | RHS = RightUse; |
| 4043 | return true; |
| 4044 | } |
| 4045 | |
| 4046 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { |
| 4047 | LHS = RightUse; |
| 4048 | RHS = LeftUse; |
| 4049 | return true; |
| 4050 | } |
| 4051 | |
| 4052 | return false; |
| 4053 | } |
| 4054 | |
| 4055 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4056 | if (PN->getNumIncomingValues() == 2) { |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4057 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 4058 | |
Sanjoy Das | 337d478 | 2015-10-31 23:21:40 +0000 | [diff] [blame] | 4059 | // We don't want to break LCSSA, even in a SCEV expression tree. |
| 4060 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 4061 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) |
| 4062 | return nullptr; |
| 4063 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4064 | // Try to match |
| 4065 | // |
| 4066 | // br %cond, label %left, label %right |
| 4067 | // left: |
| 4068 | // br label %merge |
| 4069 | // right: |
| 4070 | // br label %merge |
| 4071 | // merge: |
| 4072 | // V = phi [ %x, %left ], [ %y, %right ] |
| 4073 | // |
| 4074 | // as "select %cond, %x, %y" |
| 4075 | |
| 4076 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); |
| 4077 | assert(IDom && "At least the entry block should dominate PN"); |
| 4078 | |
| 4079 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); |
| 4080 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; |
| 4081 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4082 | if (BI && BI->isConditional() && |
| 4083 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && |
| 4084 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && |
| 4085 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4086 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); |
| 4087 | } |
| 4088 | |
| 4089 | return nullptr; |
| 4090 | } |
| 4091 | |
| 4092 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
| 4093 | if (const SCEV *S = createAddRecFromPHI(PN)) |
| 4094 | return S; |
| 4095 | |
| 4096 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) |
| 4097 | return S; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 4098 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4099 | // If the PHI has a single incoming value, follow that value, unless the |
| 4100 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 4101 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 4102 | // it doesn't have DominatorTree information, so it may miss cases. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4103 | if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4104 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4105 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 4106 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4107 | // 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] | 4108 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4109 | } |
| 4110 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4111 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, |
| 4112 | Value *Cond, |
| 4113 | Value *TrueVal, |
| 4114 | Value *FalseVal) { |
Mehdi Amini | 044cb34 | 2015-10-07 18:14:25 +0000 | [diff] [blame] | 4115 | // Handle "constant" branch or select. This can occur for instance when a |
| 4116 | // loop pass transforms an inner loop and moves on to process the outer loop. |
| 4117 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) |
| 4118 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); |
| 4119 | |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4120 | // Try to match some simple smax or umax patterns. |
| 4121 | auto *ICI = dyn_cast<ICmpInst>(Cond); |
| 4122 | if (!ICI) |
| 4123 | return getUnknown(I); |
| 4124 | |
| 4125 | Value *LHS = ICI->getOperand(0); |
| 4126 | Value *RHS = ICI->getOperand(1); |
| 4127 | |
| 4128 | switch (ICI->getPredicate()) { |
| 4129 | case ICmpInst::ICMP_SLT: |
| 4130 | case ICmpInst::ICMP_SLE: |
| 4131 | std::swap(LHS, RHS); |
| 4132 | // fall through |
| 4133 | case ICmpInst::ICMP_SGT: |
| 4134 | case ICmpInst::ICMP_SGE: |
| 4135 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4136 | // a >s b ? b+x : a+x -> smin(a, b)+x |
| 4137 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4138 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); |
| 4139 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); |
| 4140 | const SCEV *LA = getSCEV(TrueVal); |
| 4141 | const SCEV *RA = getSCEV(FalseVal); |
| 4142 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4143 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4144 | if (LDiff == RDiff) |
| 4145 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4146 | LDiff = getMinusSCEV(LA, RS); |
| 4147 | RDiff = getMinusSCEV(RA, LS); |
| 4148 | if (LDiff == RDiff) |
| 4149 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4150 | } |
| 4151 | break; |
| 4152 | case ICmpInst::ICMP_ULT: |
| 4153 | case ICmpInst::ICMP_ULE: |
| 4154 | std::swap(LHS, RHS); |
| 4155 | // fall through |
| 4156 | case ICmpInst::ICMP_UGT: |
| 4157 | case ICmpInst::ICMP_UGE: |
| 4158 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4159 | // a >u b ? b+x : a+x -> umin(a, b)+x |
| 4160 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4161 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4162 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); |
| 4163 | const SCEV *LA = getSCEV(TrueVal); |
| 4164 | const SCEV *RA = getSCEV(FalseVal); |
| 4165 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4166 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4167 | if (LDiff == RDiff) |
| 4168 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4169 | LDiff = getMinusSCEV(LA, RS); |
| 4170 | RDiff = getMinusSCEV(RA, LS); |
| 4171 | if (LDiff == RDiff) |
| 4172 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4173 | } |
| 4174 | break; |
| 4175 | case ICmpInst::ICMP_NE: |
| 4176 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
| 4177 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4178 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4179 | const SCEV *One = getOne(I->getType()); |
| 4180 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4181 | const SCEV *LA = getSCEV(TrueVal); |
| 4182 | const SCEV *RA = getSCEV(FalseVal); |
| 4183 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4184 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4185 | if (LDiff == RDiff) |
| 4186 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4187 | } |
| 4188 | break; |
| 4189 | case ICmpInst::ICMP_EQ: |
| 4190 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
| 4191 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4192 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4193 | const SCEV *One = getOne(I->getType()); |
| 4194 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4195 | const SCEV *LA = getSCEV(TrueVal); |
| 4196 | const SCEV *RA = getSCEV(FalseVal); |
| 4197 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4198 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4199 | if (LDiff == RDiff) |
| 4200 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4201 | } |
| 4202 | break; |
| 4203 | default: |
| 4204 | break; |
| 4205 | } |
| 4206 | |
| 4207 | return getUnknown(I); |
| 4208 | } |
| 4209 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4210 | /// createNodeForGEP - Expand GEP instructions into add and multiply |
| 4211 | /// operations. This allows them to be analyzed by regular SCEV code. |
| 4212 | /// |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4213 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4214 | // Don't attempt to analyze GEPs over unsized objects. |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4215 | if (!GEP->getSourceElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4216 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 4217 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 4218 | SmallVector<const SCEV *, 4> IndexExprs; |
| 4219 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 4220 | IndexExprs.push_back(getSCEV(*Index)); |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4221 | return getGEPExpr(GEP->getSourceElementType(), |
| 4222 | getSCEV(GEP->getPointerOperand()), |
| 4223 | IndexExprs, GEP->isInBounds()); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4224 | } |
| 4225 | |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4226 | /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is |
| 4227 | /// guaranteed to end in (at every loop iteration). It is, at the same time, |
| 4228 | /// the minimum number of times S is divisible by 2. For example, given {4,+,8} |
| 4229 | /// 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] | 4230 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4231 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4232 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4233 | return C->getAPInt().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4234 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4235 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4236 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 4237 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4238 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4239 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4240 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4241 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4242 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4243 | } |
| 4244 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4245 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4246 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4247 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4248 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4249 | } |
| 4250 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4251 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4252 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4253 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4254 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4255 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4256 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4257 | } |
| 4258 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4259 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4260 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4261 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 4262 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4263 | for (unsigned i = 1, e = M->getNumOperands(); |
| 4264 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4265 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4266 | BitWidth); |
| 4267 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4268 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4269 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4270 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4271 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4272 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4273 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4274 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4275 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4276 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4277 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4278 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4279 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4280 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4281 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4282 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4283 | return MinOpRes; |
| 4284 | } |
| 4285 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4286 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4287 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4288 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4289 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4290 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4291 | return MinOpRes; |
| 4292 | } |
| 4293 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4294 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 4295 | // For a SCEVUnknown, ask ValueTracking. |
| 4296 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4297 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4298 | computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, |
| 4299 | nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4300 | return Zeros.countTrailingOnes(); |
| 4301 | } |
| 4302 | |
| 4303 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4304 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4305 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4306 | |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4307 | /// GetRangeFromMetadata - Helper method to assign a range to V from |
| 4308 | /// metadata present in the IR. |
| 4309 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
Sanjoy Das | a7e1378 | 2015-10-24 05:37:35 +0000 | [diff] [blame] | 4310 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4311 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) |
| 4312 | return getConstantRangeFromMetadata(*MD); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4313 | |
| 4314 | return None; |
| 4315 | } |
| 4316 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4317 | /// getRange - Determine the range for a particular SCEV. If SignHint is |
| 4318 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 4319 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4320 | /// |
| 4321 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4322 | ScalarEvolution::getRange(const SCEV *S, |
| 4323 | ScalarEvolution::RangeSignHint SignHint) { |
| 4324 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 4325 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 4326 | : SignedRanges; |
| 4327 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4328 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4329 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 4330 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4331 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4332 | |
| 4333 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4334 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4335 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4336 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 4337 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 4338 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4339 | // If the value has known zeros, the maximum value will have those known zeros |
| 4340 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4341 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4342 | if (TZ != 0) { |
| 4343 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 4344 | ConservativeResult = |
| 4345 | ConstantRange(APInt::getMinValue(BitWidth), |
| 4346 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 4347 | else |
| 4348 | ConservativeResult = ConstantRange( |
| 4349 | APInt::getSignedMinValue(BitWidth), |
| 4350 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 4351 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4352 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4353 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4354 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4355 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4356 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 4357 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4358 | } |
| 4359 | |
| 4360 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4361 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4362 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4363 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 4364 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4365 | } |
| 4366 | |
| 4367 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4368 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4369 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4370 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 4371 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4372 | } |
| 4373 | |
| 4374 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4375 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4376 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4377 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 4378 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4379 | } |
| 4380 | |
| 4381 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4382 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 4383 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 4384 | return setRange(UDiv, SignHint, |
| 4385 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4386 | } |
| 4387 | |
| 4388 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4389 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 4390 | return setRange(ZExt, SignHint, |
| 4391 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4392 | } |
| 4393 | |
| 4394 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4395 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 4396 | return setRange(SExt, SignHint, |
| 4397 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4398 | } |
| 4399 | |
| 4400 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4401 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 4402 | return setRange(Trunc, SignHint, |
| 4403 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4404 | } |
| 4405 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4406 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4407 | // If there's no unsigned wrap, the value will never be less than its |
| 4408 | // initial value. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4409 | if (AddRec->hasNoUnsignedWrap()) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4410 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 4411 | if (!C->getValue()->isZero()) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4412 | ConservativeResult = ConservativeResult.intersectWith( |
| 4413 | ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4414 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4415 | // If there's no signed wrap, and all the operands have the same sign or |
| 4416 | // zero, the value won't ever change sign. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4417 | if (AddRec->hasNoSignedWrap()) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4418 | bool AllNonNeg = true; |
| 4419 | bool AllNonPos = true; |
| 4420 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 4421 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 4422 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4423 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4424 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4425 | ConservativeResult = ConservativeResult.intersectWith( |
| 4426 | ConstantRange(APInt(BitWidth, 0), |
| 4427 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4428 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4429 | ConservativeResult = ConservativeResult.intersectWith( |
| 4430 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4431 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4432 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4433 | |
| 4434 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4435 | if (AddRec->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4436 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4437 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4438 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4439 | auto RangeFromAffine = getRangeForAffineAR( |
| 4440 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4441 | BitWidth); |
| 4442 | if (!RangeFromAffine.isFullSet()) |
| 4443 | ConservativeResult = |
| 4444 | ConservativeResult.intersectWith(RangeFromAffine); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4445 | |
| 4446 | auto RangeFromFactoring = getRangeViaFactoring( |
| 4447 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4448 | BitWidth); |
| 4449 | if (!RangeFromFactoring.isFullSet()) |
| 4450 | ConservativeResult = |
| 4451 | ConservativeResult.intersectWith(RangeFromFactoring); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4452 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4453 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4454 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4455 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4456 | } |
| 4457 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4458 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4459 | // Check if the IR explicitly contains !range metadata. |
| 4460 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4461 | if (MDRange.hasValue()) |
| 4462 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4463 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4464 | // Split here to avoid paying the compile-time cost of calling both |
| 4465 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4466 | // if needed. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4467 | const DataLayout &DL = getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4468 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4469 | // For a SCEVUnknown, ask ValueTracking. |
| 4470 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4471 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4472 | if (Ones != ~Zeros + 1) |
| 4473 | ConservativeResult = |
| 4474 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4475 | } else { |
| 4476 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4477 | "generalize as needed!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4478 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4479 | if (NS > 1) |
| 4480 | ConservativeResult = ConservativeResult.intersectWith( |
| 4481 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4482 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4483 | } |
| 4484 | |
| 4485 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4486 | } |
| 4487 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4488 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4489 | } |
| 4490 | |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4491 | ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, |
| 4492 | const SCEV *Step, |
| 4493 | const SCEV *MaxBECount, |
| 4494 | unsigned BitWidth) { |
| 4495 | assert(!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4496 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && |
| 4497 | "Precondition!"); |
| 4498 | |
| 4499 | ConstantRange Result(BitWidth, /* isFullSet = */ true); |
| 4500 | |
| 4501 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4502 | // because we could be called from within the ScalarEvolution overflow |
| 4503 | // checking code. |
| 4504 | |
| 4505 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); |
| 4506 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
| 4507 | ConstantRange ZExtMaxBECountRange = |
| 4508 | MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); |
| 4509 | |
| 4510 | ConstantRange StepSRange = getSignedRange(Step); |
| 4511 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4512 | |
| 4513 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4514 | ConstantRange EndURange = |
| 4515 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
| 4516 | |
| 4517 | // Check for unsigned overflow. |
| 4518 | ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4519 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4520 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4521 | ZExtEndURange) { |
| 4522 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4523 | EndURange.getUnsignedMin()); |
| 4524 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4525 | EndURange.getUnsignedMax()); |
| 4526 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4527 | if (!IsFullRange) |
| 4528 | Result = |
| 4529 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4530 | } |
| 4531 | |
| 4532 | ConstantRange StartSRange = getSignedRange(Start); |
| 4533 | ConstantRange EndSRange = |
| 4534 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4535 | |
| 4536 | // Check for signed overflow. This must be done with ConstantRange |
| 4537 | // arithmetic because we could be called from within the ScalarEvolution |
| 4538 | // overflow checking code. |
| 4539 | ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4540 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4541 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4542 | SExtEndSRange) { |
| 4543 | APInt Min = |
| 4544 | APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); |
| 4545 | APInt Max = |
| 4546 | APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); |
| 4547 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4548 | if (!IsFullRange) |
| 4549 | Result = |
| 4550 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4551 | } |
| 4552 | |
| 4553 | return Result; |
| 4554 | } |
| 4555 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4556 | ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, |
| 4557 | const SCEV *Step, |
| 4558 | const SCEV *MaxBECount, |
| 4559 | unsigned BitWidth) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4560 | // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) |
| 4561 | // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) |
| 4562 | |
| 4563 | struct SelectPattern { |
| 4564 | Value *Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4565 | APInt TrueValue; |
| 4566 | APInt FalseValue; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4567 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4568 | explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, |
| 4569 | const SCEV *S) { |
| 4570 | Optional<unsigned> CastOp; |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4571 | APInt Offset(BitWidth, 0); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4572 | |
| 4573 | assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && |
| 4574 | "Should be!"); |
| 4575 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4576 | // Peel off a constant offset: |
| 4577 | if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { |
| 4578 | // In the future we could consider being smarter here and handle |
| 4579 | // {Start+Step,+,Step} too. |
| 4580 | if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) |
| 4581 | return; |
| 4582 | |
| 4583 | Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); |
| 4584 | S = SA->getOperand(1); |
| 4585 | } |
| 4586 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4587 | // Peel off a cast operation |
| 4588 | if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { |
| 4589 | CastOp = SCast->getSCEVType(); |
| 4590 | S = SCast->getOperand(); |
| 4591 | } |
| 4592 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4593 | using namespace llvm::PatternMatch; |
| 4594 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4595 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 4596 | const APInt *TrueVal, *FalseVal; |
| 4597 | if (!SU || |
| 4598 | !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), |
| 4599 | m_APInt(FalseVal)))) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4600 | Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4601 | return; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4602 | } |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4603 | |
| 4604 | TrueValue = *TrueVal; |
| 4605 | FalseValue = *FalseVal; |
| 4606 | |
| 4607 | // Re-apply the cast we peeled off earlier |
| 4608 | if (CastOp.hasValue()) |
| 4609 | switch (*CastOp) { |
| 4610 | default: |
| 4611 | llvm_unreachable("Unknown SCEV cast type!"); |
| 4612 | |
| 4613 | case scTruncate: |
| 4614 | TrueValue = TrueValue.trunc(BitWidth); |
| 4615 | FalseValue = FalseValue.trunc(BitWidth); |
| 4616 | break; |
| 4617 | case scZeroExtend: |
| 4618 | TrueValue = TrueValue.zext(BitWidth); |
| 4619 | FalseValue = FalseValue.zext(BitWidth); |
| 4620 | break; |
| 4621 | case scSignExtend: |
| 4622 | TrueValue = TrueValue.sext(BitWidth); |
| 4623 | FalseValue = FalseValue.sext(BitWidth); |
| 4624 | break; |
| 4625 | } |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4626 | |
| 4627 | // Re-apply the constant offset we peeled off earlier |
| 4628 | TrueValue += Offset; |
| 4629 | FalseValue += Offset; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4630 | } |
| 4631 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4632 | bool isRecognized() { return Condition != nullptr; } |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4633 | }; |
| 4634 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4635 | SelectPattern StartPattern(*this, BitWidth, Start); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4636 | if (!StartPattern.isRecognized()) |
| 4637 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4638 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4639 | SelectPattern StepPattern(*this, BitWidth, Step); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4640 | if (!StepPattern.isRecognized()) |
| 4641 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4642 | |
| 4643 | if (StartPattern.Condition != StepPattern.Condition) { |
| 4644 | // We don't handle this case today; but we could, by considering four |
| 4645 | // possibilities below instead of two. I'm not sure if there are cases where |
| 4646 | // that will help over what getRange already does, though. |
| 4647 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4648 | } |
| 4649 | |
| 4650 | // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to |
| 4651 | // construct arbitrary general SCEV expressions here. This function is called |
| 4652 | // from deep in the call stack, and calling getSCEV (on a sext instruction, |
| 4653 | // say) can end up caching a suboptimal value. |
| 4654 | |
Sanjoy Das | 6b017a1 | 2016-03-02 02:56:29 +0000 | [diff] [blame] | 4655 | // FIXME: without the explicit `this` receiver below, MSVC errors out with |
| 4656 | // C2352 and C2512 (otherwise it isn't needed). |
| 4657 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4658 | const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4659 | const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4660 | const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4661 | const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); |
Sanjoy Das | 62a1c33 | 2016-03-02 02:15:42 +0000 | [diff] [blame] | 4662 | |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4663 | ConstantRange TrueRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4664 | this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4665 | ConstantRange FalseRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4666 | this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4667 | |
| 4668 | return TrueRange.unionWith(FalseRange); |
| 4669 | } |
| 4670 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4671 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4672 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4673 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4674 | |
| 4675 | // Return early if there are no flags to propagate to the SCEV. |
| 4676 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4677 | if (BinOp->hasNoUnsignedWrap()) |
| 4678 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4679 | if (BinOp->hasNoSignedWrap()) |
| 4680 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4681 | if (Flags == SCEV::FlagAnyWrap) |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4682 | return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4683 | |
| 4684 | // Here we check that BinOp is in the header of the innermost loop |
| 4685 | // containing BinOp, since we only deal with instructions in the loop |
| 4686 | // header. The actual loop we need to check later will come from an add |
| 4687 | // recurrence, but getting that requires computing the SCEV of the operands, |
| 4688 | // which can be expensive. This check we can do cheaply to rule out some |
| 4689 | // cases early. |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4690 | Loop *InnermostContainingLoop = LI.getLoopFor(BinOp->getParent()); |
| 4691 | if (InnermostContainingLoop == nullptr || |
| 4692 | InnermostContainingLoop->getHeader() != BinOp->getParent()) |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4693 | return SCEV::FlagAnyWrap; |
| 4694 | |
| 4695 | // Only proceed if we can prove that BinOp does not yield poison. |
| 4696 | if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap; |
| 4697 | |
| 4698 | // At this point we know that if V is executed, then it does not wrap |
| 4699 | // according to at least one of NSW or NUW. If V is not executed, then we do |
| 4700 | // not know if the calculation that V represents would wrap. Multiple |
| 4701 | // instructions can map to the same SCEV. If we apply NSW or NUW from V to |
| 4702 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4703 | // derived from other instructions that map to the same SCEV. We cannot make |
| 4704 | // that guarantee for cases where V is not executed. So we need to find the |
| 4705 | // loop that V is considered in relation to and prove that V is executed for |
| 4706 | // every iteration of that loop. That implies that the value that V |
| 4707 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4708 | // flags to the SCEV. |
| 4709 | // |
| 4710 | // We check isLoopInvariant to disambiguate in case we are adding two |
| 4711 | // recurrences from different loops, so that we know which loop to prove |
| 4712 | // that V is executed in. |
| 4713 | for (int OpIndex = 0; OpIndex < 2; ++OpIndex) { |
| 4714 | const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex)); |
| 4715 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 4716 | const int OtherOpIndex = 1 - OpIndex; |
| 4717 | const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex)); |
| 4718 | if (isLoopInvariant(OtherOp, AddRec->getLoop()) && |
| 4719 | isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop())) |
| 4720 | return Flags; |
| 4721 | } |
| 4722 | } |
| 4723 | return SCEV::FlagAnyWrap; |
| 4724 | } |
| 4725 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4726 | namespace { |
| 4727 | /// Represents an abstract binary operation. This may exist as a |
| 4728 | /// normal instruction or constant expression, or may have been |
| 4729 | /// derived from an expression tree. |
| 4730 | struct BinaryOp { |
| 4731 | unsigned Opcode; |
| 4732 | Value *LHS; |
| 4733 | Value *RHS; |
| 4734 | |
| 4735 | /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or |
| 4736 | /// constant expression. |
| 4737 | Operator *Op; |
| 4738 | |
| 4739 | explicit BinaryOp(Operator *Op) |
| 4740 | : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), |
| 4741 | Op(Op) {} |
| 4742 | |
| 4743 | explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS) |
| 4744 | : Opcode(Opcode), LHS(LHS), RHS(RHS), Op(nullptr) {} |
| 4745 | }; |
| 4746 | } |
| 4747 | |
| 4748 | |
| 4749 | /// Try to map \p V into a BinaryOp, and return \c None on failure. |
| 4750 | static Optional<BinaryOp> MatchBinaryOp(Value *V) { |
| 4751 | auto *Op = dyn_cast<Operator>(V); |
| 4752 | if (!Op) |
| 4753 | return None; |
| 4754 | |
| 4755 | // Implementation detail: all the cleverness here should happen without |
| 4756 | // creating new SCEV expressions -- our caller knowns tricks to avoid creating |
| 4757 | // SCEV expressions when possible, and we should not break that. |
| 4758 | |
| 4759 | switch (Op->getOpcode()) { |
| 4760 | case Instruction::Add: |
| 4761 | case Instruction::Sub: |
| 4762 | case Instruction::Mul: |
| 4763 | case Instruction::UDiv: |
| 4764 | case Instruction::And: |
| 4765 | case Instruction::Or: |
| 4766 | case Instruction::AShr: |
| 4767 | case Instruction::Shl: |
| 4768 | return BinaryOp(Op); |
| 4769 | |
| 4770 | case Instruction::Xor: |
| 4771 | if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) |
| 4772 | // If the RHS of the xor is a signbit, then this is just an add. |
| 4773 | // Instcombine turns add of signbit into xor as a strength reduction step. |
| 4774 | if (RHSC->getValue().isSignBit()) |
| 4775 | return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); |
| 4776 | return BinaryOp(Op); |
| 4777 | |
| 4778 | case Instruction::LShr: |
| 4779 | // Turn logical shift right of a constant into a unsigned divide. |
| 4780 | if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { |
| 4781 | uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); |
| 4782 | |
| 4783 | // If the shift count is not less than the bitwidth, the result of |
| 4784 | // the shift is undefined. Don't try to analyze it, because the |
| 4785 | // resolution chosen here may differ from the resolution chosen in |
| 4786 | // other parts of the compiler. |
| 4787 | if (SA->getValue().ult(BitWidth)) { |
| 4788 | Constant *X = |
| 4789 | ConstantInt::get(SA->getContext(), |
| 4790 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
| 4791 | return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); |
| 4792 | } |
| 4793 | } |
| 4794 | return BinaryOp(Op); |
| 4795 | |
| 4796 | default: |
| 4797 | break; |
| 4798 | } |
| 4799 | |
| 4800 | return None; |
| 4801 | } |
| 4802 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4803 | /// createSCEV - We know that there is no SCEV for the specified value. Analyze |
| 4804 | /// the expression. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4805 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4806 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4807 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4808 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4809 | |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4810 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4811 | // Don't attempt to analyze instructions in blocks that aren't |
| 4812 | // reachable. Such instructions don't matter, and they aren't required |
| 4813 | // to obey basic rules for definitions dominating uses which this |
| 4814 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4815 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4816 | return getUnknown(V); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 4817 | } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 4818 | return getConstant(CI); |
| 4819 | else if (isa<ConstantPointerNull>(V)) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 4820 | return getZero(V->getType()); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 4821 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
| 4822 | return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 4823 | else if (!isa<ConstantExpr>(V)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4824 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 4825 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 4826 | Operator *U = cast<Operator>(V); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4827 | if (auto BO = MatchBinaryOp(U)) { |
| 4828 | switch (BO->Opcode) { |
| 4829 | case Instruction::Add: { |
| 4830 | // The simple thing to do would be to just call getSCEV on both operands |
| 4831 | // and call getAddExpr with the result. However if we're looking at a |
| 4832 | // bunch of things all added together, this can be quite inefficient, |
| 4833 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 4834 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 4835 | // LLVM IR canonical form means we need only traverse the left operands. |
| 4836 | SmallVector<const SCEV *, 4> AddOps; |
| 4837 | do { |
| 4838 | if (BO->Op) { |
| 4839 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 4840 | AddOps.push_back(OpSCEV); |
| 4841 | break; |
| 4842 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4843 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4844 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 4845 | // addition, then compute the SCEV for this addition by itself |
| 4846 | // with a separate call to getAddExpr. We need to do that |
| 4847 | // instead of pushing the operands of the addition onto AddOps, |
| 4848 | // since the flags are only known to apply to this particular |
| 4849 | // addition - they may not apply to other additions that can be |
| 4850 | // formed with operands from AddOps. |
| 4851 | const SCEV *RHS = getSCEV(BO->RHS); |
| 4852 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 4853 | if (Flags != SCEV::FlagAnyWrap) { |
| 4854 | const SCEV *LHS = getSCEV(BO->LHS); |
| 4855 | if (BO->Opcode == Instruction::Sub) |
| 4856 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 4857 | else |
| 4858 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 4859 | break; |
| 4860 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4861 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4862 | |
| 4863 | if (BO->Opcode == Instruction::Sub) |
| 4864 | AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); |
| 4865 | else |
| 4866 | AddOps.push_back(getSCEV(BO->RHS)); |
| 4867 | |
| 4868 | auto NewBO = MatchBinaryOp(BO->LHS); |
| 4869 | if (!NewBO || (NewBO->Opcode != Instruction::Add && |
| 4870 | NewBO->Opcode != Instruction::Sub)) { |
| 4871 | AddOps.push_back(getSCEV(BO->LHS)); |
| 4872 | break; |
| 4873 | } |
| 4874 | BO = NewBO; |
| 4875 | } while (true); |
| 4876 | |
| 4877 | return getAddExpr(AddOps); |
| 4878 | } |
| 4879 | |
| 4880 | case Instruction::Mul: { |
| 4881 | SmallVector<const SCEV *, 4> MulOps; |
| 4882 | do { |
| 4883 | if (BO->Op) { |
| 4884 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 4885 | MulOps.push_back(OpSCEV); |
| 4886 | break; |
| 4887 | } |
| 4888 | |
| 4889 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 4890 | if (Flags != SCEV::FlagAnyWrap) { |
| 4891 | MulOps.push_back( |
| 4892 | getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); |
| 4893 | break; |
| 4894 | } |
| 4895 | } |
| 4896 | |
| 4897 | MulOps.push_back(getSCEV(BO->RHS)); |
| 4898 | auto NewBO = MatchBinaryOp(BO->LHS); |
| 4899 | if (!NewBO || NewBO->Opcode != Instruction::Mul) { |
| 4900 | MulOps.push_back(getSCEV(BO->LHS)); |
| 4901 | break; |
| 4902 | } |
| 4903 | BO = NewBO; |
| 4904 | } while (true); |
| 4905 | |
| 4906 | return getMulExpr(MulOps); |
| 4907 | } |
| 4908 | case Instruction::UDiv: |
| 4909 | return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); |
| 4910 | case Instruction::Sub: { |
| 4911 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4912 | if (BO->Op) |
| 4913 | Flags = getNoWrapFlagsFromUB(BO->Op); |
| 4914 | return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); |
| 4915 | } |
| 4916 | case Instruction::And: |
| 4917 | // For an expression like x&255 that merely masks off the high bits, |
| 4918 | // use zext(trunc(x)) as the SCEV expression. |
| 4919 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 4920 | if (CI->isNullValue()) |
| 4921 | return getSCEV(BO->RHS); |
| 4922 | if (CI->isAllOnesValue()) |
| 4923 | return getSCEV(BO->LHS); |
| 4924 | const APInt &A = CI->getValue(); |
| 4925 | |
| 4926 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 4927 | // constants, obscuring what would otherwise be a low-bits mask. |
| 4928 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
| 4929 | // knew about to reconstruct a low-bits mask value. |
| 4930 | unsigned LZ = A.countLeadingZeros(); |
| 4931 | unsigned TZ = A.countTrailingZeros(); |
| 4932 | unsigned BitWidth = A.getBitWidth(); |
| 4933 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 4934 | computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), |
| 4935 | 0, &AC, nullptr, &DT); |
| 4936 | |
| 4937 | APInt EffectiveMask = |
| 4938 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 4939 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
| 4940 | const SCEV *MulCount = getConstant(ConstantInt::get( |
| 4941 | getContext(), APInt::getOneBitSet(BitWidth, TZ))); |
| 4942 | return getMulExpr( |
| 4943 | getZeroExtendExpr( |
| 4944 | getTruncateExpr( |
| 4945 | getUDivExactExpr(getSCEV(BO->LHS), MulCount), |
| 4946 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 4947 | BO->LHS->getType()), |
| 4948 | MulCount); |
| 4949 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4950 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4951 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4952 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4953 | case Instruction::Or: |
| 4954 | // If the RHS of the Or is a constant, we may have something like: |
| 4955 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 4956 | // optimizations will transparently handle this case. |
| 4957 | // |
| 4958 | // In order for this transformation to be safe, the LHS must be of the |
| 4959 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 4960 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 4961 | const SCEV *LHS = getSCEV(BO->LHS); |
| 4962 | const APInt &CIVal = CI->getValue(); |
| 4963 | if (GetMinTrailingZeros(LHS) >= |
| 4964 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 4965 | // Build a plain add SCEV. |
| 4966 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 4967 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 4968 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 4969 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 4970 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
| 4971 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 4972 | OldAR->getNoWrapFlags()); |
| 4973 | } |
| 4974 | return S; |
| 4975 | } |
| 4976 | } |
| 4977 | break; |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 4978 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4979 | case Instruction::Xor: |
| 4980 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 4981 | // If the RHS of xor is -1, then this is a not operation. |
| 4982 | if (CI->isAllOnesValue()) |
| 4983 | return getNotSCEV(getSCEV(BO->LHS)); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4984 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 4985 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 4986 | // This is a variant of the check for xor with -1, and it handles |
| 4987 | // the case where instcombine has trimmed non-demanded bits out |
| 4988 | // of an xor with -1. |
| 4989 | if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) |
| 4990 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) |
| 4991 | if (LBO->getOpcode() == Instruction::And && |
| 4992 | LCI->getValue() == CI->getValue()) |
| 4993 | if (const SCEVZeroExtendExpr *Z = |
| 4994 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { |
| 4995 | Type *UTy = BO->LHS->getType(); |
| 4996 | const SCEV *Z0 = Z->getOperand(); |
| 4997 | Type *Z0Ty = Z0->getType(); |
| 4998 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4999 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5000 | // If C is a low-bits mask, the zero extend is serving to |
| 5001 | // mask off the high bits. Complement the operand and |
| 5002 | // re-apply the zext. |
| 5003 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 5004 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 5005 | |
| 5006 | // If C is a single bit, it may be in the sign-bit position |
| 5007 | // before the zero-extend. In this case, represent the xor |
| 5008 | // using an add, which is equivalent, and re-apply the zext. |
| 5009 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 5010 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
| 5011 | Trunc.isSignBit()) |
| 5012 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 5013 | UTy); |
| 5014 | } |
| 5015 | } |
| 5016 | break; |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5017 | |
| 5018 | case Instruction::Shl: |
| 5019 | // Turn shift left of a constant amount into a multiply. |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5020 | if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5021 | uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5022 | |
| 5023 | // If the shift count is not less than the bitwidth, the result of |
| 5024 | // the shift is undefined. Don't try to analyze it, because the |
| 5025 | // resolution chosen here may differ from the resolution chosen in |
| 5026 | // other parts of the compiler. |
| 5027 | if (SA->getValue().uge(BitWidth)) |
| 5028 | break; |
| 5029 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5030 | // It is currently not resolved how to interpret NSW for left |
| 5031 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 5032 | // case. Remove this check (or this comment) once the situation |
| 5033 | // is resolved. See |
| 5034 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 5035 | // and http://reviews.llvm.org/D8890 . |
| 5036 | auto Flags = SCEV::FlagAnyWrap; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5037 | if (BO->Op && SA->getValue().ult(BitWidth - 1)) |
| 5038 | Flags = getNoWrapFlagsFromUB(BO->Op); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5039 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5040 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 5041 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5042 | return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5043 | } |
| 5044 | break; |
| 5045 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5046 | case Instruction::AShr: |
| 5047 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 5048 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) |
| 5049 | if (Operator *L = dyn_cast<Operator>(BO->LHS)) |
| 5050 | if (L->getOpcode() == Instruction::Shl && |
| 5051 | L->getOperand(1) == BO->RHS) { |
| 5052 | uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5053 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5054 | // If the shift count is not less than the bitwidth, the result of |
| 5055 | // the shift is undefined. Don't try to analyze it, because the |
| 5056 | // resolution chosen here may differ from the resolution chosen in |
| 5057 | // other parts of the compiler. |
| 5058 | if (CI->getValue().uge(BitWidth)) |
| 5059 | break; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5060 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5061 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 5062 | if (Amt == BitWidth) |
| 5063 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
| 5064 | return getSignExtendExpr( |
| 5065 | getTruncateExpr(getSCEV(L->getOperand(0)), |
| 5066 | IntegerType::get(getContext(), Amt)), |
| 5067 | BO->LHS->getType()); |
| 5068 | } |
| 5069 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5070 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5071 | } |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5072 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame^] | 5073 | switch (U->getOpcode()) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5074 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5075 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5076 | |
| 5077 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5078 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5079 | |
| 5080 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5081 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5082 | |
| 5083 | case Instruction::BitCast: |
| 5084 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 5085 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5086 | return getSCEV(U->getOperand(0)); |
| 5087 | break; |
| 5088 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 5089 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 5090 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 5091 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 5092 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5093 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 5094 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 5095 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5096 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5097 | case Instruction::PHI: |
| 5098 | return createNodeForPHI(cast<PHINode>(U)); |
| 5099 | |
| 5100 | case Instruction::Select: |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 5101 | // U can also be a select constant expr, which let fall through. Since |
| 5102 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and |
| 5103 | // constant expressions cannot have instructions as operands, we'd have |
| 5104 | // returned getUnknown for a select constant expressions anyway. |
| 5105 | if (isa<Instruction>(U)) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 5106 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), |
| 5107 | U->getOperand(1), U->getOperand(2)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5108 | } |
| 5109 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5110 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5111 | } |
| 5112 | |
| 5113 | |
| 5114 | |
| 5115 | //===----------------------------------------------------------------------===// |
| 5116 | // Iteration Count Computation Code |
| 5117 | // |
| 5118 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5119 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 5120 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5121 | return getSmallConstantTripCount(L, ExitingBB); |
| 5122 | |
| 5123 | // No trip count information for multiple exits. |
| 5124 | return 0; |
| 5125 | } |
| 5126 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5127 | /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5128 | /// normal unsigned value. Returns 0 if the trip count is unknown or not |
| 5129 | /// constant. Will also return 0 if the maximum trip count is very large (>= |
| 5130 | /// 2^32). |
| 5131 | /// |
| 5132 | /// This "trip count" assumes that control exits via ExitingBlock. More |
| 5133 | /// precisely, it is the number of times that control may reach ExitingBlock |
| 5134 | /// before taking the branch. For loops with multiple exits, it may not be the |
| 5135 | /// number times that the loop header executes because the loop may exit |
| 5136 | /// prematurely via another branch. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5137 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 5138 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5139 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5140 | assert(L->isLoopExiting(ExitingBlock) && |
| 5141 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5142 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5143 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5144 | if (!ExitCount) |
| 5145 | return 0; |
| 5146 | |
| 5147 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 5148 | |
| 5149 | // Guard against huge trip counts. |
| 5150 | if (ExitConst->getValue().getActiveBits() > 32) |
| 5151 | return 0; |
| 5152 | |
| 5153 | // In case of integer overflow, this returns 0, which is correct. |
| 5154 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 5155 | } |
| 5156 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5157 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 5158 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5159 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 5160 | |
| 5161 | // No trip multiple information for multiple exits. |
| 5162 | return 0; |
| 5163 | } |
| 5164 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5165 | /// getSmallConstantTripMultiple - Returns the largest constant divisor of the |
| 5166 | /// trip count of this loop as a normal unsigned value, if possible. This |
| 5167 | /// means that the actual trip count is always a multiple of the returned |
| 5168 | /// value (don't forget the trip count could very well be zero as well!). |
| 5169 | /// |
| 5170 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 5171 | /// multiple of a constant (which is also the case if the trip count is simply |
| 5172 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 5173 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5174 | /// |
| 5175 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 5176 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5177 | unsigned |
| 5178 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 5179 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5180 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5181 | assert(L->isLoopExiting(ExitingBlock) && |
| 5182 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5183 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5184 | if (ExitCount == getCouldNotCompute()) |
| 5185 | return 1; |
| 5186 | |
| 5187 | // Get the trip count from the BE count by adding 1. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5188 | const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5189 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 5190 | // to factor simple cases. |
| 5191 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 5192 | TCMul = Mul->getOperand(0); |
| 5193 | |
| 5194 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 5195 | if (!MulC) |
| 5196 | return 1; |
| 5197 | |
| 5198 | ConstantInt *Result = MulC->getValue(); |
| 5199 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 5200 | // Guard against huge trip counts (this requires checking |
| 5201 | // for zero to handle the case where the trip count == -1 and the |
| 5202 | // addition wraps). |
| 5203 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 5204 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5205 | return 1; |
| 5206 | |
| 5207 | return (unsigned)Result->getZExtValue(); |
| 5208 | } |
| 5209 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5210 | // getExitCount - Get the expression for the number of loop iterations for which |
Andrew Trick | ee9143a | 2013-05-31 23:34:46 +0000 | [diff] [blame] | 5211 | // this loop is guaranteed not to exit via ExitingBlock. Otherwise return |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5212 | // SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5213 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 5214 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5215 | } |
| 5216 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5217 | /// getBackedgeTakenCount - If the specified loop has a predictable |
| 5218 | /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute |
| 5219 | /// object. The backedge-taken count is the number of times the loop header |
| 5220 | /// will be branched to from within the loop. This is one less than the |
| 5221 | /// trip count of the loop, since it doesn't count the first iteration, |
| 5222 | /// when the header is branched to from outside the loop. |
| 5223 | /// |
| 5224 | /// Note that it is not valid to call this method on a loop without a |
| 5225 | /// loop-invariant backedge-taken count (see |
| 5226 | /// hasLoopInvariantBackedgeTakenCount). |
| 5227 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5228 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5229 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5230 | } |
| 5231 | |
| 5232 | /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except |
| 5233 | /// return the least SCEV value that is known never to be less than the |
| 5234 | /// actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5235 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5236 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5237 | } |
| 5238 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5239 | /// PushLoopPHIs - Push PHI nodes in the header of the given loop |
| 5240 | /// onto the given Worklist. |
| 5241 | static void |
| 5242 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 5243 | BasicBlock *Header = L->getHeader(); |
| 5244 | |
| 5245 | // Push all Loop-header PHIs onto the Worklist stack. |
| 5246 | for (BasicBlock::iterator I = Header->begin(); |
| 5247 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 5248 | Worklist.push_back(PN); |
| 5249 | } |
| 5250 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5251 | const ScalarEvolution::BackedgeTakenInfo & |
| 5252 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5253 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5254 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5255 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 5256 | // code elsewhere that it shouldn't attempt to request a new |
| 5257 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5258 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5259 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5260 | if (!Pair.second) |
| 5261 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5262 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5263 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5264 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 5265 | // must be cleared in this scope. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5266 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5267 | |
| 5268 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 5269 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 5270 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5271 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 5272 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5273 | } |
| 5274 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 5275 | isa<PHINode>(L->getHeader()->begin())) { |
| 5276 | // Only count loops that have phi nodes as not being computable. |
| 5277 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5278 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5279 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5280 | // Now that we know more about the trip count for this loop, forget any |
| 5281 | // existing SCEV values for PHI nodes in this loop since they are only |
| 5282 | // conservative estimates made without the benefit of trip count |
| 5283 | // information. This is similar to the code in forgetLoop, except that |
| 5284 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5285 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5286 | SmallVector<Instruction *, 16> Worklist; |
| 5287 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5288 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5289 | SmallPtrSet<Instruction *, 8> Visited; |
| 5290 | while (!Worklist.empty()) { |
| 5291 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5292 | if (!Visited.insert(I).second) |
| 5293 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5294 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5295 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5296 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5297 | if (It != ValueExprMap.end()) { |
| 5298 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 5299 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5300 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 5301 | // structure, or it's a PHI that's in the progress of being computed |
| 5302 | // by createNodeForPHI. In the former case, additional loop trip |
| 5303 | // count information isn't going to change anything. In the later |
| 5304 | // case, createNodeForPHI will perform the necessary updates on its |
| 5305 | // own when it gets to that point. |
| 5306 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
| 5307 | forgetMemoizedResults(Old); |
| 5308 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5309 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5310 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5311 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5312 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5313 | |
| 5314 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5315 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5316 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5317 | |
| 5318 | // Re-lookup the insert position, since the call to |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5319 | // computeBackedgeTakenCount above could result in a |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5320 | // recusive call to getBackedgeTakenInfo (on a different |
| 5321 | // loop), which would invalidate the iterator computed |
| 5322 | // earlier. |
| 5323 | return BackedgeTakenCounts.find(L)->second = Result; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5324 | } |
| 5325 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5326 | /// forgetLoop - This method should be called by the client when it has |
| 5327 | /// changed a loop in a way that may effect ScalarEvolution's ability to |
| 5328 | /// compute a trip count, or if the loop is deleted. |
| 5329 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 5330 | // Drop any stored trip count value. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5331 | DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos = |
| 5332 | BackedgeTakenCounts.find(L); |
| 5333 | if (BTCPos != BackedgeTakenCounts.end()) { |
| 5334 | BTCPos->second.clear(); |
| 5335 | BackedgeTakenCounts.erase(BTCPos); |
| 5336 | } |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 5337 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5338 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5339 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5340 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5341 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5342 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5343 | while (!Worklist.empty()) { |
| 5344 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5345 | if (!Visited.insert(I).second) |
| 5346 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5347 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5348 | ValueExprMapType::iterator It = |
| 5349 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5350 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5351 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5352 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5353 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5354 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5355 | } |
| 5356 | |
| 5357 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5358 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 5359 | |
| 5360 | // Forget all contained loops too, to avoid dangling entries in the |
| 5361 | // ValuesAtScopes map. |
| 5362 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 5363 | forgetLoop(*I); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 5364 | } |
| 5365 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 5366 | /// forgetValue - This method should be called by the client when it has |
| 5367 | /// changed a value in a way that may effect its value, or which may |
| 5368 | /// disconnect it from a def-use chain linking it to a loop. |
| 5369 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5370 | Instruction *I = dyn_cast<Instruction>(V); |
| 5371 | if (!I) return; |
| 5372 | |
| 5373 | // Drop information about expressions based on loop-header PHIs. |
| 5374 | SmallVector<Instruction *, 16> Worklist; |
| 5375 | Worklist.push_back(I); |
| 5376 | |
| 5377 | SmallPtrSet<Instruction *, 8> Visited; |
| 5378 | while (!Worklist.empty()) { |
| 5379 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5380 | if (!Visited.insert(I).second) |
| 5381 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5382 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5383 | ValueExprMapType::iterator It = |
| 5384 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5385 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5386 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5387 | ValueExprMap.erase(It); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5388 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5389 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5390 | } |
| 5391 | |
| 5392 | PushDefUseChildren(I, Worklist); |
| 5393 | } |
| 5394 | } |
| 5395 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5396 | /// getExact - Get the exact loop backedge taken count considering all loop |
Sanjoy Das | 135e5b9 | 2015-07-21 20:59:22 +0000 | [diff] [blame] | 5397 | /// exits. A computable result can only be returned for loops with a single |
| 5398 | /// exit. Returning the minimum taken count among all exits is incorrect |
| 5399 | /// because one of the loop's exit limit's may have been skipped. HowFarToZero |
| 5400 | /// assumes that the limit of each loop test is never skipped. This is a valid |
| 5401 | /// assumption as long as the loop exits via that test. For precise results, it |
| 5402 | /// is the caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5403 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5404 | const SCEV * |
| 5405 | ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const { |
| 5406 | // If any exits were not computable, the loop is not computable. |
| 5407 | if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); |
| 5408 | |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5409 | // We need exactly one computable exit. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5410 | if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5411 | assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); |
| 5412 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5413 | const SCEV *BECount = nullptr; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5414 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5415 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5416 | |
| 5417 | assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
| 5418 | |
| 5419 | if (!BECount) |
| 5420 | BECount = ENT->ExactNotTaken; |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5421 | else if (BECount != ENT->ExactNotTaken) |
| 5422 | return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5423 | } |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 5424 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5425 | return BECount; |
| 5426 | } |
| 5427 | |
| 5428 | /// getExact - Get the exact not taken count for this loop exit. |
| 5429 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5430 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5431 | ScalarEvolution *SE) const { |
| 5432 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5433 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5434 | |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5435 | if (ENT->ExitingBlock == ExitingBlock) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5436 | return ENT->ExactNotTaken; |
| 5437 | } |
| 5438 | return SE->getCouldNotCompute(); |
| 5439 | } |
| 5440 | |
| 5441 | /// getMax - Get the max backedge taken count for the loop. |
| 5442 | const SCEV * |
| 5443 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
| 5444 | return Max ? Max : SE->getCouldNotCompute(); |
| 5445 | } |
| 5446 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5447 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 5448 | ScalarEvolution *SE) const { |
| 5449 | if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) |
| 5450 | return true; |
| 5451 | |
| 5452 | if (!ExitNotTaken.ExitingBlock) |
| 5453 | return false; |
| 5454 | |
| 5455 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5456 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5457 | |
| 5458 | if (ENT->ExactNotTaken != SE->getCouldNotCompute() |
| 5459 | && SE->hasOperand(ENT->ExactNotTaken, S)) { |
| 5460 | return true; |
| 5461 | } |
| 5462 | } |
| 5463 | return false; |
| 5464 | } |
| 5465 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5466 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 5467 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 5468 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
| 5469 | SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, |
| 5470 | bool Complete, const SCEV *MaxCount) : Max(MaxCount) { |
| 5471 | |
| 5472 | if (!Complete) |
| 5473 | ExitNotTaken.setIncomplete(); |
| 5474 | |
| 5475 | unsigned NumExits = ExitCounts.size(); |
| 5476 | if (NumExits == 0) return; |
| 5477 | |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5478 | ExitNotTaken.ExitingBlock = ExitCounts[0].first; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5479 | ExitNotTaken.ExactNotTaken = ExitCounts[0].second; |
| 5480 | if (NumExits == 1) return; |
| 5481 | |
| 5482 | // Handle the rare case of multiple computable exits. |
| 5483 | ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1]; |
| 5484 | |
| 5485 | ExitNotTakenInfo *PrevENT = &ExitNotTaken; |
| 5486 | for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) { |
| 5487 | PrevENT->setNextExit(ENT); |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5488 | ENT->ExitingBlock = ExitCounts[i].first; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5489 | ENT->ExactNotTaken = ExitCounts[i].second; |
| 5490 | } |
| 5491 | } |
| 5492 | |
| 5493 | /// clear - Invalidate this result and free the ExitNotTakenInfo array. |
| 5494 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5495 | ExitNotTaken.ExitingBlock = nullptr; |
| 5496 | ExitNotTaken.ExactNotTaken = nullptr; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5497 | delete[] ExitNotTaken.getNextExit(); |
| 5498 | } |
| 5499 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5500 | /// computeBackedgeTakenCount - Compute the number of times the backedge |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5501 | /// of the specified loop will execute. |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5502 | ScalarEvolution::BackedgeTakenInfo |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5503 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5504 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5505 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5506 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5507 | SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5508 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 5509 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5510 | const SCEV *MustExitMaxBECount = nullptr; |
| 5511 | const SCEV *MayExitMaxBECount = nullptr; |
| 5512 | |
| 5513 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 5514 | // and compute maxBECount. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5515 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5516 | BasicBlock *ExitBB = ExitingBlocks[i]; |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5517 | ExitLimit EL = computeExitLimit(L, ExitBB); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5518 | |
| 5519 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 5520 | // CouldComputeBECount is true only if all exits can be computed. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5521 | if (EL.Exact == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5522 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 5523 | // 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] | 5524 | CouldComputeBECount = false; |
| 5525 | else |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5526 | ExitCounts.push_back({ExitBB, EL.Exact}); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5527 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5528 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 5529 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 5530 | // LoopMustExits and LoopMayExits. |
| 5531 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5532 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5533 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
| 5534 | // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, |
| 5535 | // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is |
| 5536 | // considered greater than any computable EL.Max. |
| 5537 | if (EL.Max != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5538 | DT.dominates(ExitBB, Latch)) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5539 | if (!MustExitMaxBECount) |
| 5540 | MustExitMaxBECount = EL.Max; |
| 5541 | else { |
| 5542 | MustExitMaxBECount = |
| 5543 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5544 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5545 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
| 5546 | if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) |
| 5547 | MayExitMaxBECount = EL.Max; |
| 5548 | else { |
| 5549 | MayExitMaxBECount = |
| 5550 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); |
| 5551 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5552 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5553 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5554 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5555 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5556 | return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5557 | } |
| 5558 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5559 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5560 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5561 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5562 | // Okay, we've chosen an exiting block. See what condition causes us to exit |
| 5563 | // at this block and remember the exit block and whether all other targets |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5564 | // lead to the loop header. |
| 5565 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5566 | BasicBlock *Exit = nullptr; |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5567 | for (auto *SBB : successors(ExitingBlock)) |
| 5568 | if (!L->contains(SBB)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5569 | if (Exit) // Multiple exit successors. |
| 5570 | return getCouldNotCompute(); |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5571 | Exit = SBB; |
| 5572 | } else if (SBB != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5573 | MustExecuteLoopHeader = false; |
| 5574 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5575 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5576 | // At this point, we know we have a conditional branch that determines whether |
| 5577 | // the loop is exited. However, we don't know if the branch is executed each |
| 5578 | // time through the loop. If not, then the execution count of the branch will |
| 5579 | // not be equal to the trip count of the loop. |
| 5580 | // |
| 5581 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5582 | // 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] | 5583 | // 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] | 5584 | // loop header. This is common for un-rotated loops. |
| 5585 | // |
| 5586 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5587 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5588 | // header is reached, the execution count of the branch will be equal to the |
| 5589 | // trip count of the loop. |
| 5590 | // |
| 5591 | // More extensive analysis could be done to handle more cases here. |
| 5592 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5593 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5594 | // The simple checks failed, try climbing the unique predecessor chain |
| 5595 | // up to the header. |
| 5596 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5597 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5598 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5599 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5600 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5601 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5602 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5603 | if (PredSucc == BB) |
| 5604 | continue; |
| 5605 | // If the predecessor has a successor that isn't BB and isn't |
| 5606 | // outside the loop, assume the worst. |
| 5607 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5608 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5609 | } |
| 5610 | if (Pred == L->getHeader()) { |
| 5611 | Ok = true; |
| 5612 | break; |
| 5613 | } |
| 5614 | BB = Pred; |
| 5615 | } |
| 5616 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5617 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5618 | } |
| 5619 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5620 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5621 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5622 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5623 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5624 | // Proceed to the next level to examine the exit condition expression. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5625 | return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0), |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5626 | BI->getSuccessor(1), |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5627 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5628 | } |
| 5629 | |
| 5630 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5631 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5632 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5633 | |
| 5634 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5635 | } |
| 5636 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5637 | /// computeExitLimitFromCond - Compute the number of times the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5638 | /// backedge of the specified loop will execute if its exit condition |
| 5639 | /// were a conditional branch of ExitCond, TBB, and FBB. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5640 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5641 | /// @param ControlsExit is true if ExitCond directly controls the exit |
| 5642 | /// branch. In this case, we can assume that the loop exits only if the |
| 5643 | /// condition is true and can infer that failing to meet the condition prior to |
| 5644 | /// integer wraparound results in undefined behavior. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5645 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5646 | ScalarEvolution::computeExitLimitFromCond(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5647 | Value *ExitCond, |
| 5648 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5649 | BasicBlock *FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5650 | bool ControlsExit) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5651 | // 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] | 5652 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5653 | if (BO->getOpcode() == Instruction::And) { |
| 5654 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5655 | bool EitherMayExit = L->contains(TBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5656 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5657 | ControlsExit && !EitherMayExit); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5658 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5659 | ControlsExit && !EitherMayExit); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5660 | const SCEV *BECount = getCouldNotCompute(); |
| 5661 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5662 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5663 | // Both conditions must be true for the loop to continue executing. |
| 5664 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5665 | if (EL0.Exact == getCouldNotCompute() || |
| 5666 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5667 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5668 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5669 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5670 | if (EL0.Max == getCouldNotCompute()) |
| 5671 | MaxBECount = EL1.Max; |
| 5672 | else if (EL1.Max == getCouldNotCompute()) |
| 5673 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5674 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5675 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5676 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5677 | // Both conditions must be true at the same time for the loop to exit. |
| 5678 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5679 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5680 | if (EL0.Max == EL1.Max) |
| 5681 | MaxBECount = EL0.Max; |
| 5682 | if (EL0.Exact == EL1.Exact) |
| 5683 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5684 | } |
| 5685 | |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5686 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able |
| 5687 | // to be more aggressive when computing BECount than when computing |
| 5688 | // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact |
| 5689 | // to match, but for EL0.Max and EL1.Max to not. |
| 5690 | if (isa<SCEVCouldNotCompute>(MaxBECount) && |
| 5691 | !isa<SCEVCouldNotCompute>(BECount)) |
| 5692 | MaxBECount = BECount; |
| 5693 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5694 | return ExitLimit(BECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5695 | } |
| 5696 | if (BO->getOpcode() == Instruction::Or) { |
| 5697 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5698 | bool EitherMayExit = L->contains(FBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5699 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5700 | ControlsExit && !EitherMayExit); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5701 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5702 | ControlsExit && !EitherMayExit); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5703 | const SCEV *BECount = getCouldNotCompute(); |
| 5704 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5705 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5706 | // Both conditions must be false for the loop to continue executing. |
| 5707 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5708 | if (EL0.Exact == getCouldNotCompute() || |
| 5709 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5710 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5711 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5712 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5713 | if (EL0.Max == getCouldNotCompute()) |
| 5714 | MaxBECount = EL1.Max; |
| 5715 | else if (EL1.Max == getCouldNotCompute()) |
| 5716 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5717 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5718 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5719 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5720 | // Both conditions must be false at the same time for the loop to exit. |
| 5721 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5722 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5723 | if (EL0.Max == EL1.Max) |
| 5724 | MaxBECount = EL0.Max; |
| 5725 | if (EL0.Exact == EL1.Exact) |
| 5726 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5727 | } |
| 5728 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5729 | return ExitLimit(BECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5730 | } |
| 5731 | } |
| 5732 | |
| 5733 | // 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] | 5734 | // Proceed to the next level to examine the icmp. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5735 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5736 | return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5737 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5738 | // Check for a constant condition. These are normally stripped out by |
| 5739 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 5740 | // preserve the CFG and is temporarily leaving constant conditions |
| 5741 | // in place. |
| 5742 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 5743 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 5744 | // The backedge is always taken. |
| 5745 | return getCouldNotCompute(); |
| 5746 | else |
| 5747 | // The backedge is never taken. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5748 | return getZero(CI->getType()); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5749 | } |
| 5750 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5751 | // If it's not an integer or pointer comparison then compute it the hard way. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5752 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5753 | } |
| 5754 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5755 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5756 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5757 | ICmpInst *ExitCond, |
| 5758 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5759 | BasicBlock *FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5760 | bool ControlsExit) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5761 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5762 | // If the condition was exit on true, convert the condition to exit on false |
| 5763 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5764 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5765 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5766 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5767 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5768 | |
| 5769 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 5770 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 5771 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5772 | ExitLimit ItCnt = |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5773 | computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 5774 | if (ItCnt.hasAnyInfo()) |
| 5775 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5776 | } |
| 5777 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 5778 | ExitLimit ShiftEL = computeShiftCompareExitLimit( |
| 5779 | ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond); |
| 5780 | if (ShiftEL.hasAnyInfo()) |
| 5781 | return ShiftEL; |
| 5782 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5783 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 5784 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5785 | |
| 5786 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5787 | LHS = getSCEVAtScope(LHS, L); |
| 5788 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5789 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5790 | // 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] | 5791 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5792 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 5793 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5794 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5795 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5796 | } |
| 5797 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 5798 | // Simplify the operands before analyzing them. |
| 5799 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 5800 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5801 | // If we have a comparison of a chrec against a constant, try to use value |
| 5802 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5803 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 5804 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5805 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5806 | // Form the constant range. |
| 5807 | ConstantRange CompRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 5808 | ICmpInst::makeConstantRange(Cond, RHSC->getAPInt())); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5809 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5810 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5811 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5812 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5813 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5814 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5815 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5816 | // Convert to: while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5817 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5818 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5819 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5820 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 5821 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 5822 | // Convert to: while (X-Y == 0) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5823 | ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); |
| 5824 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5825 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5826 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5827 | case ICmpInst::ICMP_SLT: |
| 5828 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 5829 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5830 | ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5831 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5832 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5833 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5834 | case ICmpInst::ICMP_SGT: |
| 5835 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 5836 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5837 | ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5838 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5839 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5840 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5841 | default: |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 5842 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5843 | } |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5844 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5845 | } |
| 5846 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5847 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5848 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5849 | SwitchInst *Switch, |
| 5850 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5851 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5852 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 5853 | |
| 5854 | // Give up if the exit is the default dest of a switch. |
| 5855 | if (Switch->getDefaultDest() == ExitingBlock) |
| 5856 | return getCouldNotCompute(); |
| 5857 | |
| 5858 | assert(L->contains(Switch->getDefaultDest()) && |
| 5859 | "Default case must not exit the loop!"); |
| 5860 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 5861 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 5862 | |
| 5863 | // while (X != Y) --> while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5864 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5865 | if (EL.hasAnyInfo()) |
| 5866 | return EL; |
| 5867 | |
| 5868 | return getCouldNotCompute(); |
| 5869 | } |
| 5870 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5871 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 5872 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 5873 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5874 | const SCEV *InVal = SE.getConstant(C); |
| 5875 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5876 | assert(isa<SCEVConstant>(Val) && |
| 5877 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 5878 | return cast<SCEVConstant>(Val)->getValue(); |
| 5879 | } |
| 5880 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5881 | /// computeLoadConstantCompareExitLimit - Given an exit condition of |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5882 | /// 'icmp op load X, cst', try to see if we can compute the backedge |
| 5883 | /// execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5884 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5885 | ScalarEvolution::computeLoadConstantCompareExitLimit( |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5886 | LoadInst *LI, |
| 5887 | Constant *RHS, |
| 5888 | const Loop *L, |
| 5889 | ICmpInst::Predicate predicate) { |
| 5890 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5891 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5892 | |
| 5893 | // 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] | 5894 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5895 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5896 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5897 | |
| 5898 | // Make sure that it is really a constant global we are gepping, with an |
| 5899 | // initializer, and make sure the first IDX is really 0. |
| 5900 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 5901 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5902 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 5903 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5904 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5905 | |
| 5906 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5907 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 5908 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5909 | unsigned VarIdxNum = 0; |
| 5910 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 5911 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 5912 | Indexes.push_back(CI); |
| 5913 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5914 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5915 | VarIdx = GEP->getOperand(i); |
| 5916 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5917 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5918 | } |
| 5919 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 5920 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 5921 | if (!VarIdx) |
| 5922 | return getCouldNotCompute(); |
| 5923 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5924 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 5925 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5926 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5927 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5928 | |
| 5929 | // We can only recognize very limited forms of loop index expressions, in |
| 5930 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5931 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5932 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5933 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 5934 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5935 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5936 | |
| 5937 | unsigned MaxSteps = MaxBruteForceIterations; |
| 5938 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5939 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 5940 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5941 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5942 | |
| 5943 | // Form the GEP offset. |
| 5944 | Indexes[VarIdxNum] = Val; |
| 5945 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 5946 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 5947 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5948 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5949 | |
| 5950 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5951 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 5952 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 5953 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5954 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5955 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5956 | } |
| 5957 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5958 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5959 | } |
| 5960 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 5961 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( |
| 5962 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { |
| 5963 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); |
| 5964 | if (!RHS) |
| 5965 | return getCouldNotCompute(); |
| 5966 | |
| 5967 | const BasicBlock *Latch = L->getLoopLatch(); |
| 5968 | if (!Latch) |
| 5969 | return getCouldNotCompute(); |
| 5970 | |
| 5971 | const BasicBlock *Predecessor = L->getLoopPredecessor(); |
| 5972 | if (!Predecessor) |
| 5973 | return getCouldNotCompute(); |
| 5974 | |
| 5975 | // Return true if V is of the form "LHS `shift_op` <positive constant>". |
| 5976 | // Return LHS in OutLHS and shift_opt in OutOpCode. |
| 5977 | auto MatchPositiveShift = |
| 5978 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { |
| 5979 | |
| 5980 | using namespace PatternMatch; |
| 5981 | |
| 5982 | ConstantInt *ShiftAmt; |
| 5983 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 5984 | OutOpCode = Instruction::LShr; |
| 5985 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 5986 | OutOpCode = Instruction::AShr; |
| 5987 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 5988 | OutOpCode = Instruction::Shl; |
| 5989 | else |
| 5990 | return false; |
| 5991 | |
| 5992 | return ShiftAmt->getValue().isStrictlyPositive(); |
| 5993 | }; |
| 5994 | |
| 5995 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in |
| 5996 | // |
| 5997 | // loop: |
| 5998 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] |
| 5999 | // %iv.shifted = lshr i32 %iv, <positive constant> |
| 6000 | // |
| 6001 | // Return true on a succesful match. Return the corresponding PHI node (%iv |
| 6002 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. |
| 6003 | auto MatchShiftRecurrence = |
| 6004 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { |
| 6005 | Optional<Instruction::BinaryOps> PostShiftOpCode; |
| 6006 | |
| 6007 | { |
| 6008 | Instruction::BinaryOps OpC; |
| 6009 | Value *V; |
| 6010 | |
| 6011 | // If we encounter a shift instruction, "peel off" the shift operation, |
| 6012 | // and remember that we did so. Later when we inspect %iv's backedge |
| 6013 | // value, we will make sure that the backedge value uses the same |
| 6014 | // operation. |
| 6015 | // |
| 6016 | // Note: the peeled shift operation does not have to be the same |
| 6017 | // instruction as the one feeding into the PHI's backedge value. We only |
| 6018 | // really care about it being the same *kind* of shift instruction -- |
| 6019 | // that's all that is required for our later inferences to hold. |
| 6020 | if (MatchPositiveShift(LHS, V, OpC)) { |
| 6021 | PostShiftOpCode = OpC; |
| 6022 | LHS = V; |
| 6023 | } |
| 6024 | } |
| 6025 | |
| 6026 | PNOut = dyn_cast<PHINode>(LHS); |
| 6027 | if (!PNOut || PNOut->getParent() != L->getHeader()) |
| 6028 | return false; |
| 6029 | |
| 6030 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); |
| 6031 | Value *OpLHS; |
| 6032 | |
| 6033 | return |
| 6034 | // The backedge value for the PHI node must be a shift by a positive |
| 6035 | // amount |
| 6036 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && |
| 6037 | |
| 6038 | // of the PHI node itself |
| 6039 | OpLHS == PNOut && |
| 6040 | |
| 6041 | // and the kind of shift should be match the kind of shift we peeled |
| 6042 | // off, if any. |
| 6043 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); |
| 6044 | }; |
| 6045 | |
| 6046 | PHINode *PN; |
| 6047 | Instruction::BinaryOps OpCode; |
| 6048 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) |
| 6049 | return getCouldNotCompute(); |
| 6050 | |
| 6051 | const DataLayout &DL = getDataLayout(); |
| 6052 | |
| 6053 | // The key rationale for this optimization is that for some kinds of shift |
| 6054 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 |
| 6055 | // within a finite number of iterations. If the condition guarding the |
| 6056 | // backedge (in the sense that the backedge is taken if the condition is true) |
| 6057 | // is false for the value the shift recurrence stabilizes to, then we know |
| 6058 | // that the backedge is taken only a finite number of times. |
| 6059 | |
| 6060 | ConstantInt *StableValue = nullptr; |
| 6061 | switch (OpCode) { |
| 6062 | default: |
| 6063 | llvm_unreachable("Impossible case!"); |
| 6064 | |
| 6065 | case Instruction::AShr: { |
| 6066 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most |
| 6067 | // bitwidth(K) iterations. |
| 6068 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); |
| 6069 | bool KnownZero, KnownOne; |
| 6070 | ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, |
| 6071 | Predecessor->getTerminator(), &DT); |
| 6072 | auto *Ty = cast<IntegerType>(RHS->getType()); |
| 6073 | if (KnownZero) |
| 6074 | StableValue = ConstantInt::get(Ty, 0); |
| 6075 | else if (KnownOne) |
| 6076 | StableValue = ConstantInt::get(Ty, -1, true); |
| 6077 | else |
| 6078 | return getCouldNotCompute(); |
| 6079 | |
| 6080 | break; |
| 6081 | } |
| 6082 | case Instruction::LShr: |
| 6083 | case Instruction::Shl: |
| 6084 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} |
| 6085 | // stabilize to 0 in at most bitwidth(K) iterations. |
| 6086 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); |
| 6087 | break; |
| 6088 | } |
| 6089 | |
| 6090 | auto *Result = |
| 6091 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); |
| 6092 | assert(Result->getType()->isIntegerTy(1) && |
| 6093 | "Otherwise cannot be an operand to a branch instruction"); |
| 6094 | |
| 6095 | if (Result->isZeroValue()) { |
| 6096 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 6097 | const SCEV *UpperBound = |
| 6098 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); |
| 6099 | return ExitLimit(getCouldNotCompute(), UpperBound); |
| 6100 | } |
| 6101 | |
| 6102 | return getCouldNotCompute(); |
| 6103 | } |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6104 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6105 | /// CanConstantFold - Return true if we can constant fold an instruction of the |
| 6106 | /// specified type, assuming that all operands were constants. |
| 6107 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 6108 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6109 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 6110 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6111 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6112 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6113 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 6114 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 6115 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6116 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6117 | } |
| 6118 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6119 | /// Determine whether this instruction can constant evolve within this loop |
| 6120 | /// assuming its operands can all constant evolve. |
| 6121 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 6122 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 6123 | if (!L->contains(I)) return false; |
| 6124 | |
| 6125 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 6126 | // We don't currently keep track of the control flow needed to evaluate |
| 6127 | // PHIs, so we cannot handle PHIs inside of loops. |
| 6128 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6129 | } |
| 6130 | |
| 6131 | // If we won't be able to constant fold this expression even if the operands |
| 6132 | // are constants, bail early. |
| 6133 | return CanConstantFold(I); |
| 6134 | } |
| 6135 | |
| 6136 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 6137 | /// recursing through each instruction operand until reaching a loop header phi. |
| 6138 | static PHINode * |
| 6139 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6140 | DenseMap<Instruction *, PHINode *> &PHIMap) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6141 | |
| 6142 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 6143 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6144 | PHINode *PHI = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6145 | for (Value *Op : UseInst->operands()) { |
| 6146 | if (isa<Constant>(Op)) continue; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6147 | |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6148 | Instruction *OpInst = dyn_cast<Instruction>(Op); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6149 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6150 | |
| 6151 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 6152 | if (!P) |
| 6153 | // If this operand is already visited, reuse the prior result. |
| 6154 | // We may have P != PHI if this is the deepest point at which the |
| 6155 | // inconsistent paths meet. |
| 6156 | P = PHIMap.lookup(OpInst); |
| 6157 | if (!P) { |
| 6158 | // Recurse and memoize the results, whether a phi is found or not. |
| 6159 | // This recursive call invalidates pointers into PHIMap. |
| 6160 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); |
| 6161 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6162 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6163 | if (!P) |
| 6164 | return nullptr; // Not evolving from PHI |
| 6165 | if (PHI && PHI != P) |
| 6166 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6167 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6168 | } |
| 6169 | // This is a expression evolving from a constant PHI! |
| 6170 | return PHI; |
| 6171 | } |
| 6172 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6173 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 6174 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 6175 | /// way, but the operands of an operation must either be constants or a value |
| 6176 | /// derived from a constant PHI. If this expression does not fit with these |
| 6177 | /// constraints, return null. |
| 6178 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6179 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6180 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6181 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 6182 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6183 | return PN; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6184 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6185 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6186 | DenseMap<Instruction *, PHINode *> PHIMap; |
| 6187 | return getConstantEvolvingPHIOperands(I, L, PHIMap); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6188 | } |
| 6189 | |
| 6190 | /// EvaluateExpression - Given an expression that passes the |
| 6191 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 6192 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 6193 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6194 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 6195 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6196 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 6197 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6198 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 6199 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6200 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6201 | if (!I) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6202 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6203 | if (Constant *C = Vals.lookup(I)) return C; |
| 6204 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6205 | // An instruction inside the loop depends on a value outside the loop that we |
| 6206 | // 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] | 6207 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6208 | |
| 6209 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 6210 | // or due to this not being the initial iteration through a loop where we |
| 6211 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6212 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6213 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 6214 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6215 | |
| 6216 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6217 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 6218 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 6219 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6220 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6221 | continue; |
| 6222 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6223 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6224 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6225 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6226 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6227 | } |
| 6228 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6229 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 6230 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6231 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6232 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6233 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6234 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6235 | } |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6236 | return ConstantFoldInstOperands(I, Operands, DL, TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6237 | } |
| 6238 | |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6239 | |
| 6240 | // If every incoming value to PN except the one for BB is a specific Constant, |
| 6241 | // return that, else return nullptr. |
| 6242 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { |
| 6243 | Constant *IncomingVal = nullptr; |
| 6244 | |
| 6245 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 6246 | if (PN->getIncomingBlock(i) == BB) |
| 6247 | continue; |
| 6248 | |
| 6249 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 6250 | if (!CurrentVal) |
| 6251 | return nullptr; |
| 6252 | |
| 6253 | if (IncomingVal != CurrentVal) { |
| 6254 | if (IncomingVal) |
| 6255 | return nullptr; |
| 6256 | IncomingVal = CurrentVal; |
| 6257 | } |
| 6258 | } |
| 6259 | |
| 6260 | return IncomingVal; |
| 6261 | } |
| 6262 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6263 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 6264 | /// in the header of its containing loop, we know the loop executes a |
| 6265 | /// constant number of times, and the PHI node is just a recurrence |
| 6266 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6267 | Constant * |
| 6268 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 6269 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6270 | const Loop *L) { |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6271 | auto I = ConstantEvolutionLoopExitValue.find(PN); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6272 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 6273 | return I->second; |
| 6274 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 6275 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6276 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6277 | |
| 6278 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 6279 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6280 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6281 | BasicBlock *Header = L->getHeader(); |
| 6282 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6283 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6284 | BasicBlock *Latch = L->getLoopLatch(); |
| 6285 | if (!Latch) |
| 6286 | return nullptr; |
| 6287 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6288 | for (auto &I : *Header) { |
| 6289 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6290 | if (!PHI) break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6291 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6292 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6293 | CurrentIterVals[PHI] = StartCST; |
| 6294 | } |
| 6295 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6296 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6297 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6298 | Value *BEValue = PN->getIncomingValueForBlock(Latch); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6299 | |
| 6300 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6301 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6302 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6303 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6304 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6305 | unsigned IterationNum = 0; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6306 | const DataLayout &DL = getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6307 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6308 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6309 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6310 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6311 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6312 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6313 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6314 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6315 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6316 | if (!NextPHI) |
| 6317 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6318 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6319 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6320 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 6321 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6322 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 6323 | // cease to be able to evaluate one of them or if they stop evolving, |
| 6324 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6325 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6326 | for (const auto &I : CurrentIterVals) { |
| 6327 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 6328 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6329 | PHIsToCompute.emplace_back(PHI, I.second); |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6330 | } |
| 6331 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 6332 | // iterators into CurrentIterVals. |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6333 | for (const auto &I : PHIsToCompute) { |
| 6334 | PHINode *PHI = I.first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6335 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6336 | if (!NextPHI) { // Not already computed. |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6337 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6338 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6339 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6340 | if (NextPHI != I.second) |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6341 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6342 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6343 | |
| 6344 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 6345 | // iterating, the loop can't continue to change. |
| 6346 | if (StoppedEvolving) |
| 6347 | return RetVal = CurrentIterVals[PN]; |
| 6348 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6349 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6350 | } |
| 6351 | } |
| 6352 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6353 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6354 | Value *Cond, |
| 6355 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6356 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6357 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6358 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 6359 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 6360 | // That's the only form we support here. |
| 6361 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 6362 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6363 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 6364 | BasicBlock *Header = L->getHeader(); |
| 6365 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 6366 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6367 | BasicBlock *Latch = L->getLoopLatch(); |
| 6368 | assert(Latch && "Should follow from NumIncomingValues == 2!"); |
| 6369 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6370 | for (auto &I : *Header) { |
| 6371 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6372 | if (!PHI) |
| 6373 | break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6374 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6375 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6376 | CurrentIterVals[PHI] = StartCST; |
| 6377 | } |
| 6378 | if (!CurrentIterVals.count(PN)) |
| 6379 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6380 | |
| 6381 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 6382 | // the loop symbolically to determine when the condition gets a value of |
| 6383 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 6384 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6385 | const DataLayout &DL = getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6386 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6387 | auto *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6388 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6389 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6390 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6391 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6392 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6393 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6394 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 6395 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6396 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6397 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6398 | // Update all the PHI nodes for the next iteration. |
| 6399 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6400 | |
| 6401 | // Create a list of which PHIs we need to compute. We want to do this before |
| 6402 | // calling EvaluateExpression on them because that may invalidate iterators |
| 6403 | // into CurrentIterVals. |
| 6404 | SmallVector<PHINode *, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6405 | for (const auto &I : CurrentIterVals) { |
| 6406 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6407 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6408 | PHIsToCompute.push_back(PHI); |
| 6409 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6410 | for (PHINode *PHI : PHIsToCompute) { |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6411 | Constant *&NextPHI = NextIterVals[PHI]; |
| 6412 | if (NextPHI) continue; // Already computed! |
| 6413 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6414 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6415 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6416 | } |
| 6417 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6418 | } |
| 6419 | |
| 6420 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6421 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6422 | } |
| 6423 | |
Dan Gohman | 237d9e5 | 2009-09-03 15:00:26 +0000 | [diff] [blame] | 6424 | /// getSCEVAtScope - Return a SCEV expression for the specified value |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6425 | /// at the specified scope in the program. The L value specifies a loop |
| 6426 | /// nest to evaluate the expression at, where null is the top-level or a |
| 6427 | /// specified loop is immediately inside of the loop. |
| 6428 | /// |
| 6429 | /// This method can be used to compute the exit value for a variable defined |
| 6430 | /// in a loop by querying what the value will hold in the parent loop. |
| 6431 | /// |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6432 | /// In the case that a relevant loop exit value cannot be computed, the |
| 6433 | /// original value V is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6434 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6435 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = |
| 6436 | ValuesAtScopes[V]; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6437 | // Check to see if we've folded this expression at this loop before. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6438 | for (auto &LS : Values) |
| 6439 | if (LS.first == L) |
| 6440 | return LS.second ? LS.second : V; |
| 6441 | |
| 6442 | Values.emplace_back(L, nullptr); |
| 6443 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6444 | // Otherwise compute it. |
| 6445 | const SCEV *C = computeSCEVAtScope(V, L); |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6446 | for (auto &LS : reverse(ValuesAtScopes[V])) |
| 6447 | if (LS.first == L) { |
| 6448 | LS.second = C; |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 6449 | break; |
| 6450 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6451 | return C; |
| 6452 | } |
| 6453 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6454 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 6455 | /// will return Constants for objects which aren't represented by a |
| 6456 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 6457 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 6458 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6459 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6460 | case scCouldNotCompute: |
| 6461 | case scAddRecExpr: |
| 6462 | break; |
| 6463 | case scConstant: |
| 6464 | return cast<SCEVConstant>(V)->getValue(); |
| 6465 | case scUnknown: |
| 6466 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 6467 | case scSignExtend: { |
| 6468 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 6469 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 6470 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 6471 | break; |
| 6472 | } |
| 6473 | case scZeroExtend: { |
| 6474 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 6475 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 6476 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 6477 | break; |
| 6478 | } |
| 6479 | case scTruncate: { |
| 6480 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 6481 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 6482 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 6483 | break; |
| 6484 | } |
| 6485 | case scAddExpr: { |
| 6486 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 6487 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6488 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6489 | unsigned AS = PTy->getAddressSpace(); |
| 6490 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 6491 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 6492 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6493 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 6494 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6495 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6496 | |
| 6497 | // First pointer! |
| 6498 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6499 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6500 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6501 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6502 | // The offsets have been converted to bytes. We can add bytes to an |
| 6503 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6504 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6505 | } |
| 6506 | |
| 6507 | // Don't bother trying to sum two pointers. We probably can't |
| 6508 | // statically compute a load that results from it anyway. |
| 6509 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6510 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6511 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6512 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6513 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6514 | C2 = ConstantExpr::getIntegerCast( |
| 6515 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 6516 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6517 | } else |
| 6518 | C = ConstantExpr::getAdd(C, C2); |
| 6519 | } |
| 6520 | return C; |
| 6521 | } |
| 6522 | break; |
| 6523 | } |
| 6524 | case scMulExpr: { |
| 6525 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 6526 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 6527 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6528 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6529 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 6530 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6531 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6532 | C = ConstantExpr::getMul(C, C2); |
| 6533 | } |
| 6534 | return C; |
| 6535 | } |
| 6536 | break; |
| 6537 | } |
| 6538 | case scUDivExpr: { |
| 6539 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 6540 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 6541 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 6542 | if (LHS->getType() == RHS->getType()) |
| 6543 | return ConstantExpr::getUDiv(LHS, RHS); |
| 6544 | break; |
| 6545 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6546 | case scSMaxExpr: |
| 6547 | case scUMaxExpr: |
| 6548 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6549 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6550 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6551 | } |
| 6552 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6553 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6554 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6555 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6556 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6557 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6558 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6559 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6560 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6561 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 6562 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 6563 | if (PN->getParent() == LI->getHeader()) { |
| 6564 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6565 | // to see if the loop that contains it has a known backedge-taken |
| 6566 | // count. If so, we may be able to force computation of the exit |
| 6567 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6568 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6569 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6570 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6571 | // Okay, we know how many times the containing loop executes. If |
| 6572 | // this is a constant evolving PHI node, get the final value at |
| 6573 | // the specified iteration number. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6574 | Constant *RV = |
| 6575 | getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 6576 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6577 | } |
| 6578 | } |
| 6579 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6580 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6581 | // 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] | 6582 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6583 | // result. This is particularly useful for computing loop exit values. |
| 6584 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6585 | SmallVector<Constant *, 4> Operands; |
| 6586 | bool MadeImprovement = false; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 6587 | for (Value *Op : I->operands()) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6588 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 6589 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6590 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6591 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6592 | |
| 6593 | // If any of the operands is non-constant and if they are |
| 6594 | // non-integer and non-pointer, don't even try to analyze them |
| 6595 | // with scev techniques. |
| 6596 | if (!isSCEVable(Op->getType())) |
| 6597 | return V; |
| 6598 | |
| 6599 | const SCEV *OrigV = getSCEV(Op); |
| 6600 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 6601 | MadeImprovement |= OrigV != OpV; |
| 6602 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6603 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6604 | if (!C) return V; |
| 6605 | if (C->getType() != Op->getType()) |
| 6606 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 6607 | Op->getType(), |
| 6608 | false), |
| 6609 | C, Op->getType()); |
| 6610 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6611 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6612 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6613 | // Check to see if getSCEVAtScope actually made an improvement. |
| 6614 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6615 | Constant *C = nullptr; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6616 | const DataLayout &DL = getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6617 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6618 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6619 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6620 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6621 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6622 | C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6623 | } else |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6624 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6625 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 6626 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6627 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6628 | } |
| 6629 | } |
| 6630 | |
| 6631 | // This is some other type of SCEVUnknown, just return it. |
| 6632 | return V; |
| 6633 | } |
| 6634 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6635 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6636 | // Avoid performing the look-up in the common case where the specified |
| 6637 | // expression has no loop-variant portions. |
| 6638 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6639 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6640 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6641 | // Okay, at least one of these operands is loop variant but might be |
| 6642 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6643 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 6644 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6645 | NewOps.push_back(OpAtScope); |
| 6646 | |
| 6647 | for (++i; i != e; ++i) { |
| 6648 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6649 | NewOps.push_back(OpAtScope); |
| 6650 | } |
| 6651 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6652 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6653 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6654 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6655 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6656 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6657 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6658 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6659 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6660 | } |
| 6661 | } |
| 6662 | // If we got here, all operands are loop invariant. |
| 6663 | return Comm; |
| 6664 | } |
| 6665 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6666 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6667 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 6668 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 6669 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 6670 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6671 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6672 | } |
| 6673 | |
| 6674 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6675 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6676 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6677 | // First, attempt to evaluate each operand. |
| 6678 | // Avoid performing the look-up in the common case where the specified |
| 6679 | // expression has no loop-variant portions. |
| 6680 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6681 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6682 | if (OpAtScope == AddRec->getOperand(i)) |
| 6683 | continue; |
| 6684 | |
| 6685 | // Okay, at least one of these operands is loop variant but might be |
| 6686 | // foldable. Build a new instance of the folded commutative expression. |
| 6687 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6688 | AddRec->op_begin()+i); |
| 6689 | NewOps.push_back(OpAtScope); |
| 6690 | for (++i; i != e; ++i) |
| 6691 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6692 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6693 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6694 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6695 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6696 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6697 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6698 | // induction variable is multiplied by zero after constant folding. Go |
| 6699 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6700 | if (!AddRec) |
| 6701 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6702 | break; |
| 6703 | } |
| 6704 | |
| 6705 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6706 | // loop exit value of the addrec. |
| 6707 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6708 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6709 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6710 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6711 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6712 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6713 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6714 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6715 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6716 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6717 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6718 | } |
| 6719 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6720 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6721 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6722 | if (Op == Cast->getOperand()) |
| 6723 | return Cast; // must be loop invariant |
| 6724 | return getZeroExtendExpr(Op, Cast->getType()); |
| 6725 | } |
| 6726 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6727 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6728 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6729 | if (Op == Cast->getOperand()) |
| 6730 | return Cast; // must be loop invariant |
| 6731 | return getSignExtendExpr(Op, Cast->getType()); |
| 6732 | } |
| 6733 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6734 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6735 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6736 | if (Op == Cast->getOperand()) |
| 6737 | return Cast; // must be loop invariant |
| 6738 | return getTruncateExpr(Op, Cast->getType()); |
| 6739 | } |
| 6740 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6741 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6742 | } |
| 6743 | |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6744 | /// getSCEVAtScope - This is a convenience function which does |
| 6745 | /// getSCEVAtScope(getSCEV(V), L). |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6746 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6747 | return getSCEVAtScope(getSCEV(V), L); |
| 6748 | } |
| 6749 | |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6750 | /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the |
| 6751 | /// following equation: |
| 6752 | /// |
| 6753 | /// A * X = B (mod N) |
| 6754 | /// |
| 6755 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 6756 | /// A and B isn't important. |
| 6757 | /// |
| 6758 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6759 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6760 | ScalarEvolution &SE) { |
| 6761 | uint32_t BW = A.getBitWidth(); |
| 6762 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 6763 | assert(A != 0 && "A must be non-zero."); |
| 6764 | |
| 6765 | // 1. D = gcd(A, N) |
| 6766 | // |
| 6767 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 6768 | // trailing zeros in A is its multiplicity |
| 6769 | uint32_t Mult2 = A.countTrailingZeros(); |
| 6770 | // D = 2^Mult2 |
| 6771 | |
| 6772 | // 2. Check if B is divisible by D. |
| 6773 | // |
| 6774 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 6775 | // is not less than multiplicity of this prime factor for D. |
| 6776 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 6777 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6778 | |
| 6779 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 6780 | // modulo (N / D). |
| 6781 | // |
| 6782 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 6783 | // bit width during computations. |
| 6784 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 6785 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 6786 | Mod.setBit(BW - Mult2); // Mod = N / D |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6787 | APInt I = AD.multiplicativeInverse(Mod); |
| 6788 | |
| 6789 | // 4. Compute the minimum unsigned root of the equation: |
| 6790 | // I * (B / D) mod (N / D) |
| 6791 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 6792 | |
| 6793 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 6794 | // bits. |
| 6795 | return SE.getConstant(Result.trunc(BW)); |
| 6796 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6797 | |
| 6798 | /// SolveQuadraticEquation - Find the roots of the quadratic equation for the |
| 6799 | /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which |
| 6800 | /// might be the same) or two SCEVCouldNotCompute objects. |
| 6801 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6802 | static std::pair<const SCEV *,const SCEV *> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6803 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6804 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6805 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 6806 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 6807 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6808 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6809 | // We currently can only solve this if the coefficients are constants. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6810 | if (!LC || !MC || !NC) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6811 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6812 | return {CNC, CNC}; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6813 | } |
| 6814 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6815 | uint32_t BitWidth = LC->getAPInt().getBitWidth(); |
| 6816 | const APInt &L = LC->getAPInt(); |
| 6817 | const APInt &M = MC->getAPInt(); |
| 6818 | const APInt &N = NC->getAPInt(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6819 | APInt Two(BitWidth, 2); |
| 6820 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6821 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6822 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6823 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6824 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6825 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 6826 | // The B coefficient is M-N/2 |
| 6827 | APInt B(M); |
| 6828 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6829 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6830 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6831 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6832 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6833 | // Compute the B^2-4ac term. |
| 6834 | APInt SqrtTerm(B); |
| 6835 | SqrtTerm *= B; |
| 6836 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6837 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6838 | if (SqrtTerm.isNegative()) { |
| 6839 | // The loop is provably infinite. |
| 6840 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6841 | return {CNC, CNC}; |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6842 | } |
| 6843 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6844 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 6845 | // integer value or else APInt::sqrt() will assert. |
| 6846 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6847 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6848 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6849 | // The divisions must be performed as signed divisions. |
| 6850 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6851 | APInt TwoA(A << 1); |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6852 | if (TwoA.isMinValue()) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6853 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6854 | return {CNC, CNC}; |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6855 | } |
| 6856 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 6857 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6858 | |
| 6859 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6860 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6861 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6862 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6863 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6864 | return {SE.getConstant(Solution1), SE.getConstant(Solution2)}; |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6865 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6866 | } |
| 6867 | |
| 6868 | /// HowFarToZero - Return the number of times a backedge comparing the specified |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 6869 | /// value to zero will execute. If not computable, return CouldNotCompute. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6870 | /// |
| 6871 | /// This is only used for loops with a "x != y" exit test. The exit condition is |
| 6872 | /// now expressed as a single expression, V = x-y. So the exit test is |
| 6873 | /// effectively V != 0. We know and take advantage of the fact that this |
| 6874 | /// expression only being used in a comparison by zero context. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6875 | ScalarEvolution::ExitLimit |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6876 | ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6877 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6878 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6879 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 6880 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6881 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6882 | } |
| 6883 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6884 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6885 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6886 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6887 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6888 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 6889 | // the quadratic equation to solve it. |
| 6890 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
| 6891 | std::pair<const SCEV *,const SCEV *> Roots = |
| 6892 | SolveQuadraticEquation(AddRec, *this); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6893 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 6894 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6895 | if (R1 && R2) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6896 | // Pick the smallest positive root value. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6897 | if (ConstantInt *CB = |
Chris Lattner | 28f140a | 2011-01-09 22:58:47 +0000 | [diff] [blame] | 6898 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, |
| 6899 | R1->getValue(), |
| 6900 | R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6901 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6902 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 6903 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6904 | // We can only use this value if the chrec ends up with an exact zero |
| 6905 | // value at this index. When solving for "X*X != 5", for example, we |
| 6906 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6907 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 6908 | if (Val->isZero()) |
| 6909 | return R1; // We found a quadratic root! |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6910 | } |
| 6911 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6912 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6913 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6914 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6915 | // Otherwise we can only handle this if it is affine. |
| 6916 | if (!AddRec->isAffine()) |
| 6917 | return getCouldNotCompute(); |
| 6918 | |
| 6919 | // If this is an affine expression, the execution count of this branch is |
| 6920 | // the minimum unsigned root of the following equation: |
| 6921 | // |
| 6922 | // Start + Step*N = 0 (mod 2^BW) |
| 6923 | // |
| 6924 | // equivalent to: |
| 6925 | // |
| 6926 | // Step*N = -Start (mod 2^BW) |
| 6927 | // |
| 6928 | // where BW is the common bit width of Start and Step. |
| 6929 | |
| 6930 | // Get the initial value for the loop. |
| 6931 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 6932 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 6933 | |
| 6934 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6935 | // |
| 6936 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 6937 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 6938 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 6939 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6940 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6941 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6942 | return getCouldNotCompute(); |
| 6943 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6944 | // For positive steps (counting up until unsigned overflow): |
| 6945 | // N = -Start/Step (as unsigned) |
| 6946 | // For negative steps (counting down to zero): |
| 6947 | // N = Start/-Step |
| 6948 | // First compute the unsigned distance from zero in the direction of Step. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6949 | bool CountDown = StepC->getAPInt().isNegative(); |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 6950 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6951 | |
| 6952 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 6953 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 6954 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6955 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
| 6956 | ConstantRange CR = getUnsignedRange(Start); |
| 6957 | const SCEV *MaxBECount; |
| 6958 | if (!CountDown && CR.getUnsignedMin().isMinValue()) |
| 6959 | // When counting up, the worst starting value is 1, not 0. |
| 6960 | MaxBECount = CR.getUnsignedMax().isMinValue() |
| 6961 | ? getConstant(APInt::getMinValue(CR.getBitWidth())) |
| 6962 | : getConstant(APInt::getMaxValue(CR.getBitWidth())); |
| 6963 | else |
| 6964 | MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() |
| 6965 | : -CR.getUnsignedMin()); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6966 | return ExitLimit(Distance, MaxBECount); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6967 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 6968 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6969 | // As a special case, handle the instance where Step is a positive power of |
| 6970 | // two. In this case, determining whether Step divides Distance evenly can be |
| 6971 | // done by counting and comparing the number of trailing zeros of Step and |
| 6972 | // Distance. |
| 6973 | if (!CountDown) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6974 | const APInt &StepV = StepC->getAPInt(); |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6975 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 6976 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 6977 | // case is not handled as this code is guarded by !CountDown. |
| 6978 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 6979 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 6980 | // Here we've constrained the equation to be of the form |
| 6981 | // |
| 6982 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 6983 | // |
| 6984 | // where we're operating on a W bit wide integer domain and k is |
| 6985 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 6986 | // |
| 6987 | // (0) is equivalent to: |
| 6988 | // |
| 6989 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 6990 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 6991 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 6992 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 6993 | // |
| 6994 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 6995 | // by 2^(W - N). |
| 6996 | // |
| 6997 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 6998 | // |
| 6999 | // E.g. say we're solving |
| 7000 | // |
| 7001 | // 2 * Val = 2 * X (in i8) ... (3) |
| 7002 | // |
| 7003 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 7004 | // |
| 7005 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 7006 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 7007 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 7008 | // is i8 1, not i8 -127 |
| 7009 | |
| 7010 | const auto *ModuloResult = getUDivExactExpr(Distance, Step); |
| 7011 | |
| 7012 | // Since SCEV does not have a URem node, we construct one using a truncate |
| 7013 | // and a zero extend. |
| 7014 | |
| 7015 | unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); |
| 7016 | auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); |
| 7017 | auto *WideTy = Distance->getType(); |
| 7018 | |
| 7019 | return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); |
| 7020 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7021 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7022 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7023 | // If the condition controls loop exit (the loop exits only if the expression |
| 7024 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 7025 | // compute the backedge count. In this case, the step may not divide the |
| 7026 | // distance, but we don't care because if the condition is "missed" the loop |
| 7027 | // will have undefined behavior due to wrapping. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7028 | if (ControlsExit && AddRec->hasNoSelfWrap()) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7029 | const SCEV *Exact = |
| 7030 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
| 7031 | return ExitLimit(Exact, Exact); |
| 7032 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7033 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7034 | // Then, try to solve the above equation provided that Start is constant. |
| 7035 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7036 | return SolveLinEquationWithOverflow(StepC->getAPInt(), -StartC->getAPInt(), |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7037 | *this); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7038 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7039 | } |
| 7040 | |
| 7041 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 7042 | /// specified value for nonzero will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 7043 | /// CouldNotCompute |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7044 | ScalarEvolution::ExitLimit |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 7045 | ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7046 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 7047 | // handle them yet except for the trivial case. This could be expanded in the |
| 7048 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7049 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7050 | // If the value is a constant, check to see if it is known to be non-zero |
| 7051 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7052 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 7053 | if (!C->getValue()->isNullValue()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 7054 | return getZero(C->getType()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7055 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7056 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7057 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7058 | // We could implement others, but I really doubt anyone writes loops like |
| 7059 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7060 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7061 | } |
| 7062 | |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7063 | /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB |
| 7064 | /// (which may not be an immediate predecessor) which has exactly one |
| 7065 | /// successor from which BB is reachable, or null if no such block is |
| 7066 | /// found. |
| 7067 | /// |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7068 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7069 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 7070 | // If the block has a unique predecessor, then there is no path from the |
| 7071 | // predecessor to the block that does not go through the direct edge |
| 7072 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7073 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7074 | return {Pred, BB}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7075 | |
| 7076 | // 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] | 7077 | // If the header has a unique predecessor outside the loop, it must be |
| 7078 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7079 | if (Loop *L = LI.getLoopFor(BB)) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7080 | return {L->getLoopPredecessor(), L->getHeader()}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7081 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7082 | return {nullptr, nullptr}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7083 | } |
| 7084 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7085 | /// HasSameValue - SCEV structural equivalence is usually sufficient for |
| 7086 | /// testing whether two expressions are equal, however for the purposes of |
| 7087 | /// looking for a condition guarding a loop, it can be useful to be a little |
| 7088 | /// more general, since a front-end may have replicated the controlling |
| 7089 | /// expression. |
| 7090 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7091 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7092 | // Quick check to see if they are the same SCEV. |
| 7093 | if (A == B) return true; |
| 7094 | |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7095 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { |
| 7096 | // Not all instructions that are "identical" compute the same value. For |
| 7097 | // instance, two distinct alloca instructions allocating the same type are |
| 7098 | // identical and do not read memory; but compute distinct values. |
| 7099 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); |
| 7100 | }; |
| 7101 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7102 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 7103 | // two different instructions with the same value. Check for this case. |
| 7104 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 7105 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 7106 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 7107 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7108 | if (ComputesEqualValues(AI, BI)) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7109 | return true; |
| 7110 | |
| 7111 | // Otherwise assume they may have a different value. |
| 7112 | return false; |
| 7113 | } |
| 7114 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7115 | /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 7116 | /// predicate Pred. Return true iff any changes were made. |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7117 | /// |
| 7118 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7119 | const SCEV *&LHS, const SCEV *&RHS, |
| 7120 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7121 | bool Changed = false; |
| 7122 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7123 | // If we hit the max recursion limit bail out. |
| 7124 | if (Depth >= 3) |
| 7125 | return false; |
| 7126 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7127 | // Canonicalize a constant to the right side. |
| 7128 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 7129 | // Check for both operands constant. |
| 7130 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 7131 | if (ConstantExpr::getICmp(Pred, |
| 7132 | LHSC->getValue(), |
| 7133 | RHSC->getValue())->isNullValue()) |
| 7134 | goto trivially_false; |
| 7135 | else |
| 7136 | goto trivially_true; |
| 7137 | } |
| 7138 | // Otherwise swap the operands to put the constant on the right. |
| 7139 | std::swap(LHS, RHS); |
| 7140 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7141 | Changed = true; |
| 7142 | } |
| 7143 | |
| 7144 | // 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] | 7145 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 7146 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 7147 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 7148 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 7149 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7150 | std::swap(LHS, RHS); |
| 7151 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7152 | Changed = true; |
| 7153 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 7154 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7155 | |
| 7156 | // If there's a constant operand, canonicalize comparisons with boundary |
| 7157 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 7158 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7159 | const APInt &RA = RC->getAPInt(); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7160 | switch (Pred) { |
| 7161 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 7162 | case ICmpInst::ICMP_EQ: |
| 7163 | case ICmpInst::ICMP_NE: |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7164 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 7165 | if (!RA) |
| 7166 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 7167 | if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
Benjamin Kramer | 406a2db | 2012-05-30 18:42:43 +0000 | [diff] [blame] | 7168 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 7169 | ME->getOperand(0)->isAllOnesValue()) { |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7170 | RHS = AE->getOperand(1); |
| 7171 | LHS = ME->getOperand(1); |
| 7172 | Changed = true; |
| 7173 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7174 | break; |
| 7175 | case ICmpInst::ICMP_UGE: |
| 7176 | if ((RA - 1).isMinValue()) { |
| 7177 | Pred = ICmpInst::ICMP_NE; |
| 7178 | RHS = getConstant(RA - 1); |
| 7179 | Changed = true; |
| 7180 | break; |
| 7181 | } |
| 7182 | if (RA.isMaxValue()) { |
| 7183 | Pred = ICmpInst::ICMP_EQ; |
| 7184 | Changed = true; |
| 7185 | break; |
| 7186 | } |
| 7187 | if (RA.isMinValue()) goto trivially_true; |
| 7188 | |
| 7189 | Pred = ICmpInst::ICMP_UGT; |
| 7190 | RHS = getConstant(RA - 1); |
| 7191 | Changed = true; |
| 7192 | break; |
| 7193 | case ICmpInst::ICMP_ULE: |
| 7194 | if ((RA + 1).isMaxValue()) { |
| 7195 | Pred = ICmpInst::ICMP_NE; |
| 7196 | RHS = getConstant(RA + 1); |
| 7197 | Changed = true; |
| 7198 | break; |
| 7199 | } |
| 7200 | if (RA.isMinValue()) { |
| 7201 | Pred = ICmpInst::ICMP_EQ; |
| 7202 | Changed = true; |
| 7203 | break; |
| 7204 | } |
| 7205 | if (RA.isMaxValue()) goto trivially_true; |
| 7206 | |
| 7207 | Pred = ICmpInst::ICMP_ULT; |
| 7208 | RHS = getConstant(RA + 1); |
| 7209 | Changed = true; |
| 7210 | break; |
| 7211 | case ICmpInst::ICMP_SGE: |
| 7212 | if ((RA - 1).isMinSignedValue()) { |
| 7213 | Pred = ICmpInst::ICMP_NE; |
| 7214 | RHS = getConstant(RA - 1); |
| 7215 | Changed = true; |
| 7216 | break; |
| 7217 | } |
| 7218 | if (RA.isMaxSignedValue()) { |
| 7219 | Pred = ICmpInst::ICMP_EQ; |
| 7220 | Changed = true; |
| 7221 | break; |
| 7222 | } |
| 7223 | if (RA.isMinSignedValue()) goto trivially_true; |
| 7224 | |
| 7225 | Pred = ICmpInst::ICMP_SGT; |
| 7226 | RHS = getConstant(RA - 1); |
| 7227 | Changed = true; |
| 7228 | break; |
| 7229 | case ICmpInst::ICMP_SLE: |
| 7230 | if ((RA + 1).isMaxSignedValue()) { |
| 7231 | Pred = ICmpInst::ICMP_NE; |
| 7232 | RHS = getConstant(RA + 1); |
| 7233 | Changed = true; |
| 7234 | break; |
| 7235 | } |
| 7236 | if (RA.isMinSignedValue()) { |
| 7237 | Pred = ICmpInst::ICMP_EQ; |
| 7238 | Changed = true; |
| 7239 | break; |
| 7240 | } |
| 7241 | if (RA.isMaxSignedValue()) goto trivially_true; |
| 7242 | |
| 7243 | Pred = ICmpInst::ICMP_SLT; |
| 7244 | RHS = getConstant(RA + 1); |
| 7245 | Changed = true; |
| 7246 | break; |
| 7247 | case ICmpInst::ICMP_UGT: |
| 7248 | if (RA.isMinValue()) { |
| 7249 | Pred = ICmpInst::ICMP_NE; |
| 7250 | Changed = true; |
| 7251 | break; |
| 7252 | } |
| 7253 | if ((RA + 1).isMaxValue()) { |
| 7254 | Pred = ICmpInst::ICMP_EQ; |
| 7255 | RHS = getConstant(RA + 1); |
| 7256 | Changed = true; |
| 7257 | break; |
| 7258 | } |
| 7259 | if (RA.isMaxValue()) goto trivially_false; |
| 7260 | break; |
| 7261 | case ICmpInst::ICMP_ULT: |
| 7262 | if (RA.isMaxValue()) { |
| 7263 | Pred = ICmpInst::ICMP_NE; |
| 7264 | Changed = true; |
| 7265 | break; |
| 7266 | } |
| 7267 | if ((RA - 1).isMinValue()) { |
| 7268 | Pred = ICmpInst::ICMP_EQ; |
| 7269 | RHS = getConstant(RA - 1); |
| 7270 | Changed = true; |
| 7271 | break; |
| 7272 | } |
| 7273 | if (RA.isMinValue()) goto trivially_false; |
| 7274 | break; |
| 7275 | case ICmpInst::ICMP_SGT: |
| 7276 | if (RA.isMinSignedValue()) { |
| 7277 | Pred = ICmpInst::ICMP_NE; |
| 7278 | Changed = true; |
| 7279 | break; |
| 7280 | } |
| 7281 | if ((RA + 1).isMaxSignedValue()) { |
| 7282 | Pred = ICmpInst::ICMP_EQ; |
| 7283 | RHS = getConstant(RA + 1); |
| 7284 | Changed = true; |
| 7285 | break; |
| 7286 | } |
| 7287 | if (RA.isMaxSignedValue()) goto trivially_false; |
| 7288 | break; |
| 7289 | case ICmpInst::ICMP_SLT: |
| 7290 | if (RA.isMaxSignedValue()) { |
| 7291 | Pred = ICmpInst::ICMP_NE; |
| 7292 | Changed = true; |
| 7293 | break; |
| 7294 | } |
| 7295 | if ((RA - 1).isMinSignedValue()) { |
| 7296 | Pred = ICmpInst::ICMP_EQ; |
| 7297 | RHS = getConstant(RA - 1); |
| 7298 | Changed = true; |
| 7299 | break; |
| 7300 | } |
| 7301 | if (RA.isMinSignedValue()) goto trivially_false; |
| 7302 | break; |
| 7303 | } |
| 7304 | } |
| 7305 | |
| 7306 | // Check for obvious equality. |
| 7307 | if (HasSameValue(LHS, RHS)) { |
| 7308 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7309 | goto trivially_true; |
| 7310 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 7311 | goto trivially_false; |
| 7312 | } |
| 7313 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7314 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 7315 | // adding or subtracting 1 from one of the operands. |
| 7316 | switch (Pred) { |
| 7317 | case ICmpInst::ICMP_SLE: |
| 7318 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 7319 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7320 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7321 | Pred = ICmpInst::ICMP_SLT; |
| 7322 | Changed = true; |
| 7323 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7324 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7325 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7326 | Pred = ICmpInst::ICMP_SLT; |
| 7327 | Changed = true; |
| 7328 | } |
| 7329 | break; |
| 7330 | case ICmpInst::ICMP_SGE: |
| 7331 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7332 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7333 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7334 | Pred = ICmpInst::ICMP_SGT; |
| 7335 | Changed = true; |
| 7336 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 7337 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7338 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7339 | Pred = ICmpInst::ICMP_SGT; |
| 7340 | Changed = true; |
| 7341 | } |
| 7342 | break; |
| 7343 | case ICmpInst::ICMP_ULE: |
| 7344 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7345 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7346 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7347 | Pred = ICmpInst::ICMP_ULT; |
| 7348 | Changed = true; |
| 7349 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7350 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7351 | Pred = ICmpInst::ICMP_ULT; |
| 7352 | Changed = true; |
| 7353 | } |
| 7354 | break; |
| 7355 | case ICmpInst::ICMP_UGE: |
| 7356 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7357 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7358 | Pred = ICmpInst::ICMP_UGT; |
| 7359 | Changed = true; |
| 7360 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7361 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7362 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7363 | Pred = ICmpInst::ICMP_UGT; |
| 7364 | Changed = true; |
| 7365 | } |
| 7366 | break; |
| 7367 | default: |
| 7368 | break; |
| 7369 | } |
| 7370 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7371 | // TODO: More simplifications are possible here. |
| 7372 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7373 | // Recursively simplify until we either hit a recursion limit or nothing |
| 7374 | // changes. |
| 7375 | if (Changed) |
| 7376 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 7377 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7378 | return Changed; |
| 7379 | |
| 7380 | trivially_true: |
| 7381 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7382 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7383 | Pred = ICmpInst::ICMP_EQ; |
| 7384 | return true; |
| 7385 | |
| 7386 | trivially_false: |
| 7387 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7388 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7389 | Pred = ICmpInst::ICMP_NE; |
| 7390 | return true; |
| 7391 | } |
| 7392 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7393 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 7394 | return getSignedRange(S).getSignedMax().isNegative(); |
| 7395 | } |
| 7396 | |
| 7397 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 7398 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 7399 | } |
| 7400 | |
| 7401 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 7402 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 7403 | } |
| 7404 | |
| 7405 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 7406 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 7407 | } |
| 7408 | |
| 7409 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 7410 | return isKnownNegative(S) || isKnownPositive(S); |
| 7411 | } |
| 7412 | |
| 7413 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 7414 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 7415 | // Canonicalize the inputs first. |
| 7416 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 7417 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7418 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 7419 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 7420 | // If LHS and RHS are both addrec, both conditions must be true in |
| 7421 | // every iteration of the loop. |
| 7422 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7423 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7424 | bool LeftGuarded = false; |
| 7425 | bool RightGuarded = false; |
| 7426 | if (LAR) { |
| 7427 | const Loop *L = LAR->getLoop(); |
| 7428 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 7429 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 7430 | if (!RAR) return true; |
| 7431 | LeftGuarded = true; |
| 7432 | } |
| 7433 | } |
| 7434 | if (RAR) { |
| 7435 | const Loop *L = RAR->getLoop(); |
| 7436 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 7437 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 7438 | if (!LAR) return true; |
| 7439 | RightGuarded = true; |
| 7440 | } |
| 7441 | } |
| 7442 | if (LeftGuarded && RightGuarded) |
| 7443 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7444 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7445 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) |
| 7446 | return true; |
| 7447 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7448 | // Otherwise see what can be done with known constant ranges. |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7449 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7450 | } |
| 7451 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7452 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 7453 | ICmpInst::Predicate Pred, |
| 7454 | bool &Increasing) { |
| 7455 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 7456 | |
| 7457 | #ifndef NDEBUG |
| 7458 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 7459 | // increasing change to a monotonically decreasing one, and vice versa. |
| 7460 | bool IncreasingSwapped; |
| 7461 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 7462 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 7463 | |
| 7464 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 7465 | if (ResultSwapped) |
| 7466 | assert(Increasing == !IncreasingSwapped && |
| 7467 | "monotonicity should flip as we flip the predicate"); |
| 7468 | #endif |
| 7469 | |
| 7470 | return Result; |
| 7471 | } |
| 7472 | |
| 7473 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 7474 | ICmpInst::Predicate Pred, |
| 7475 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7476 | |
| 7477 | // A zero step value for LHS means the induction variable is essentially a |
| 7478 | // loop invariant value. We don't really depend on the predicate actually |
| 7479 | // flipping from false to true (for increasing predicates, and the other way |
| 7480 | // around for decreasing predicates), all we care about is that *if* the |
| 7481 | // predicate changes then it only changes from false to true. |
| 7482 | // |
| 7483 | // A zero step value in itself is not very useful, but there may be places |
| 7484 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 7485 | // as general as possible. |
| 7486 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7487 | switch (Pred) { |
| 7488 | default: |
| 7489 | return false; // Conservative answer |
| 7490 | |
| 7491 | case ICmpInst::ICMP_UGT: |
| 7492 | case ICmpInst::ICMP_UGE: |
| 7493 | case ICmpInst::ICMP_ULT: |
| 7494 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7495 | if (!LHS->hasNoUnsignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7496 | return false; |
| 7497 | |
| 7498 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7499 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7500 | |
| 7501 | case ICmpInst::ICMP_SGT: |
| 7502 | case ICmpInst::ICMP_SGE: |
| 7503 | case ICmpInst::ICMP_SLT: |
| 7504 | case ICmpInst::ICMP_SLE: { |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7505 | if (!LHS->hasNoSignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7506 | return false; |
| 7507 | |
| 7508 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 7509 | |
| 7510 | if (isKnownNonNegative(Step)) { |
| 7511 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 7512 | return true; |
| 7513 | } |
| 7514 | |
| 7515 | if (isKnownNonPositive(Step)) { |
| 7516 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 7517 | return true; |
| 7518 | } |
| 7519 | |
| 7520 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7521 | } |
| 7522 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7523 | } |
| 7524 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7525 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7526 | } |
| 7527 | |
| 7528 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 7529 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 7530 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 7531 | const SCEV *&InvariantRHS) { |
| 7532 | |
| 7533 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 7534 | if (!isLoopInvariant(RHS, L)) { |
| 7535 | if (!isLoopInvariant(LHS, L)) |
| 7536 | return false; |
| 7537 | |
| 7538 | std::swap(LHS, RHS); |
| 7539 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7540 | } |
| 7541 | |
| 7542 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7543 | if (!ArLHS || ArLHS->getLoop() != L) |
| 7544 | return false; |
| 7545 | |
| 7546 | bool Increasing; |
| 7547 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 7548 | return false; |
| 7549 | |
| 7550 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 7551 | // true as the loop iterates, and the backedge is control dependent on |
| 7552 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 7553 | // |
| 7554 | // * if the predicate was false in the first iteration then the predicate |
| 7555 | // is never evaluated again, since the loop exits without taking the |
| 7556 | // backedge. |
| 7557 | // * if the predicate was true in the first iteration then it will |
| 7558 | // continue to be true for all future iterations since it is |
| 7559 | // monotonically increasing. |
| 7560 | // |
| 7561 | // For both the above possibilities, we can replace the loop varying |
| 7562 | // predicate with its value on the first iteration of the loop (which is |
| 7563 | // loop invariant). |
| 7564 | // |
| 7565 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 7566 | // replacing true with false and false with true in the above two bullets. |
| 7567 | |
| 7568 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 7569 | |
| 7570 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 7571 | return false; |
| 7572 | |
| 7573 | InvariantPred = Pred; |
| 7574 | InvariantLHS = ArLHS->getStart(); |
| 7575 | InvariantRHS = RHS; |
| 7576 | return true; |
| 7577 | } |
| 7578 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7579 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( |
| 7580 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7581 | if (HasSameValue(LHS, RHS)) |
| 7582 | return ICmpInst::isTrueWhenEqual(Pred); |
| 7583 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7584 | // This code is split out from isKnownPredicate because it is called from |
| 7585 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7586 | |
Sanjoy Das | 4c7b6d7 | 2016-02-01 20:48:14 +0000 | [diff] [blame] | 7587 | auto CheckRanges = |
| 7588 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { |
| 7589 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) |
| 7590 | .contains(RangeLHS); |
| 7591 | }; |
| 7592 | |
| 7593 | // The check at the top of the function catches the case where the values are |
| 7594 | // known to be equal. |
| 7595 | if (Pred == CmpInst::ICMP_EQ) |
| 7596 | return false; |
| 7597 | |
| 7598 | if (Pred == CmpInst::ICMP_NE) |
| 7599 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || |
| 7600 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || |
| 7601 | isKnownNonZero(getMinusSCEV(LHS, RHS)); |
| 7602 | |
| 7603 | if (CmpInst::isSigned(Pred)) |
| 7604 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); |
| 7605 | |
| 7606 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7607 | } |
| 7608 | |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7609 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, |
| 7610 | const SCEV *LHS, |
| 7611 | const SCEV *RHS) { |
| 7612 | |
| 7613 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. |
| 7614 | // Return Y via OutY. |
| 7615 | auto MatchBinaryAddToConst = |
| 7616 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, |
| 7617 | SCEV::NoWrapFlags ExpectedFlags) { |
| 7618 | const SCEV *NonConstOp, *ConstOp; |
| 7619 | SCEV::NoWrapFlags FlagsPresent; |
| 7620 | |
| 7621 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || |
| 7622 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) |
| 7623 | return false; |
| 7624 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7625 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7626 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; |
| 7627 | }; |
| 7628 | |
| 7629 | APInt C; |
| 7630 | |
| 7631 | switch (Pred) { |
| 7632 | default: |
| 7633 | break; |
| 7634 | |
| 7635 | case ICmpInst::ICMP_SGE: |
| 7636 | std::swap(LHS, RHS); |
| 7637 | case ICmpInst::ICMP_SLE: |
| 7638 | // X s<= (X + C)<nsw> if C >= 0 |
| 7639 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) |
| 7640 | return true; |
| 7641 | |
| 7642 | // (X + C)<nsw> s<= X if C <= 0 |
| 7643 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && |
| 7644 | !C.isStrictlyPositive()) |
| 7645 | return true; |
| 7646 | break; |
| 7647 | |
| 7648 | case ICmpInst::ICMP_SGT: |
| 7649 | std::swap(LHS, RHS); |
| 7650 | case ICmpInst::ICMP_SLT: |
| 7651 | // X s< (X + C)<nsw> if C > 0 |
| 7652 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && |
| 7653 | C.isStrictlyPositive()) |
| 7654 | return true; |
| 7655 | |
| 7656 | // (X + C)<nsw> s< X if C < 0 |
| 7657 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) |
| 7658 | return true; |
| 7659 | break; |
| 7660 | } |
| 7661 | |
| 7662 | return false; |
| 7663 | } |
| 7664 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7665 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, |
| 7666 | const SCEV *LHS, |
| 7667 | const SCEV *RHS) { |
Sanjoy Das | 10dffcb | 2015-10-08 03:46:00 +0000 | [diff] [blame] | 7668 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7669 | return false; |
| 7670 | |
| 7671 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on |
| 7672 | // the stack can result in exponential time complexity. |
| 7673 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); |
| 7674 | |
| 7675 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L |
| 7676 | // |
| 7677 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use |
| 7678 | // isKnownPredicate. isKnownPredicate is more powerful, but also more |
| 7679 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the |
| 7680 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to |
| 7681 | // use isKnownPredicate later if needed. |
Alexander Kornienko | 484e48e3 | 2015-11-05 21:07:12 +0000 | [diff] [blame] | 7682 | return isKnownNonNegative(RHS) && |
| 7683 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && |
| 7684 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7685 | } |
| 7686 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7687 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 7688 | /// protected by a conditional between LHS and RHS. This is used to |
| 7689 | /// to eliminate casts. |
| 7690 | bool |
| 7691 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 7692 | ICmpInst::Predicate Pred, |
| 7693 | const SCEV *LHS, const SCEV *RHS) { |
| 7694 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7695 | // (interprocedural conditions notwithstanding). |
| 7696 | if (!L) return true; |
| 7697 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7698 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7699 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7700 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7701 | BasicBlock *Latch = L->getLoopLatch(); |
| 7702 | if (!Latch) |
| 7703 | return false; |
| 7704 | |
| 7705 | BranchInst *LoopContinuePredicate = |
| 7706 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7707 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 7708 | isImpliedCond(Pred, LHS, RHS, |
| 7709 | LoopContinuePredicate->getCondition(), |
| 7710 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 7711 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7712 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7713 | // 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] | 7714 | // -- that can lead to O(n!) time complexity. |
| 7715 | if (WalkingBEDominatingConds) |
| 7716 | return false; |
| 7717 | |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 7718 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7719 | |
Sanjoy Das | b174f9a | 2015-09-25 23:53:50 +0000 | [diff] [blame] | 7720 | // See if we can exploit a trip count to prove the predicate. |
| 7721 | const auto &BETakenInfo = getBackedgeTakenInfo(L); |
| 7722 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); |
| 7723 | if (LatchBECount != getCouldNotCompute()) { |
| 7724 | // We know that Latch branches back to the loop header exactly |
| 7725 | // LatchBECount times. This means the backdege condition at Latch is |
| 7726 | // equivalent to "{0,+,1} u< LatchBECount". |
| 7727 | Type *Ty = LatchBECount->getType(); |
| 7728 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); |
| 7729 | const SCEV *LoopCounter = |
| 7730 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); |
| 7731 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, |
| 7732 | LatchBECount)) |
| 7733 | return true; |
| 7734 | } |
| 7735 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7736 | // Check conditions due to any @llvm.assume intrinsics. |
| 7737 | for (auto &AssumeVH : AC.assumptions()) { |
| 7738 | if (!AssumeVH) |
| 7739 | continue; |
| 7740 | auto *CI = cast<CallInst>(AssumeVH); |
| 7741 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7742 | continue; |
| 7743 | |
| 7744 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7745 | return true; |
| 7746 | } |
| 7747 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7748 | // If the loop is not reachable from the entry block, we risk running into an |
| 7749 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7750 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7751 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7752 | return false; |
| 7753 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7754 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7755 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7756 | |
| 7757 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7758 | |
| 7759 | BasicBlock *BB = DTN->getBlock(); |
| 7760 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7761 | if (!PBB) |
| 7762 | continue; |
| 7763 | |
| 7764 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7765 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7766 | continue; |
| 7767 | |
| 7768 | Value *Condition = ContinuePredicate->getCondition(); |
| 7769 | |
| 7770 | // If we have an edge `E` within the loop body that dominates the only |
| 7771 | // latch, the condition guarding `E` also guards the backedge. This |
| 7772 | // reasoning works only for loops with a single latch. |
| 7773 | |
| 7774 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 7775 | if (DominatingEdge.isSingleEdge()) { |
| 7776 | // We're constructively (and conservatively) enumerating edges within the |
| 7777 | // loop body that dominate the latch. The dominator tree better agree |
| 7778 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7779 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7780 | |
| 7781 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 7782 | BB != ContinuePredicate->getSuccessor(0))) |
| 7783 | return true; |
| 7784 | } |
| 7785 | } |
| 7786 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7787 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7788 | } |
| 7789 | |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7790 | /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7791 | /// by a conditional between LHS and RHS. This is used to help avoid max |
| 7792 | /// expressions in loop trip counts, and to eliminate casts. |
| 7793 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7794 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 7795 | ICmpInst::Predicate Pred, |
| 7796 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 7797 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7798 | // (interprocedural conditions notwithstanding). |
| 7799 | if (!L) return false; |
| 7800 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7801 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7802 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7803 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 7804 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 7805 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7806 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7807 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 7808 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7809 | Pair.first; |
| 7810 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7811 | |
| 7812 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7813 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7814 | if (!LoopEntryPredicate || |
| 7815 | LoopEntryPredicate->isUnconditional()) |
| 7816 | continue; |
| 7817 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7818 | if (isImpliedCond(Pred, LHS, RHS, |
| 7819 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7820 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7821 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7822 | } |
| 7823 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7824 | // Check conditions due to any @llvm.assume intrinsics. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7825 | for (auto &AssumeVH : AC.assumptions()) { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 7826 | if (!AssumeVH) |
| 7827 | continue; |
| 7828 | auto *CI = cast<CallInst>(AssumeVH); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7829 | if (!DT.dominates(CI, L->getHeader())) |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7830 | continue; |
| 7831 | |
| 7832 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7833 | return true; |
| 7834 | } |
| 7835 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7836 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7837 | } |
| 7838 | |
Benjamin Kramer | 039b104 | 2015-10-28 13:54:36 +0000 | [diff] [blame] | 7839 | namespace { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7840 | /// RAII wrapper to prevent recursive application of isImpliedCond. |
| 7841 | /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are |
| 7842 | /// currently evaluating isImpliedCond. |
| 7843 | struct MarkPendingLoopPredicate { |
| 7844 | Value *Cond; |
| 7845 | DenseSet<Value*> &LoopPreds; |
| 7846 | bool Pending; |
| 7847 | |
| 7848 | MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) |
| 7849 | : Cond(C), LoopPreds(LP) { |
| 7850 | Pending = !LoopPreds.insert(Cond).second; |
| 7851 | } |
| 7852 | ~MarkPendingLoopPredicate() { |
| 7853 | if (!Pending) |
| 7854 | LoopPreds.erase(Cond); |
| 7855 | } |
| 7856 | }; |
Benjamin Kramer | 039b104 | 2015-10-28 13:54:36 +0000 | [diff] [blame] | 7857 | } // end anonymous namespace |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7858 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7859 | /// isImpliedCond - Test whether the condition described by Pred, LHS, |
| 7860 | /// and RHS is true whenever the given Cond value evaluates to true. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7861 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7862 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7863 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7864 | bool Inverse) { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7865 | MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); |
| 7866 | if (Mark.Pending) |
| 7867 | return false; |
| 7868 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 7869 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7870 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7871 | if (BO->getOpcode() == Instruction::And) { |
| 7872 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7873 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 7874 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7875 | } else if (BO->getOpcode() == Instruction::Or) { |
| 7876 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7877 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 7878 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7879 | } |
| 7880 | } |
| 7881 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7882 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7883 | if (!ICI) return false; |
| 7884 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 7885 | // Now that we found a conditional branch that dominates the loop or controls |
| 7886 | // 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] | 7887 | ICmpInst::Predicate FoundPred; |
| 7888 | if (Inverse) |
| 7889 | FoundPred = ICI->getInversePredicate(); |
| 7890 | else |
| 7891 | FoundPred = ICI->getPredicate(); |
| 7892 | |
| 7893 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 7894 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7895 | |
Sanjoy Das | df1635d | 2015-09-25 19:59:52 +0000 | [diff] [blame] | 7896 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); |
| 7897 | } |
| 7898 | |
| 7899 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, |
| 7900 | const SCEV *RHS, |
| 7901 | ICmpInst::Predicate FoundPred, |
| 7902 | const SCEV *FoundLHS, |
| 7903 | const SCEV *FoundRHS) { |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 7904 | // Balance the types. |
| 7905 | if (getTypeSizeInBits(LHS->getType()) < |
| 7906 | getTypeSizeInBits(FoundLHS->getType())) { |
| 7907 | if (CmpInst::isSigned(Pred)) { |
| 7908 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 7909 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 7910 | } else { |
| 7911 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 7912 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 7913 | } |
| 7914 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7915 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 7916 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7917 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 7918 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 7919 | } else { |
| 7920 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 7921 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 7922 | } |
| 7923 | } |
| 7924 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7925 | // Canonicalize the query to match the way instcombine will have |
| 7926 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 7927 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 7928 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 7929 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 7930 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 7931 | if (FoundLHS == FoundRHS) |
| 7932 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7933 | |
| 7934 | // Check to see if we can make the LHS or RHS match. |
| 7935 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 7936 | if (isa<SCEVConstant>(RHS)) { |
| 7937 | std::swap(FoundLHS, FoundRHS); |
| 7938 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 7939 | } else { |
| 7940 | std::swap(LHS, RHS); |
| 7941 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7942 | } |
| 7943 | } |
| 7944 | |
| 7945 | // Check whether the found predicate is the same as the desired predicate. |
| 7946 | if (FoundPred == Pred) |
| 7947 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 7948 | |
| 7949 | // Check whether swapping the found predicate makes it the same as the |
| 7950 | // desired predicate. |
| 7951 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 7952 | if (isa<SCEVConstant>(RHS)) |
| 7953 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 7954 | else |
| 7955 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 7956 | RHS, LHS, FoundLHS, FoundRHS); |
| 7957 | } |
| 7958 | |
Sanjoy Das | 6e78b17 | 2015-10-22 19:57:34 +0000 | [diff] [blame] | 7959 | // Unsigned comparison is the same as signed comparison when both the operands |
| 7960 | // are non-negative. |
| 7961 | if (CmpInst::isUnsigned(FoundPred) && |
| 7962 | CmpInst::getSignedPredicate(FoundPred) == Pred && |
| 7963 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) |
| 7964 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 7965 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 7966 | // Check if we can make progress by sharpening ranges. |
| 7967 | if (FoundPred == ICmpInst::ICMP_NE && |
| 7968 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 7969 | |
| 7970 | const SCEVConstant *C = nullptr; |
| 7971 | const SCEV *V = nullptr; |
| 7972 | |
| 7973 | if (isa<SCEVConstant>(FoundLHS)) { |
| 7974 | C = cast<SCEVConstant>(FoundLHS); |
| 7975 | V = FoundRHS; |
| 7976 | } else { |
| 7977 | C = cast<SCEVConstant>(FoundRHS); |
| 7978 | V = FoundLHS; |
| 7979 | } |
| 7980 | |
| 7981 | // The guarding predicate tells us that C != V. If the known range |
| 7982 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 7983 | // range we consider has to correspond to same signedness as the |
| 7984 | // predicate we're interested in folding. |
| 7985 | |
| 7986 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 7987 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 7988 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7989 | if (Min == C->getAPInt()) { |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 7990 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 7991 | // This is true even if (Min + 1) wraps around -- in case of |
| 7992 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 7993 | |
| 7994 | APInt SharperMin = Min + 1; |
| 7995 | |
| 7996 | switch (Pred) { |
| 7997 | case ICmpInst::ICMP_SGE: |
| 7998 | case ICmpInst::ICMP_UGE: |
| 7999 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 8000 | // RHS, we're done. |
| 8001 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 8002 | getConstant(SharperMin))) |
| 8003 | return true; |
| 8004 | |
| 8005 | case ICmpInst::ICMP_SGT: |
| 8006 | case ICmpInst::ICMP_UGT: |
| 8007 | // We know from the range information that (V `Pred` Min || |
| 8008 | // V == Min). We know from the guarding condition that !(V |
| 8009 | // == Min). This gives us |
| 8010 | // |
| 8011 | // V `Pred` Min || V == Min && !(V == Min) |
| 8012 | // => V `Pred` Min |
| 8013 | // |
| 8014 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 8015 | |
| 8016 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 8017 | return true; |
| 8018 | |
| 8019 | default: |
| 8020 | // No change |
| 8021 | break; |
| 8022 | } |
| 8023 | } |
| 8024 | } |
| 8025 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8026 | // Check whether the actual condition is beyond sufficient. |
| 8027 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 8028 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 8029 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8030 | return true; |
| 8031 | if (Pred == ICmpInst::ICMP_NE) |
| 8032 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 8033 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8034 | return true; |
| 8035 | |
| 8036 | // Otherwise assume the worst. |
| 8037 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8038 | } |
| 8039 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8040 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, |
| 8041 | const SCEV *&L, const SCEV *&R, |
| 8042 | SCEV::NoWrapFlags &Flags) { |
| 8043 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); |
| 8044 | if (!AE || AE->getNumOperands() != 2) |
| 8045 | return false; |
| 8046 | |
| 8047 | L = AE->getOperand(0); |
| 8048 | R = AE->getOperand(1); |
| 8049 | Flags = AE->getNoWrapFlags(); |
| 8050 | return true; |
| 8051 | } |
| 8052 | |
| 8053 | bool ScalarEvolution::computeConstantDifference(const SCEV *Less, |
| 8054 | const SCEV *More, |
| 8055 | APInt &C) { |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8056 | // We avoid subtracting expressions here because this function is usually |
| 8057 | // fairly deep in the call stack (i.e. is called many times). |
| 8058 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8059 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { |
| 8060 | const auto *LAR = cast<SCEVAddRecExpr>(Less); |
| 8061 | const auto *MAR = cast<SCEVAddRecExpr>(More); |
| 8062 | |
| 8063 | if (LAR->getLoop() != MAR->getLoop()) |
| 8064 | return false; |
| 8065 | |
| 8066 | // We look at affine expressions only; not for correctness but to keep |
| 8067 | // getStepRecurrence cheap. |
| 8068 | if (!LAR->isAffine() || !MAR->isAffine()) |
| 8069 | return false; |
| 8070 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8071 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8072 | return false; |
| 8073 | |
| 8074 | Less = LAR->getStart(); |
| 8075 | More = MAR->getStart(); |
| 8076 | |
| 8077 | // fall through |
| 8078 | } |
| 8079 | |
| 8080 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8081 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); |
| 8082 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8083 | C = M - L; |
| 8084 | return true; |
| 8085 | } |
| 8086 | |
| 8087 | const SCEV *L, *R; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8088 | SCEV::NoWrapFlags Flags; |
| 8089 | if (splitBinaryAdd(Less, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8090 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
| 8091 | if (R == More) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8092 | C = -(LC->getAPInt()); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8093 | return true; |
| 8094 | } |
| 8095 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8096 | if (splitBinaryAdd(More, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8097 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
| 8098 | if (R == Less) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8099 | C = LC->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8100 | return true; |
| 8101 | } |
| 8102 | |
| 8103 | return false; |
| 8104 | } |
| 8105 | |
| 8106 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( |
| 8107 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 8108 | const SCEV *FoundLHS, const SCEV *FoundRHS) { |
| 8109 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) |
| 8110 | return false; |
| 8111 | |
| 8112 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8113 | if (!AddRecLHS) |
| 8114 | return false; |
| 8115 | |
| 8116 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); |
| 8117 | if (!AddRecFoundLHS) |
| 8118 | return false; |
| 8119 | |
| 8120 | // We'd like to let SCEV reason about control dependencies, so we constrain |
| 8121 | // both the inequalities to be about add recurrences on the same loop. This |
| 8122 | // way we can use isLoopEntryGuardedByCond later. |
| 8123 | |
| 8124 | const Loop *L = AddRecFoundLHS->getLoop(); |
| 8125 | if (L != AddRecLHS->getLoop()) |
| 8126 | return false; |
| 8127 | |
| 8128 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) |
| 8129 | // |
| 8130 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) |
| 8131 | // ... (2) |
| 8132 | // |
| 8133 | // Informal proof for (2), assuming (1) [*]: |
| 8134 | // |
| 8135 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] |
| 8136 | // |
| 8137 | // Then |
| 8138 | // |
| 8139 | // FoundLHS s< FoundRHS s< INT_MIN - C |
| 8140 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] |
| 8141 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] |
| 8142 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< |
| 8143 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] |
| 8144 | // <=> FoundLHS + C s< FoundRHS + C |
| 8145 | // |
| 8146 | // [*]: (1) can be proved by ruling out overflow. |
| 8147 | // |
| 8148 | // [**]: This can be proved by analyzing all the four possibilities: |
| 8149 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and |
| 8150 | // (A s>= 0, B s>= 0). |
| 8151 | // |
| 8152 | // Note: |
| 8153 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" |
| 8154 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS |
| 8155 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS |
| 8156 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is |
| 8157 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + |
| 8158 | // C)". |
| 8159 | |
| 8160 | APInt LDiff, RDiff; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8161 | if (!computeConstantDifference(FoundLHS, LHS, LDiff) || |
| 8162 | !computeConstantDifference(FoundRHS, RHS, RDiff) || |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8163 | LDiff != RDiff) |
| 8164 | return false; |
| 8165 | |
| 8166 | if (LDiff == 0) |
| 8167 | return true; |
| 8168 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8169 | APInt FoundRHSLimit; |
| 8170 | |
| 8171 | if (Pred == CmpInst::ICMP_ULT) { |
| 8172 | FoundRHSLimit = -RDiff; |
| 8173 | } else { |
| 8174 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); |
Sanjoy Das | 4f1c459 | 2015-09-28 21:14:32 +0000 | [diff] [blame] | 8175 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8176 | } |
| 8177 | |
| 8178 | // Try to prove (1) or (2), as needed. |
| 8179 | return isLoopEntryGuardedByCond(L, Pred, FoundRHS, |
| 8180 | getConstant(FoundRHSLimit)); |
| 8181 | } |
| 8182 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8183 | /// isImpliedCondOperands - Test whether the condition described by Pred, |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8184 | /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8185 | /// and FoundRHS is true. |
| 8186 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 8187 | const SCEV *LHS, const SCEV *RHS, |
| 8188 | const SCEV *FoundLHS, |
| 8189 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8190 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8191 | return true; |
| 8192 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8193 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8194 | return true; |
| 8195 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8196 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8197 | FoundLHS, FoundRHS) || |
| 8198 | // ~x < ~y --> x > y |
| 8199 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8200 | getNotSCEV(FoundRHS), |
| 8201 | getNotSCEV(FoundLHS)); |
| 8202 | } |
| 8203 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8204 | |
| 8205 | /// If Expr computes ~A, return A else return nullptr |
| 8206 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 8207 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8208 | if (!Add || Add->getNumOperands() != 2 || |
| 8209 | !Add->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8210 | return nullptr; |
| 8211 | |
| 8212 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8213 | if (!AddRHS || AddRHS->getNumOperands() != 2 || |
| 8214 | !AddRHS->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8215 | return nullptr; |
| 8216 | |
| 8217 | return AddRHS->getOperand(1); |
| 8218 | } |
| 8219 | |
| 8220 | |
| 8221 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 8222 | template<typename MaxExprType> |
| 8223 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 8224 | const SCEV *Candidate) { |
| 8225 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 8226 | if (!MaxExpr) return false; |
| 8227 | |
Sanjoy Das | 347d272 | 2015-12-01 07:49:27 +0000 | [diff] [blame] | 8228 | return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8229 | } |
| 8230 | |
| 8231 | |
| 8232 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 8233 | template<typename MaxExprType> |
| 8234 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 8235 | const SCEV *MaybeMinExpr, |
| 8236 | const SCEV *Candidate) { |
| 8237 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 8238 | if (!MaybeMaxExpr) |
| 8239 | return false; |
| 8240 | |
| 8241 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 8242 | } |
| 8243 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8244 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 8245 | ICmpInst::Predicate Pred, |
| 8246 | const SCEV *LHS, const SCEV *RHS) { |
| 8247 | |
| 8248 | // If both sides are affine addrecs for the same loop, with equal |
| 8249 | // steps, and we know the recurrences don't wrap, then we only |
| 8250 | // need to check the predicate on the starting values. |
| 8251 | |
| 8252 | if (!ICmpInst::isRelational(Pred)) |
| 8253 | return false; |
| 8254 | |
| 8255 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8256 | if (!LAR) |
| 8257 | return false; |
| 8258 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 8259 | if (!RAR) |
| 8260 | return false; |
| 8261 | if (LAR->getLoop() != RAR->getLoop()) |
| 8262 | return false; |
| 8263 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 8264 | return false; |
| 8265 | |
| 8266 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 8267 | return false; |
| 8268 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 8269 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 8270 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 8271 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8272 | return false; |
| 8273 | |
| 8274 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 8275 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8276 | |
| 8277 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 8278 | /// expression? |
| 8279 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 8280 | ICmpInst::Predicate Pred, |
| 8281 | const SCEV *LHS, const SCEV *RHS) { |
| 8282 | switch (Pred) { |
| 8283 | default: |
| 8284 | return false; |
| 8285 | |
| 8286 | case ICmpInst::ICMP_SGE: |
| 8287 | std::swap(LHS, RHS); |
| 8288 | // fall through |
| 8289 | case ICmpInst::ICMP_SLE: |
| 8290 | return |
| 8291 | // min(A, ...) <= A |
| 8292 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 8293 | // A <= max(A, ...) |
| 8294 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 8295 | |
| 8296 | case ICmpInst::ICMP_UGE: |
| 8297 | std::swap(LHS, RHS); |
| 8298 | // fall through |
| 8299 | case ICmpInst::ICMP_ULE: |
| 8300 | return |
| 8301 | // min(A, ...) <= A |
| 8302 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 8303 | // A <= max(A, ...) |
| 8304 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 8305 | } |
| 8306 | |
| 8307 | llvm_unreachable("covered switch fell through?!"); |
| 8308 | } |
| 8309 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8310 | /// isImpliedCondOperandsHelper - Test whether the condition described by |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8311 | /// Pred, LHS, and RHS is true whenever the condition described by Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8312 | /// FoundLHS, and FoundRHS is true. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8313 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8314 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 8315 | const SCEV *LHS, const SCEV *RHS, |
| 8316 | const SCEV *FoundLHS, |
| 8317 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8318 | auto IsKnownPredicateFull = |
| 8319 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8320 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || |
Sanjoy Das | 1123148 | 2015-10-22 19:57:29 +0000 | [diff] [blame] | 8321 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 8322 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || |
| 8323 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8324 | }; |
| 8325 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8326 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8327 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 8328 | case ICmpInst::ICMP_EQ: |
| 8329 | case ICmpInst::ICMP_NE: |
| 8330 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 8331 | return true; |
| 8332 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8333 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8334 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8335 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 8336 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8337 | return true; |
| 8338 | break; |
| 8339 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8340 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8341 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 8342 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8343 | return true; |
| 8344 | break; |
| 8345 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8346 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8347 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 8348 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8349 | return true; |
| 8350 | break; |
| 8351 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8352 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8353 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 8354 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8355 | return true; |
| 8356 | break; |
| 8357 | } |
| 8358 | |
| 8359 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8360 | } |
| 8361 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8362 | /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands. |
| 8363 | /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1". |
| 8364 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 8365 | const SCEV *LHS, |
| 8366 | const SCEV *RHS, |
| 8367 | const SCEV *FoundLHS, |
| 8368 | const SCEV *FoundRHS) { |
| 8369 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 8370 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 8371 | // reduce the compile time impact of this optimization. |
| 8372 | return false; |
| 8373 | |
| 8374 | const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS); |
| 8375 | if (!AddLHS || AddLHS->getOperand(1) != FoundLHS || |
| 8376 | !isa<SCEVConstant>(AddLHS->getOperand(0))) |
| 8377 | return false; |
| 8378 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8379 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8380 | |
| 8381 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 8382 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 8383 | ConstantRange FoundLHSRange = |
| 8384 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 8385 | |
| 8386 | // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range |
| 8387 | // for `LHS`: |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8388 | APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8389 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend)); |
| 8390 | |
| 8391 | // We can also compute the range of values for `LHS` that satisfy the |
| 8392 | // consequent, "`LHS` `Pred` `RHS`": |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8393 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8394 | ConstantRange SatisfyingLHSRange = |
| 8395 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 8396 | |
| 8397 | // The antecedent implies the consequent if every value of `LHS` that |
| 8398 | // satisfies the antecedent also satisfies the consequent. |
| 8399 | return SatisfyingLHSRange.contains(LHSRange); |
| 8400 | } |
| 8401 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8402 | // Verify if an linear IV with positive stride can overflow when in a |
| 8403 | // less-than comparison, knowing the invariant term of the comparison, the |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8404 | // stride and the knowledge of NSW/NUW flags on the recurrence. |
| 8405 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 8406 | bool IsSigned, bool NoWrap) { |
| 8407 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8408 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8409 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8410 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8411 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8412 | if (IsSigned) { |
| 8413 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 8414 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 8415 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8416 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8417 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8418 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 8419 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 8420 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8421 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8422 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 8423 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 8424 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8425 | .getUnsignedMax(); |
| 8426 | |
| 8427 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 8428 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 8429 | } |
| 8430 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8431 | // 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] | 8432 | // greater-than comparison, knowing the invariant term of the comparison, |
| 8433 | // the stride and the knowledge of NSW/NUW flags on the recurrence. |
| 8434 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 8435 | bool IsSigned, bool NoWrap) { |
| 8436 | if (NoWrap) return false; |
| 8437 | |
| 8438 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8439 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8440 | |
| 8441 | if (IsSigned) { |
| 8442 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 8443 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 8444 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8445 | .getSignedMax(); |
| 8446 | |
| 8447 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 8448 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 8449 | } |
| 8450 | |
| 8451 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 8452 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 8453 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8454 | .getUnsignedMax(); |
| 8455 | |
| 8456 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 8457 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 8458 | } |
| 8459 | |
| 8460 | // Compute the backedge taken count knowing the interval difference, the |
| 8461 | // stride and presence of the equality in the comparison. |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8462 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8463 | bool Equality) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8464 | const SCEV *One = getOne(Step->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8465 | Delta = Equality ? getAddExpr(Delta, Step) |
| 8466 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 8467 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8468 | } |
| 8469 | |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8470 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 8471 | /// specified less-than comparison will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 8472 | /// CouldNotCompute. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 8473 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8474 | /// @param ControlsExit is true when the LHS < RHS condition directly controls |
| 8475 | /// the branch (loops exits only if condition is true). In this case, we can use |
| 8476 | /// NoWrapFlags to skip overflow checks. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8477 | ScalarEvolution::ExitLimit |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8478 | ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8479 | const Loop *L, bool IsSigned, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8480 | bool ControlsExit) { |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8481 | // We handle only IV < Invariant |
| 8482 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 8483 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8484 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8485 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8486 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8487 | // Avoid weird loops |
| 8488 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8489 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8490 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8491 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8492 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8493 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8494 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8495 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8496 | // Avoid negative or zero stride values |
| 8497 | if (!isKnownPositive(Stride)) |
| 8498 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8499 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8500 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8501 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8502 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8503 | // behaviors like the case of C language. |
| 8504 | if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 8505 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8506 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8507 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 8508 | : ICmpInst::ICMP_ULT; |
| 8509 | const SCEV *Start = IV->getStart(); |
| 8510 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8511 | if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) { |
| 8512 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 8513 | // If we have NoWrap set, then we can assume that the increment won't |
| 8514 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 8515 | // do a max operation since we can just figure it out statically |
| 8516 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8517 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8518 | if (D.isNegative()) |
| 8519 | End = Start; |
| 8520 | } else |
| 8521 | End = IsSigned ? getSMaxExpr(RHS, Start) |
| 8522 | : getUMaxExpr(RHS, Start); |
| 8523 | } |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8524 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8525 | const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8526 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8527 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 8528 | : getUnsignedRange(Start).getUnsignedMin(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8529 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8530 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8531 | : getUnsignedRange(Stride).getUnsignedMin(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8532 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8533 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8534 | APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1) |
| 8535 | : APInt::getMaxValue(BitWidth) - (MinStride - 1); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8536 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8537 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 8538 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 8539 | // is zero, leading to a zero maximum backedge taken count. |
| 8540 | APInt MaxEnd = |
| 8541 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 8542 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 8543 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 8544 | const SCEV *MaxBECount; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8545 | if (isa<SCEVConstant>(BECount)) |
| 8546 | MaxBECount = BECount; |
| 8547 | else |
| 8548 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
| 8549 | getConstant(MinStride), false); |
| 8550 | |
| 8551 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8552 | MaxBECount = BECount; |
| 8553 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8554 | return ExitLimit(BECount, MaxBECount); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8555 | } |
| 8556 | |
| 8557 | ScalarEvolution::ExitLimit |
| 8558 | ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
| 8559 | const Loop *L, bool IsSigned, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8560 | bool ControlsExit) { |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8561 | // We handle only IV > Invariant |
| 8562 | if (!isLoopInvariant(RHS, L)) |
| 8563 | return getCouldNotCompute(); |
| 8564 | |
| 8565 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8566 | |
| 8567 | // Avoid weird loops |
| 8568 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8569 | return getCouldNotCompute(); |
| 8570 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8571 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8572 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 8573 | |
| 8574 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 8575 | |
| 8576 | // Avoid negative or zero stride values |
| 8577 | if (!isKnownPositive(Stride)) |
| 8578 | return getCouldNotCompute(); |
| 8579 | |
| 8580 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8581 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8582 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8583 | // behaviors like the case of C language. |
| 8584 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 8585 | return getCouldNotCompute(); |
| 8586 | |
| 8587 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 8588 | : ICmpInst::ICMP_UGT; |
| 8589 | |
| 8590 | const SCEV *Start = IV->getStart(); |
| 8591 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8592 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { |
| 8593 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 8594 | // If we have NoWrap set, then we can assume that the increment won't |
| 8595 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 8596 | // do a max operation since we can just figure it out statically |
| 8597 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8598 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8599 | if (!D.isNegative()) |
| 8600 | End = Start; |
| 8601 | } else |
| 8602 | End = IsSigned ? getSMinExpr(RHS, Start) |
| 8603 | : getUMinExpr(RHS, Start); |
| 8604 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8605 | |
| 8606 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 8607 | |
| 8608 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 8609 | : getUnsignedRange(Start).getUnsignedMax(); |
| 8610 | |
| 8611 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8612 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8613 | |
| 8614 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8615 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 8616 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 8617 | |
| 8618 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 8619 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 8620 | // is zero, leading to a zero maximum backedge taken count. |
| 8621 | APInt MinEnd = |
| 8622 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 8623 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 8624 | |
| 8625 | |
| 8626 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 8627 | if (isa<SCEVConstant>(BECount)) |
| 8628 | MaxBECount = BECount; |
| 8629 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8630 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8631 | getConstant(MinStride), false); |
| 8632 | |
| 8633 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8634 | MaxBECount = BECount; |
| 8635 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8636 | return ExitLimit(BECount, MaxBECount); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8637 | } |
| 8638 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8639 | /// getNumIterationsInRange - Return the number of iterations of this loop that |
| 8640 | /// produce values in the specified constant range. Another way of looking at |
| 8641 | /// this is that it returns the first iteration number where the value is not in |
| 8642 | /// the condition, thus computing the exit count. If the iteration count can't |
| 8643 | /// be computed, an instance of SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8644 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8645 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8646 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8647 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8648 | |
| 8649 | // 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] | 8650 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 8651 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8652 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8653 | Operands[0] = SE.getZero(SC->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8654 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 8655 | getNoWrapFlags(FlagNW)); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 8656 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8657 | return ShiftedAddRec->getNumIterationsInRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8658 | Range.subtract(SC->getAPInt()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8659 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8660 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8661 | } |
| 8662 | |
| 8663 | // The only time we can solve this is when we have all constant indices. |
| 8664 | // Otherwise, we cannot determine the overflow conditions. |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 8665 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 8666 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8667 | |
| 8668 | // Okay at this point we know that all elements of the chrec are constants and |
| 8669 | // that the start element is zero. |
| 8670 | |
| 8671 | // First check to see if the range contains zero. If not, the first |
| 8672 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 8673 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8674 | if (!Range.contains(APInt(BitWidth, 0))) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8675 | return SE.getZero(getType()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8676 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8677 | if (isAffine()) { |
| 8678 | // If this is an affine expression then we have this situation: |
| 8679 | // Solve {0,+,A} in Range === Ax in Range |
| 8680 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8681 | // We know that zero is in the range. If A is positive then we know that |
| 8682 | // the upper value of the range must be the first possible exit value. |
| 8683 | // If A is negative then the lower of the range is the last possible loop |
| 8684 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8685 | APInt One(BitWidth,1); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8686 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8687 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8688 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8689 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 8690 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8691 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8692 | |
| 8693 | // Evaluate at the exit value. If we really did fall out of the valid |
| 8694 | // range, then we computed our trip count, otherwise wrap around or other |
| 8695 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8696 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8697 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8698 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8699 | |
| 8700 | // 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] | 8701 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8702 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8703 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8704 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8705 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8706 | } else if (isQuadratic()) { |
| 8707 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 8708 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 8709 | // terms of figuring out when zero is crossed, instead of when |
| 8710 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8711 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8712 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8713 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), |
| 8714 | // getNoWrapFlags(FlagNW) |
| 8715 | FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8716 | |
| 8717 | // Next, solve the constructed addrec |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8718 | auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8719 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 8720 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8721 | if (R1) { |
| 8722 | // Pick the smallest positive root value. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8723 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 8724 | ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 8725 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8726 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8727 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8728 | // Make sure the root is not off by one. The returned iteration should |
| 8729 | // not be in the range, but the previous one should be. When solving |
| 8730 | // for "X*X < 5", for example, we should not return a root of 2. |
| 8731 | ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8732 | R1->getValue(), |
| 8733 | SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8734 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8735 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8736 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8737 | ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8738 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8739 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8740 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8741 | return SE.getConstant(NextVal); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8742 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8743 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8744 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8745 | // If R1 was not in the range, then it is a good return value. Make |
| 8746 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8747 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8748 | ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8749 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8750 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8751 | return R1; |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8752 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8753 | } |
| 8754 | } |
| 8755 | } |
| 8756 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8757 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8758 | } |
| 8759 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8760 | namespace { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8761 | struct FindUndefs { |
| 8762 | bool Found; |
| 8763 | FindUndefs() : Found(false) {} |
| 8764 | |
| 8765 | bool follow(const SCEV *S) { |
| 8766 | if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { |
| 8767 | if (isa<UndefValue>(C->getValue())) |
| 8768 | Found = true; |
| 8769 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
| 8770 | if (isa<UndefValue>(C->getValue())) |
| 8771 | Found = true; |
| 8772 | } |
| 8773 | |
| 8774 | // Keep looking if we haven't found it yet. |
| 8775 | return !Found; |
| 8776 | } |
| 8777 | bool isDone() const { |
| 8778 | // Stop recursion if we have found an undef. |
| 8779 | return Found; |
| 8780 | } |
| 8781 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8782 | } |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8783 | |
| 8784 | // Return true when S contains at least an undef value. |
| 8785 | static inline bool |
| 8786 | containsUndefs(const SCEV *S) { |
| 8787 | FindUndefs F; |
| 8788 | SCEVTraversal<FindUndefs> ST(F); |
| 8789 | ST.visitAll(S); |
| 8790 | |
| 8791 | return F.Found; |
| 8792 | } |
| 8793 | |
| 8794 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8795 | // Collect all steps of SCEV expressions. |
| 8796 | struct SCEVCollectStrides { |
| 8797 | ScalarEvolution &SE; |
| 8798 | SmallVectorImpl<const SCEV *> &Strides; |
| 8799 | |
| 8800 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 8801 | : SE(SE), Strides(S) {} |
| 8802 | |
| 8803 | bool follow(const SCEV *S) { |
| 8804 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 8805 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 8806 | return true; |
| 8807 | } |
| 8808 | bool isDone() const { return false; } |
| 8809 | }; |
| 8810 | |
| 8811 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 8812 | struct SCEVCollectTerms { |
| 8813 | SmallVectorImpl<const SCEV *> &Terms; |
| 8814 | |
| 8815 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 8816 | : Terms(T) {} |
| 8817 | |
| 8818 | bool follow(const SCEV *S) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8819 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8820 | if (!containsUndefs(S)) |
| 8821 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8822 | |
| 8823 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8824 | return false; |
| 8825 | } |
| 8826 | |
| 8827 | // Keep looking. |
| 8828 | return true; |
| 8829 | } |
| 8830 | bool isDone() const { return false; } |
| 8831 | }; |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8832 | |
| 8833 | // Check if a SCEV contains an AddRecExpr. |
| 8834 | struct SCEVHasAddRec { |
| 8835 | bool &ContainsAddRec; |
| 8836 | |
| 8837 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { |
| 8838 | ContainsAddRec = false; |
| 8839 | } |
| 8840 | |
| 8841 | bool follow(const SCEV *S) { |
| 8842 | if (isa<SCEVAddRecExpr>(S)) { |
| 8843 | ContainsAddRec = true; |
| 8844 | |
| 8845 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8846 | return false; |
| 8847 | } |
| 8848 | |
| 8849 | // Keep looking. |
| 8850 | return true; |
| 8851 | } |
| 8852 | bool isDone() const { return false; } |
| 8853 | }; |
| 8854 | |
| 8855 | // Find factors that are multiplied with an expression that (possibly as a |
| 8856 | // subexpression) contains an AddRecExpr. In the expression: |
| 8857 | // |
| 8858 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) |
| 8859 | // |
| 8860 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" |
| 8861 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size |
| 8862 | // parameters as they form a product with an induction variable. |
| 8863 | // |
| 8864 | // This collector expects all array size parameters to be in the same MulExpr. |
| 8865 | // It might be necessary to later add support for collecting parameters that are |
| 8866 | // spread over different nested MulExpr. |
| 8867 | struct SCEVCollectAddRecMultiplies { |
| 8868 | SmallVectorImpl<const SCEV *> &Terms; |
| 8869 | ScalarEvolution &SE; |
| 8870 | |
| 8871 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) |
| 8872 | : Terms(T), SE(SE) {} |
| 8873 | |
| 8874 | bool follow(const SCEV *S) { |
| 8875 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { |
| 8876 | bool HasAddRec = false; |
| 8877 | SmallVector<const SCEV *, 0> Operands; |
| 8878 | for (auto Op : Mul->operands()) { |
| 8879 | if (isa<SCEVUnknown>(Op)) { |
| 8880 | Operands.push_back(Op); |
| 8881 | } else { |
| 8882 | bool ContainsAddRec; |
| 8883 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); |
| 8884 | visitAll(Op, ContiansAddRec); |
| 8885 | HasAddRec |= ContainsAddRec; |
| 8886 | } |
| 8887 | } |
| 8888 | if (Operands.size() == 0) |
| 8889 | return true; |
| 8890 | |
| 8891 | if (!HasAddRec) |
| 8892 | return false; |
| 8893 | |
| 8894 | Terms.push_back(SE.getMulExpr(Operands)); |
| 8895 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8896 | return false; |
| 8897 | } |
| 8898 | |
| 8899 | // Keep looking. |
| 8900 | return true; |
| 8901 | } |
| 8902 | bool isDone() const { return false; } |
| 8903 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8904 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8905 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8906 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in |
| 8907 | /// two places: |
| 8908 | /// 1) The strides of AddRec expressions. |
| 8909 | /// 2) Unknowns that are multiplied with AddRec expressions. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8910 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 8911 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8912 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8913 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 8914 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8915 | |
| 8916 | DEBUG({ |
| 8917 | dbgs() << "Strides:\n"; |
| 8918 | for (const SCEV *S : Strides) |
| 8919 | dbgs() << *S << "\n"; |
| 8920 | }); |
| 8921 | |
| 8922 | for (const SCEV *S : Strides) { |
| 8923 | SCEVCollectTerms TermCollector(Terms); |
| 8924 | visitAll(S, TermCollector); |
| 8925 | } |
| 8926 | |
| 8927 | DEBUG({ |
| 8928 | dbgs() << "Terms:\n"; |
| 8929 | for (const SCEV *T : Terms) |
| 8930 | dbgs() << *T << "\n"; |
| 8931 | }); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8932 | |
| 8933 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); |
| 8934 | visitAll(Expr, MulCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8935 | } |
| 8936 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8937 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8938 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 8939 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8940 | int Last = Terms.size() - 1; |
| 8941 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8942 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8943 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8944 | if (Last == 0) { |
| 8945 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8946 | SmallVector<const SCEV *, 2> Qs; |
| 8947 | for (const SCEV *Op : M->operands()) |
| 8948 | if (!isa<SCEVConstant>(Op)) |
| 8949 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8950 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8951 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8952 | } |
| 8953 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8954 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8955 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8956 | } |
| 8957 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 8958 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8959 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 8960 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 8961 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8962 | |
| 8963 | // Bail out when GCD does not evenly divide one of the terms. |
| 8964 | if (!R->isZero()) |
| 8965 | return false; |
| 8966 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 8967 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8968 | } |
| 8969 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 8970 | // Remove all SCEVConstants. |
Tobias Grosser | 1e9db7e | 2014-05-08 21:43:19 +0000 | [diff] [blame] | 8971 | Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) { |
| 8972 | return isa<SCEVConstant>(E); |
| 8973 | }), |
| 8974 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8975 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8976 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8977 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 8978 | return false; |
| 8979 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8980 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8981 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8982 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8983 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8984 | // Returns true when S contains at least a SCEVUnknown parameter. |
| 8985 | static inline bool |
| 8986 | containsParameters(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 8987 | struct FindParameter { |
| 8988 | bool FoundParameter; |
| 8989 | FindParameter() : FoundParameter(false) {} |
| 8990 | |
| 8991 | bool follow(const SCEV *S) { |
| 8992 | if (isa<SCEVUnknown>(S)) { |
| 8993 | FoundParameter = true; |
| 8994 | // Stop recursion: we found a parameter. |
| 8995 | return false; |
| 8996 | } |
| 8997 | // Keep looking. |
| 8998 | return true; |
| 8999 | } |
| 9000 | bool isDone() const { |
| 9001 | // Stop recursion if we have found a parameter. |
| 9002 | return FoundParameter; |
| 9003 | } |
| 9004 | }; |
| 9005 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9006 | FindParameter F; |
| 9007 | SCEVTraversal<FindParameter> ST(F); |
| 9008 | ST.visitAll(S); |
| 9009 | |
| 9010 | return F.FoundParameter; |
| 9011 | } |
| 9012 | |
| 9013 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
| 9014 | static inline bool |
| 9015 | containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
| 9016 | for (const SCEV *T : Terms) |
| 9017 | if (containsParameters(T)) |
| 9018 | return true; |
| 9019 | return false; |
| 9020 | } |
| 9021 | |
| 9022 | // Return the number of product terms in S. |
| 9023 | static inline int numberOfTerms(const SCEV *S) { |
| 9024 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 9025 | return Expr->getNumOperands(); |
| 9026 | return 1; |
| 9027 | } |
| 9028 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9029 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 9030 | if (isa<SCEVConstant>(T)) |
| 9031 | return nullptr; |
| 9032 | |
| 9033 | if (isa<SCEVUnknown>(T)) |
| 9034 | return T; |
| 9035 | |
| 9036 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 9037 | SmallVector<const SCEV *, 2> Factors; |
| 9038 | for (const SCEV *Op : M->operands()) |
| 9039 | if (!isa<SCEVConstant>(Op)) |
| 9040 | Factors.push_back(Op); |
| 9041 | |
| 9042 | return SE.getMulExpr(Factors); |
| 9043 | } |
| 9044 | |
| 9045 | return T; |
| 9046 | } |
| 9047 | |
| 9048 | /// Return the size of an element read or written by Inst. |
| 9049 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 9050 | Type *Ty; |
| 9051 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 9052 | Ty = Store->getValueOperand()->getType(); |
| 9053 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 9054 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9055 | else |
| 9056 | return nullptr; |
| 9057 | |
| 9058 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 9059 | return getSizeOfExpr(ETy, Ty); |
| 9060 | } |
| 9061 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9062 | /// Second step of delinearization: compute the array dimensions Sizes from the |
| 9063 | /// set of Terms extracted from the memory access function of this SCEVAddRec. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9064 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 9065 | SmallVectorImpl<const SCEV *> &Sizes, |
| 9066 | const SCEV *ElementSize) const { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9067 | |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 9068 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9069 | return; |
| 9070 | |
| 9071 | // Early return when Terms do not contain parameters: we do not delinearize |
| 9072 | // non parametric SCEVs. |
| 9073 | if (!containsParameters(Terms)) |
| 9074 | return; |
| 9075 | |
| 9076 | DEBUG({ |
| 9077 | dbgs() << "Terms:\n"; |
| 9078 | for (const SCEV *T : Terms) |
| 9079 | dbgs() << *T << "\n"; |
| 9080 | }); |
| 9081 | |
| 9082 | // Remove duplicates. |
| 9083 | std::sort(Terms.begin(), Terms.end()); |
| 9084 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 9085 | |
| 9086 | // Put larger terms first. |
| 9087 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 9088 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 9089 | }); |
| 9090 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9091 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9092 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9093 | // Try to divide all terms by the element size. If term is not divisible by |
| 9094 | // element size, proceed with the original term. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9095 | for (const SCEV *&Term : Terms) { |
| 9096 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9097 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9098 | if (!Q->isZero()) |
| 9099 | Term = Q; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9100 | } |
| 9101 | |
| 9102 | SmallVector<const SCEV *, 4> NewTerms; |
| 9103 | |
| 9104 | // Remove constant factors. |
| 9105 | for (const SCEV *T : Terms) |
| 9106 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 9107 | NewTerms.push_back(NewT); |
| 9108 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9109 | DEBUG({ |
| 9110 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9111 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9112 | dbgs() << *T << "\n"; |
| 9113 | }); |
| 9114 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9115 | if (NewTerms.empty() || |
| 9116 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9117 | Sizes.clear(); |
| 9118 | return; |
| 9119 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9120 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9121 | // The last element to be pushed into Sizes is the size of an element. |
| 9122 | Sizes.push_back(ElementSize); |
| 9123 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9124 | DEBUG({ |
| 9125 | dbgs() << "Sizes:\n"; |
| 9126 | for (const SCEV *S : Sizes) |
| 9127 | dbgs() << *S << "\n"; |
| 9128 | }); |
| 9129 | } |
| 9130 | |
| 9131 | /// Third step of delinearization: compute the access functions for the |
| 9132 | /// Subscripts based on the dimensions in Sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9133 | void ScalarEvolution::computeAccessFunctions( |
| 9134 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 9135 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9136 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9137 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9138 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9139 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9140 | |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 9141 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9142 | if (!AR->isAffine()) |
| 9143 | return; |
| 9144 | |
| 9145 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9146 | int Last = Sizes.size() - 1; |
| 9147 | for (int i = Last; i >= 0; i--) { |
| 9148 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9149 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9150 | |
| 9151 | DEBUG({ |
| 9152 | dbgs() << "Res: " << *Res << "\n"; |
| 9153 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 9154 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 9155 | dbgs() << "Quotient: " << *Q << "\n"; |
| 9156 | dbgs() << "Remainder: " << *R << "\n"; |
| 9157 | }); |
| 9158 | |
| 9159 | Res = Q; |
| 9160 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9161 | // Do not record the last subscript corresponding to the size of elements in |
| 9162 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9163 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9164 | |
| 9165 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9166 | if (isa<SCEVAddRecExpr>(R)) { |
| 9167 | Subscripts.clear(); |
| 9168 | Sizes.clear(); |
| 9169 | return; |
| 9170 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9171 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9172 | continue; |
| 9173 | } |
| 9174 | |
| 9175 | // Record the access function for the current subscript. |
| 9176 | Subscripts.push_back(R); |
| 9177 | } |
| 9178 | |
| 9179 | // Also push in last position the remainder of the last division: it will be |
| 9180 | // the access function of the innermost dimension. |
| 9181 | Subscripts.push_back(Res); |
| 9182 | |
| 9183 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 9184 | |
| 9185 | DEBUG({ |
| 9186 | dbgs() << "Subscripts:\n"; |
| 9187 | for (const SCEV *S : Subscripts) |
| 9188 | dbgs() << *S << "\n"; |
| 9189 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9190 | } |
| 9191 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9192 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 9193 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9194 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 9195 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 9196 | /// expressions in the stride and base of a SCEV corresponding to the |
| 9197 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 9198 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 9199 | /// |
| 9200 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 9201 | /// |
| 9202 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 9203 | /// |
| 9204 | /// for (long i = 0; i < n; i++) |
| 9205 | /// for (long j = 0; j < m; j++) |
| 9206 | /// for (long k = 0; k < o; k++) |
| 9207 | /// A[i][j][k] = 1.0; |
| 9208 | /// } |
| 9209 | /// |
| 9210 | /// the delinearization input is the following AddRec SCEV: |
| 9211 | /// |
| 9212 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 9213 | /// |
| 9214 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 9215 | /// because it appears as an offset that does not divide any of the strides in |
| 9216 | /// the loops: |
| 9217 | /// |
| 9218 | /// CHECK: Base offset: %A |
| 9219 | /// |
| 9220 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 9221 | /// the array as these are the multiples by which the strides are happening: |
| 9222 | /// |
| 9223 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 9224 | /// |
| 9225 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 9226 | /// no strides that would help identifying the size of the last dimension: when |
| 9227 | /// the array has been statically allocated, one could compute the size of that |
| 9228 | /// dimension by dividing the overall size of the array by the size of the known |
| 9229 | /// dimensions: %m * %o * 8. |
| 9230 | /// |
| 9231 | /// Finally delinearize provides the access functions for the array reference |
| 9232 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 9233 | /// |
| 9234 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 9235 | /// |
| 9236 | /// The testcases are checking the output of a function pass: |
| 9237 | /// DelinearizationPass that walks through all loads and stores of a function |
| 9238 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 9239 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 9240 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9241 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9242 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 9243 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9244 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9245 | // First step: collect parametric terms. |
| 9246 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9247 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9248 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9249 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9250 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9251 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9252 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9253 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9254 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9255 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9256 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9257 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9258 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9259 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9260 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9261 | if (Subscripts.empty()) |
| 9262 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9263 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9264 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9265 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9266 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 9267 | for (const SCEV *S : Sizes) |
| 9268 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9269 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 9270 | dbgs() << "\nArrayRef"; |
| 9271 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9272 | dbgs() << "[" << *S << "]"; |
| 9273 | dbgs() << "\n"; |
| 9274 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9275 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9276 | |
| 9277 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9278 | // SCEVCallbackVH Class Implementation |
| 9279 | //===----------------------------------------------------------------------===// |
| 9280 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9281 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9282 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9283 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 9284 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9285 | SE->eraseValueFromMap(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9286 | // this now dangles! |
| 9287 | } |
| 9288 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 9289 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9290 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 9291 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9292 | // Forget all the expressions associated with users of the old value, |
| 9293 | // so that future queries will recompute the expressions using the new |
| 9294 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9295 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9296 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9297 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9298 | while (!Worklist.empty()) { |
| 9299 | User *U = Worklist.pop_back_val(); |
| 9300 | // Deleting the Old value will cause this to dangle. Postpone |
| 9301 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9302 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9303 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 9304 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9305 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9306 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 9307 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9308 | SE->eraseValueFromMap(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9309 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9310 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9311 | // Delete the Old value. |
| 9312 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 9313 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9314 | SE->eraseValueFromMap(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9315 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9316 | } |
| 9317 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9318 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9319 | : CallbackVH(V), SE(se) {} |
| 9320 | |
| 9321 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9322 | // ScalarEvolution Class Implementation |
| 9323 | //===----------------------------------------------------------------------===// |
| 9324 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9325 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
| 9326 | AssumptionCache &AC, DominatorTree &DT, |
| 9327 | LoopInfo &LI) |
| 9328 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
| 9329 | CouldNotCompute(new SCEVCouldNotCompute()), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9330 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
| 9331 | ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), |
| 9332 | FirstUnknown(nullptr) {} |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9333 | |
| 9334 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
| 9335 | : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), |
| 9336 | CouldNotCompute(std::move(Arg.CouldNotCompute)), |
| 9337 | ValueExprMap(std::move(Arg.ValueExprMap)), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9338 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9339 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
| 9340 | ConstantEvolutionLoopExitValue( |
| 9341 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 9342 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 9343 | LoopDispositions(std::move(Arg.LoopDispositions)), |
| 9344 | BlockDispositions(std::move(Arg.BlockDispositions)), |
| 9345 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 9346 | SignedRanges(std::move(Arg.SignedRanges)), |
| 9347 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9348 | UniquePreds(std::move(Arg.UniquePreds)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9349 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 9350 | FirstUnknown(Arg.FirstUnknown) { |
| 9351 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9352 | } |
| 9353 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9354 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9355 | // Iterate through all the SCEVUnknown instances and call their |
| 9356 | // destructors, so that they release their references to their values. |
Naomi Musgrave | f90c1be | 2015-09-16 23:46:40 +0000 | [diff] [blame] | 9357 | for (SCEVUnknown *U = FirstUnknown; U;) { |
| 9358 | SCEVUnknown *Tmp = U; |
| 9359 | U = U->Next; |
| 9360 | Tmp->~SCEVUnknown(); |
| 9361 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 9362 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9363 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9364 | ExprValueMap.clear(); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 9365 | ValueExprMap.clear(); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9366 | HasRecMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9367 | |
| 9368 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 9369 | // that a loop had multiple computable exits. |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9370 | for (auto &BTCI : BackedgeTakenCounts) |
| 9371 | BTCI.second.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9372 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 9373 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 9374 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9375 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 9376 | } |
| 9377 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9378 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9379 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9380 | } |
| 9381 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9382 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9383 | const Loop *L) { |
| 9384 | // Print all inner loops first |
| 9385 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 9386 | PrintLoopInfo(OS, SE, *I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9387 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9388 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9389 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9390 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9391 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9392 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9393 | L->getExitBlocks(ExitBlocks); |
| 9394 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 9395 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9396 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9397 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 9398 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9399 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9400 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9401 | } |
| 9402 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9403 | OS << "\n" |
| 9404 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9405 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9406 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9407 | |
| 9408 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 9409 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
| 9410 | } else { |
| 9411 | OS << "Unpredictable max backedge-taken count. "; |
| 9412 | } |
| 9413 | |
| 9414 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9415 | } |
| 9416 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9417 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 9418 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9419 | // out SCEV values of all instructions that are interesting. Doing |
| 9420 | // this potentially causes it to create new SCEV objects though, |
| 9421 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 9422 | // observable from outside the class though, so casting away the |
| 9423 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9424 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9425 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9426 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9427 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9428 | OS << "\n"; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9429 | for (Instruction &I : instructions(F)) |
| 9430 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { |
| 9431 | OS << I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 9432 | OS << " --> "; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9433 | const SCEV *SV = SE.getSCEV(&I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9434 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9435 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 9436 | OS << " U: "; |
| 9437 | SE.getUnsignedRange(SV).print(OS); |
| 9438 | OS << " S: "; |
| 9439 | SE.getSignedRange(SV).print(OS); |
| 9440 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9441 | |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9442 | const Loop *L = LI.getLoopFor(I.getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9443 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9444 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9445 | if (AtUse != SV) { |
| 9446 | OS << " --> "; |
| 9447 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9448 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 9449 | OS << " U: "; |
| 9450 | SE.getUnsignedRange(AtUse).print(OS); |
| 9451 | OS << " S: "; |
| 9452 | SE.getSignedRange(AtUse).print(OS); |
| 9453 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9454 | } |
| 9455 | |
| 9456 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 9457 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9458 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9459 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9460 | OS << "<<Unknown>>"; |
| 9461 | } else { |
| 9462 | OS << *ExitValue; |
| 9463 | } |
| 9464 | } |
| 9465 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9466 | OS << "\n"; |
| 9467 | } |
| 9468 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9469 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9470 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9471 | OS << "\n"; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9472 | for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9473 | PrintLoopInfo(OS, &SE, *I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9474 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 9475 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9476 | ScalarEvolution::LoopDisposition |
| 9477 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9478 | auto &Values = LoopDispositions[S]; |
| 9479 | for (auto &V : Values) { |
| 9480 | if (V.getPointer() == L) |
| 9481 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9482 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9483 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9484 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9485 | auto &Values2 = LoopDispositions[S]; |
| 9486 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9487 | if (V.getPointer() == L) { |
| 9488 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9489 | break; |
| 9490 | } |
| 9491 | } |
| 9492 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9493 | } |
| 9494 | |
| 9495 | ScalarEvolution::LoopDisposition |
| 9496 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9497 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9498 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9499 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9500 | case scTruncate: |
| 9501 | case scZeroExtend: |
| 9502 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9503 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9504 | case scAddRecExpr: { |
| 9505 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 9506 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9507 | // If L is the addrec's loop, it's computable. |
| 9508 | if (AR->getLoop() == L) |
| 9509 | return LoopComputable; |
| 9510 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9511 | // Add recurrences are never invariant in the function-body (null loop). |
| 9512 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9513 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9514 | |
| 9515 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 9516 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9517 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9518 | |
| 9519 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 9520 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9521 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9522 | |
| 9523 | // This recurrence is variant w.r.t. L if any of its operands |
| 9524 | // are variant. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9525 | for (auto *Op : AR->operands()) |
| 9526 | if (!isLoopInvariant(Op, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9527 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9528 | |
| 9529 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9530 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9531 | } |
| 9532 | case scAddExpr: |
| 9533 | case scMulExpr: |
| 9534 | case scUMaxExpr: |
| 9535 | case scSMaxExpr: { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9536 | bool HasVarying = false; |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9537 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { |
| 9538 | LoopDisposition D = getLoopDisposition(Op, L); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9539 | if (D == LoopVariant) |
| 9540 | return LoopVariant; |
| 9541 | if (D == LoopComputable) |
| 9542 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9543 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9544 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9545 | } |
| 9546 | case scUDivExpr: { |
| 9547 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9548 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 9549 | if (LD == LoopVariant) |
| 9550 | return LoopVariant; |
| 9551 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 9552 | if (RD == LoopVariant) |
| 9553 | return LoopVariant; |
| 9554 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 9555 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9556 | } |
| 9557 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9558 | // All non-instruction values are loop invariant. All instructions are loop |
| 9559 | // invariant if they are not contained in the specified loop. |
| 9560 | // Instructions are never considered invariant in the function body |
| 9561 | // (null loop) because they are defined within the "loop". |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9562 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9563 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 9564 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9565 | case scCouldNotCompute: |
| 9566 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9567 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9568 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9569 | } |
| 9570 | |
| 9571 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 9572 | return getLoopDisposition(S, L) == LoopInvariant; |
| 9573 | } |
| 9574 | |
| 9575 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 9576 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9577 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9578 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9579 | ScalarEvolution::BlockDisposition |
| 9580 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9581 | auto &Values = BlockDispositions[S]; |
| 9582 | for (auto &V : Values) { |
| 9583 | if (V.getPointer() == BB) |
| 9584 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9585 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9586 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9587 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9588 | auto &Values2 = BlockDispositions[S]; |
| 9589 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9590 | if (V.getPointer() == BB) { |
| 9591 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9592 | break; |
| 9593 | } |
| 9594 | } |
| 9595 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9596 | } |
| 9597 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9598 | ScalarEvolution::BlockDisposition |
| 9599 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9600 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9601 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9602 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9603 | case scTruncate: |
| 9604 | case scZeroExtend: |
| 9605 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9606 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9607 | case scAddRecExpr: { |
| 9608 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9609 | // to test for proper dominance too, because the instruction which |
| 9610 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 9611 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9612 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9613 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9614 | return DoesNotDominateBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9615 | } |
| 9616 | // FALL THROUGH into SCEVNAryExpr handling. |
| 9617 | case scAddExpr: |
| 9618 | case scMulExpr: |
| 9619 | case scUMaxExpr: |
| 9620 | case scSMaxExpr: { |
| 9621 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9622 | bool Proper = true; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 9623 | for (const SCEV *NAryOp : NAry->operands()) { |
| 9624 | BlockDisposition D = getBlockDisposition(NAryOp, BB); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9625 | if (D == DoesNotDominateBlock) |
| 9626 | return DoesNotDominateBlock; |
| 9627 | if (D == DominatesBlock) |
| 9628 | Proper = false; |
| 9629 | } |
| 9630 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9631 | } |
| 9632 | case scUDivExpr: { |
| 9633 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9634 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 9635 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 9636 | if (LD == DoesNotDominateBlock) |
| 9637 | return DoesNotDominateBlock; |
| 9638 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 9639 | if (RD == DoesNotDominateBlock) |
| 9640 | return DoesNotDominateBlock; |
| 9641 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 9642 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9643 | } |
| 9644 | case scUnknown: |
| 9645 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9646 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 9647 | if (I->getParent() == BB) |
| 9648 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9649 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9650 | return ProperlyDominatesBlock; |
| 9651 | return DoesNotDominateBlock; |
| 9652 | } |
| 9653 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9654 | case scCouldNotCompute: |
| 9655 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9656 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9657 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9658 | } |
| 9659 | |
| 9660 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 9661 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 9662 | } |
| 9663 | |
| 9664 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 9665 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9666 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9667 | |
| 9668 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 9669 | // Search for a SCEV expression node within an expression tree. |
| 9670 | // Implements SCEVTraversal::Visitor. |
| 9671 | struct SCEVSearch { |
| 9672 | const SCEV *Node; |
| 9673 | bool IsFound; |
| 9674 | |
| 9675 | SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} |
| 9676 | |
| 9677 | bool follow(const SCEV *S) { |
| 9678 | IsFound |= (S == Node); |
| 9679 | return !IsFound; |
| 9680 | } |
| 9681 | bool isDone() const { return IsFound; } |
| 9682 | }; |
| 9683 | |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 9684 | SCEVSearch Search(Op); |
| 9685 | visitAll(S, Search); |
| 9686 | return Search.IsFound; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9687 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9688 | |
| 9689 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 9690 | ValuesAtScopes.erase(S); |
| 9691 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9692 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9693 | UnsignedRanges.erase(S); |
| 9694 | SignedRanges.erase(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9695 | ExprValueMap.erase(S); |
| 9696 | HasRecMap.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 9697 | |
| 9698 | for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = |
| 9699 | BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) { |
| 9700 | BackedgeTakenInfo &BEInfo = I->second; |
| 9701 | if (BEInfo.hasOperand(S, this)) { |
| 9702 | BEInfo.clear(); |
| 9703 | BackedgeTakenCounts.erase(I++); |
| 9704 | } |
| 9705 | else |
| 9706 | ++I; |
| 9707 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9708 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9709 | |
| 9710 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9711 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 9712 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9713 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 9714 | size_t Pos = 0; |
| 9715 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 9716 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 9717 | Pos += To.size(); |
| 9718 | } |
| 9719 | } |
| 9720 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9721 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 9722 | static void |
| 9723 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9724 | std::string &S = Map[L]; |
| 9725 | if (S.empty()) { |
| 9726 | raw_string_ostream OS(S); |
| 9727 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9728 | |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9729 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 9730 | replaceSubString(OS.str(), "false", "0"); |
| 9731 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 9732 | // FIXME: Remove this when SCEV gets smarter about them. |
| 9733 | replaceSubString(OS.str(), "<nw>", ""); |
| 9734 | replaceSubString(OS.str(), "<nsw>", ""); |
| 9735 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9736 | } |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9737 | |
JF Bastien | 61ad8b3 | 2015-12-23 18:18:53 +0000 | [diff] [blame] | 9738 | for (auto *R : reverse(*L)) |
| 9739 | getLoopBackedgeTakenCounts(R, Map, SE); // recurse. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9740 | } |
| 9741 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9742 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9743 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9744 | |
| 9745 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 9746 | // FIXME: It would be much better to store actual values instead of strings, |
| 9747 | // but SCEV pointers will change if we drop the caches. |
| 9748 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9749 | 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] | 9750 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 9751 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9752 | // Gather stringified backedge taken counts for all loops using a fresh |
| 9753 | // ScalarEvolution object. |
| 9754 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
| 9755 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 9756 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9757 | |
| 9758 | // Now compare whether they're the same with and without caches. This allows |
| 9759 | // verifying that no pass changed the cache. |
| 9760 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 9761 | "New loops suddenly appeared!"); |
| 9762 | |
| 9763 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 9764 | OldE = BackedgeDumpsOld.end(), |
| 9765 | NewI = BackedgeDumpsNew.begin(); |
| 9766 | OldI != OldE; ++OldI, ++NewI) { |
| 9767 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 9768 | |
| 9769 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 9770 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9771 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9772 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 9773 | // usually not harmful. |
| 9774 | if (OldI->second != NewI->second && |
| 9775 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9776 | NewI->second.find("undef") == std::string::npos && |
| 9777 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9778 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9779 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9780 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9781 | << "' changed from '" << OldI->second |
| 9782 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9783 | std::abort(); |
| 9784 | } |
| 9785 | } |
| 9786 | |
| 9787 | // TODO: Verify more things. |
| 9788 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9789 | |
Chandler Carruth | b4faf13 | 2016-03-11 10:22:49 +0000 | [diff] [blame] | 9790 | char ScalarEvolutionAnalysis::PassID; |
NAKAMURA Takumi | df0cd72 | 2016-02-28 17:17:00 +0000 | [diff] [blame] | 9791 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9792 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 9793 | AnalysisManager<Function> &AM) { |
| 9794 | return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), |
| 9795 | AM.getResult<AssumptionAnalysis>(F), |
| 9796 | AM.getResult<DominatorTreeAnalysis>(F), |
| 9797 | AM.getResult<LoopAnalysis>(F)); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9798 | } |
| 9799 | |
| 9800 | PreservedAnalyses |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 9801 | ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> &AM) { |
| 9802 | AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9803 | return PreservedAnalyses::all(); |
| 9804 | } |
| 9805 | |
| 9806 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 9807 | "Scalar Evolution Analysis", false, true) |
| 9808 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 9809 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 9810 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 9811 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 9812 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 9813 | "Scalar Evolution Analysis", false, true) |
| 9814 | char ScalarEvolutionWrapperPass::ID = 0; |
| 9815 | |
| 9816 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 9817 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 9818 | } |
| 9819 | |
| 9820 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 9821 | SE.reset(new ScalarEvolution( |
| 9822 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 9823 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 9824 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 9825 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 9826 | return false; |
| 9827 | } |
| 9828 | |
| 9829 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 9830 | |
| 9831 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 9832 | SE->print(OS); |
| 9833 | } |
| 9834 | |
| 9835 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 9836 | if (!VerifySCEV) |
| 9837 | return; |
| 9838 | |
| 9839 | SE->verify(); |
| 9840 | } |
| 9841 | |
| 9842 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 9843 | AU.setPreservesAll(); |
| 9844 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
| 9845 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 9846 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 9847 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 9848 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9849 | |
| 9850 | const SCEVPredicate * |
| 9851 | ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, |
| 9852 | const SCEVConstant *RHS) { |
| 9853 | FoldingSetNodeID ID; |
| 9854 | // Unique this node based on the arguments |
| 9855 | ID.AddInteger(SCEVPredicate::P_Equal); |
| 9856 | ID.AddPointer(LHS); |
| 9857 | ID.AddPointer(RHS); |
| 9858 | void *IP = nullptr; |
| 9859 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 9860 | return S; |
| 9861 | SCEVEqualPredicate *Eq = new (SCEVAllocator) |
| 9862 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); |
| 9863 | UniquePreds.InsertNode(Eq, IP); |
| 9864 | return Eq; |
| 9865 | } |
| 9866 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9867 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( |
| 9868 | const SCEVAddRecExpr *AR, |
| 9869 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 9870 | FoldingSetNodeID ID; |
| 9871 | // Unique this node based on the arguments |
| 9872 | ID.AddInteger(SCEVPredicate::P_Wrap); |
| 9873 | ID.AddPointer(AR); |
| 9874 | ID.AddInteger(AddedFlags); |
| 9875 | void *IP = nullptr; |
| 9876 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 9877 | return S; |
| 9878 | auto *OF = new (SCEVAllocator) |
| 9879 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); |
| 9880 | UniquePreds.InsertNode(OF, IP); |
| 9881 | return OF; |
| 9882 | } |
| 9883 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 9884 | namespace { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9885 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9886 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { |
| 9887 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9888 | // Rewrites \p S in the context of a loop L and the predicate A. |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9889 | // If Assume is true, rewrite is free to add further predicates to A |
| 9890 | // such that the result will be an AddRecExpr. |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9891 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, |
| 9892 | SCEVUnionPredicate &A, bool Assume) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9893 | SCEVPredicateRewriter Rewriter(L, SE, A, Assume); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9894 | return Rewriter.visit(S); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9895 | } |
| 9896 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9897 | SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, |
| 9898 | SCEVUnionPredicate &P, bool Assume) |
| 9899 | : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {} |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9900 | |
| 9901 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 9902 | auto ExprPreds = P.getPredicatesForExpr(Expr); |
| 9903 | for (auto *Pred : ExprPreds) |
| 9904 | if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred)) |
| 9905 | if (IPred->getLHS() == Expr) |
| 9906 | return IPred->getRHS(); |
| 9907 | |
| 9908 | return Expr; |
| 9909 | } |
| 9910 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9911 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { |
| 9912 | const SCEV *Operand = visit(Expr->getOperand()); |
| 9913 | const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); |
| 9914 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 9915 | // This couldn't be folded because the operand didn't have the nuw |
| 9916 | // flag. Add the nusw flag as an assumption that we could make. |
| 9917 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 9918 | Type *Ty = Expr->getType(); |
| 9919 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) |
| 9920 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), |
| 9921 | SE.getSignExtendExpr(Step, Ty), L, |
| 9922 | AR->getNoWrapFlags()); |
| 9923 | } |
| 9924 | return SE.getZeroExtendExpr(Operand, Expr->getType()); |
| 9925 | } |
| 9926 | |
| 9927 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { |
| 9928 | const SCEV *Operand = visit(Expr->getOperand()); |
| 9929 | const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); |
| 9930 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 9931 | // This couldn't be folded because the operand didn't have the nsw |
| 9932 | // flag. Add the nssw flag as an assumption that we could make. |
| 9933 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 9934 | Type *Ty = Expr->getType(); |
| 9935 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) |
| 9936 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), |
| 9937 | SE.getSignExtendExpr(Step, Ty), L, |
| 9938 | AR->getNoWrapFlags()); |
| 9939 | } |
| 9940 | return SE.getSignExtendExpr(Operand, Expr->getType()); |
| 9941 | } |
| 9942 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9943 | private: |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9944 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, |
| 9945 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 9946 | auto *A = SE.getWrapPredicate(AR, AddedFlags); |
| 9947 | if (!Assume) { |
| 9948 | // Check if we've already made this assumption. |
| 9949 | if (P.implies(A)) |
| 9950 | return true; |
| 9951 | return false; |
| 9952 | } |
| 9953 | P.add(A); |
| 9954 | return true; |
| 9955 | } |
| 9956 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9957 | SCEVUnionPredicate &P; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9958 | const Loop *L; |
| 9959 | bool Assume; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9960 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 9961 | } // end anonymous namespace |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9962 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9963 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9964 | SCEVUnionPredicate &Preds) { |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9965 | return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9966 | } |
| 9967 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 9968 | const SCEVAddRecExpr * |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9969 | ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, |
| 9970 | SCEVUnionPredicate &Preds) { |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 9971 | SCEVUnionPredicate TransformPreds; |
| 9972 | S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true); |
| 9973 | auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); |
| 9974 | |
| 9975 | if (!AddRec) |
| 9976 | return nullptr; |
| 9977 | |
| 9978 | // Since the transformation was successful, we can now transfer the SCEV |
| 9979 | // predicates. |
| 9980 | Preds.add(&TransformPreds); |
| 9981 | return AddRec; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9982 | } |
| 9983 | |
| 9984 | /// SCEV predicates |
| 9985 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, |
| 9986 | SCEVPredicateKind Kind) |
| 9987 | : FastID(ID), Kind(Kind) {} |
| 9988 | |
| 9989 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, |
| 9990 | const SCEVUnknown *LHS, |
| 9991 | const SCEVConstant *RHS) |
| 9992 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} |
| 9993 | |
| 9994 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { |
| 9995 | const auto *Op = dyn_cast<const SCEVEqualPredicate>(N); |
| 9996 | |
| 9997 | if (!Op) |
| 9998 | return false; |
| 9999 | |
| 10000 | return Op->LHS == LHS && Op->RHS == RHS; |
| 10001 | } |
| 10002 | |
| 10003 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } |
| 10004 | |
| 10005 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } |
| 10006 | |
| 10007 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10008 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; |
| 10009 | } |
| 10010 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10011 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, |
| 10012 | const SCEVAddRecExpr *AR, |
| 10013 | IncrementWrapFlags Flags) |
| 10014 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} |
| 10015 | |
| 10016 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } |
| 10017 | |
| 10018 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { |
| 10019 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); |
| 10020 | |
| 10021 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; |
| 10022 | } |
| 10023 | |
| 10024 | bool SCEVWrapPredicate::isAlwaysTrue() const { |
| 10025 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); |
| 10026 | IncrementWrapFlags IFlags = Flags; |
| 10027 | |
| 10028 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) |
| 10029 | IFlags = clearFlags(IFlags, IncrementNSSW); |
| 10030 | |
| 10031 | return IFlags == IncrementAnyWrap; |
| 10032 | } |
| 10033 | |
| 10034 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10035 | OS.indent(Depth) << *getExpr() << " Added Flags: "; |
| 10036 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) |
| 10037 | OS << "<nusw>"; |
| 10038 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) |
| 10039 | OS << "<nssw>"; |
| 10040 | OS << "\n"; |
| 10041 | } |
| 10042 | |
| 10043 | SCEVWrapPredicate::IncrementWrapFlags |
| 10044 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, |
| 10045 | ScalarEvolution &SE) { |
| 10046 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; |
| 10047 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); |
| 10048 | |
| 10049 | // We can safely transfer the NSW flag as NSSW. |
| 10050 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) |
| 10051 | ImpliedFlags = IncrementNSSW; |
| 10052 | |
| 10053 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { |
| 10054 | // If the increment is positive, the SCEV NUW flag will also imply the |
| 10055 | // WrapPredicate NUSW flag. |
| 10056 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 10057 | if (Step->getValue()->getValue().isNonNegative()) |
| 10058 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); |
| 10059 | } |
| 10060 | |
| 10061 | return ImpliedFlags; |
| 10062 | } |
| 10063 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10064 | /// Union predicates don't get cached so create a dummy set ID for it. |
| 10065 | SCEVUnionPredicate::SCEVUnionPredicate() |
| 10066 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} |
| 10067 | |
| 10068 | bool SCEVUnionPredicate::isAlwaysTrue() const { |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10069 | return all_of(Preds, |
| 10070 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10071 | } |
| 10072 | |
| 10073 | ArrayRef<const SCEVPredicate *> |
| 10074 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { |
| 10075 | auto I = SCEVToPreds.find(Expr); |
| 10076 | if (I == SCEVToPreds.end()) |
| 10077 | return ArrayRef<const SCEVPredicate *>(); |
| 10078 | return I->second; |
| 10079 | } |
| 10080 | |
| 10081 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { |
| 10082 | if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10083 | return all_of(Set->Preds, |
| 10084 | [this](const SCEVPredicate *I) { return this->implies(I); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10085 | |
| 10086 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); |
| 10087 | if (ScevPredsIt == SCEVToPreds.end()) |
| 10088 | return false; |
| 10089 | auto &SCEVPreds = ScevPredsIt->second; |
| 10090 | |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 10091 | return any_of(SCEVPreds, |
| 10092 | [N](const SCEVPredicate *I) { return I->implies(N); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10093 | } |
| 10094 | |
| 10095 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } |
| 10096 | |
| 10097 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10098 | for (auto Pred : Preds) |
| 10099 | Pred->print(OS, Depth); |
| 10100 | } |
| 10101 | |
| 10102 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { |
| 10103 | if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) { |
| 10104 | for (auto Pred : Set->Preds) |
| 10105 | add(Pred); |
| 10106 | return; |
| 10107 | } |
| 10108 | |
| 10109 | if (implies(N)) |
| 10110 | return; |
| 10111 | |
| 10112 | const SCEV *Key = N->getExpr(); |
| 10113 | assert(Key && "Only SCEVUnionPredicate doesn't have an " |
| 10114 | " associated expression!"); |
| 10115 | |
| 10116 | SCEVToPreds[Key].push_back(N); |
| 10117 | Preds.push_back(N); |
| 10118 | } |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10119 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10120 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, |
| 10121 | Loop &L) |
| 10122 | : SE(SE), L(L), Generation(0) {} |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10123 | |
| 10124 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { |
| 10125 | const SCEV *Expr = SE.getSCEV(V); |
| 10126 | RewriteEntry &Entry = RewriteMap[Expr]; |
| 10127 | |
| 10128 | // If we already have an entry and the version matches, return it. |
| 10129 | if (Entry.second && Generation == Entry.first) |
| 10130 | return Entry.second; |
| 10131 | |
| 10132 | // We found an entry but it's stale. Rewrite the stale entry |
| 10133 | // acording to the current predicate. |
| 10134 | if (Entry.second) |
| 10135 | Expr = Entry.second; |
| 10136 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10137 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10138 | Entry = {Generation, NewSCEV}; |
| 10139 | |
| 10140 | return NewSCEV; |
| 10141 | } |
| 10142 | |
| 10143 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { |
| 10144 | if (Preds.implies(&Pred)) |
| 10145 | return; |
| 10146 | Preds.add(&Pred); |
| 10147 | updateGeneration(); |
| 10148 | } |
| 10149 | |
| 10150 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { |
| 10151 | return Preds; |
| 10152 | } |
| 10153 | |
| 10154 | void PredicatedScalarEvolution::updateGeneration() { |
| 10155 | // If the generation number wrapped recompute everything. |
| 10156 | if (++Generation == 0) { |
| 10157 | for (auto &II : RewriteMap) { |
| 10158 | const SCEV *Rewritten = II.second.second; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10159 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10160 | } |
| 10161 | } |
| 10162 | } |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10163 | |
| 10164 | void PredicatedScalarEvolution::setNoOverflow( |
| 10165 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10166 | const SCEV *Expr = getSCEV(V); |
| 10167 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10168 | |
| 10169 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); |
| 10170 | |
| 10171 | // Clear the statically implied flags. |
| 10172 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); |
| 10173 | addPredicate(*SE.getWrapPredicate(AR, Flags)); |
| 10174 | |
| 10175 | auto II = FlagsMap.insert({V, Flags}); |
| 10176 | if (!II.second) |
| 10177 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); |
| 10178 | } |
| 10179 | |
| 10180 | bool PredicatedScalarEvolution::hasNoOverflow( |
| 10181 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10182 | const SCEV *Expr = getSCEV(V); |
| 10183 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10184 | |
| 10185 | Flags = SCEVWrapPredicate::clearFlags( |
| 10186 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); |
| 10187 | |
| 10188 | auto II = FlagsMap.find(V); |
| 10189 | |
| 10190 | if (II != FlagsMap.end()) |
| 10191 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); |
| 10192 | |
| 10193 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; |
| 10194 | } |
| 10195 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10196 | const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10197 | const SCEV *Expr = this->getSCEV(V); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10198 | auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds); |
| 10199 | |
| 10200 | if (!New) |
| 10201 | return nullptr; |
| 10202 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10203 | updateGeneration(); |
| 10204 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; |
| 10205 | return New; |
| 10206 | } |
| 10207 | |
| 10208 | PredicatedScalarEvolution:: |
| 10209 | PredicatedScalarEvolution(const PredicatedScalarEvolution &Init) : |
| 10210 | RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), |
| 10211 | Generation(Init.Generation) { |
| 10212 | for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I) |
| 10213 | FlagsMap.insert(*I); |
| 10214 | } |