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 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1457 | // If we have special knowledge that this addrec won't overflow, |
| 1458 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1459 | if (AR->hasNoUnsignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1460 | return getAddRecExpr( |
| 1461 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1462 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1463 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1464 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1465 | // Note that this serves two purposes: It filters out loops that are |
| 1466 | // simply not analyzable, and it covers the case where this code is |
| 1467 | // being called from within backedge-taken count analysis, such that |
| 1468 | // attempting to ask for the backedge-taken count would likely result |
| 1469 | // in infinite recursion. In the later case, the analysis code will |
| 1470 | // cope with a conservative value, and it will take care to purge |
| 1471 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1472 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1473 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1474 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1475 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1476 | |
| 1477 | // Check whether the backedge-taken count can be losslessly casted to |
| 1478 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1479 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1480 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1481 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1482 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1483 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1484 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1485 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1486 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1487 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1488 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1489 | const SCEV *WideMaxBECount = |
| 1490 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1491 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1492 | getAddExpr(WideStart, |
| 1493 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1494 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1495 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1496 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1497 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1498 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1499 | return getAddRecExpr( |
| 1500 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1501 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1502 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1503 | // Similar to above, only this time treat the step value as signed. |
| 1504 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1505 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1506 | getAddExpr(WideStart, |
| 1507 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1508 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1509 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1510 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1511 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1512 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1513 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1514 | return getAddRecExpr( |
| 1515 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1516 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1517 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1518 | } |
| 1519 | |
| 1520 | // If the backedge is guarded by a comparison with the pre-inc value |
| 1521 | // the addrec is safe. Also, if the entry is guarded by a comparison |
| 1522 | // with the start value and the backedge is guarded by a comparison |
| 1523 | // with the post-inc value, the addrec is safe. |
| 1524 | if (isKnownPositive(Step)) { |
| 1525 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1526 | getUnsignedRange(Step).getUnsignedMax()); |
| 1527 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1528 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1529 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1530 | AR->getPostIncExpr(*this), N))) { |
| 1531 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1532 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1533 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1534 | return getAddRecExpr( |
| 1535 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1536 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1537 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1538 | } else if (isKnownNegative(Step)) { |
| 1539 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1540 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1541 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1542 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1543 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1544 | AR->getPostIncExpr(*this), N))) { |
| 1545 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1546 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1547 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1548 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1549 | return getAddRecExpr( |
| 1550 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1551 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1552 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1553 | } |
| 1554 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1555 | |
| 1556 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1557 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1558 | return getAddRecExpr( |
| 1559 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1560 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1561 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1562 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1563 | |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1564 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1565 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1566 | if (SA->hasNoUnsignedWrap()) { |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1567 | // If the addition does not unsign overflow then we can, by definition, |
| 1568 | // commute the zero extension with the addition operation. |
| 1569 | SmallVector<const SCEV *, 4> Ops; |
| 1570 | for (const auto *Op : SA->operands()) |
| 1571 | Ops.push_back(getZeroExtendExpr(Op, Ty)); |
| 1572 | return getAddExpr(Ops, SCEV::FlagNUW); |
| 1573 | } |
| 1574 | } |
| 1575 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1576 | // The cast wasn't folded; create an explicit cast node. |
| 1577 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1578 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1579 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1580 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1581 | UniqueSCEVs.InsertNode(S, IP); |
| 1582 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1583 | } |
| 1584 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1585 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1586 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1587 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1588 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1589 | assert(isSCEVable(Ty) && |
| 1590 | "This is not a conversion to a SCEVable type!"); |
| 1591 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1592 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1593 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1594 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1595 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1596 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1597 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1598 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1599 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1600 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1601 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1602 | // sext(zext(x)) --> zext(x) |
| 1603 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1604 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1605 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1606 | // Before doing any expensive analysis, check to see if we've already |
| 1607 | // computed a SCEV for this Op and Ty. |
| 1608 | FoldingSetNodeID ID; |
| 1609 | ID.AddInteger(scSignExtend); |
| 1610 | ID.AddPointer(Op); |
| 1611 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1612 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1613 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1614 | |
Nick Lewycky | b32c894 | 2011-01-22 22:06:21 +0000 | [diff] [blame] | 1615 | // If the input value is provably positive, build a zext instead. |
| 1616 | if (isKnownNonNegative(Op)) |
| 1617 | return getZeroExtendExpr(Op, Ty); |
| 1618 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1619 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1620 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1621 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1622 | // so, we should be able to simplify this further. |
| 1623 | const SCEV *X = ST->getOperand(); |
| 1624 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1625 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1626 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1627 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1628 | CR.sextOrTrunc(NewBits))) |
| 1629 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1630 | } |
| 1631 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1632 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1633 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1634 | if (SA->getNumOperands() == 2) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1635 | auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1636 | auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1637 | if (SMul && SC1) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1638 | if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1639 | const APInt &C1 = SC1->getAPInt(); |
| 1640 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1641 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1642 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1643 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1644 | getSignExtendExpr(SMul, Ty)); |
| 1645 | } |
| 1646 | } |
| 1647 | } |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1648 | |
| 1649 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1650 | if (SA->hasNoSignedWrap()) { |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1651 | // If the addition does not sign overflow then we can, by definition, |
| 1652 | // commute the sign extension with the addition operation. |
| 1653 | SmallVector<const SCEV *, 4> Ops; |
| 1654 | for (const auto *Op : SA->operands()) |
| 1655 | Ops.push_back(getSignExtendExpr(Op, Ty)); |
| 1656 | return getAddExpr(Ops, SCEV::FlagNSW); |
| 1657 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1658 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1659 | // 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] | 1660 | // 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] | 1661 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1662 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1663 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1664 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1665 | const SCEV *Start = AR->getStart(); |
| 1666 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1667 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1668 | const Loop *L = AR->getLoop(); |
| 1669 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1670 | // If we have special knowledge that this addrec won't overflow, |
| 1671 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1672 | if (AR->hasNoSignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1673 | return getAddRecExpr( |
| 1674 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1675 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1676 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1677 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1678 | // Note that this serves two purposes: It filters out loops that are |
| 1679 | // simply not analyzable, and it covers the case where this code is |
| 1680 | // being called from within backedge-taken count analysis, such that |
| 1681 | // attempting to ask for the backedge-taken count would likely result |
| 1682 | // in infinite recursion. In the later case, the analysis code will |
| 1683 | // cope with a conservative value, and it will take care to purge |
| 1684 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1685 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1686 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1687 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1688 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1689 | |
| 1690 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1691 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1692 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1693 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1694 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1695 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1696 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1697 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1698 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1699 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1700 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1701 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1702 | const SCEV *WideMaxBECount = |
| 1703 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1704 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1705 | getAddExpr(WideStart, |
| 1706 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1707 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1708 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1709 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1710 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1711 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1712 | return getAddRecExpr( |
| 1713 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1714 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1715 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1716 | // Similar to above, only this time treat the step value as unsigned. |
| 1717 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1718 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1719 | getAddExpr(WideStart, |
| 1720 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1721 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1722 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1723 | // If AR wraps around then |
| 1724 | // |
| 1725 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1726 | // => SAdd != OperandExtendedAdd |
| 1727 | // |
| 1728 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1729 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1730 | |
| 1731 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1732 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1733 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1734 | return getAddRecExpr( |
| 1735 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1736 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1737 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1738 | } |
| 1739 | |
| 1740 | // If the backedge is guarded by a comparison with the pre-inc value |
| 1741 | // the addrec is safe. Also, if the entry is guarded by a comparison |
| 1742 | // with the start value and the backedge is guarded by a comparison |
| 1743 | // with the post-inc value, the addrec is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1744 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1745 | const SCEV *OverflowLimit = |
| 1746 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1747 | if (OverflowLimit && |
| 1748 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1749 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1750 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1751 | OverflowLimit)))) { |
| 1752 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1753 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1754 | return getAddRecExpr( |
| 1755 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1756 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1757 | } |
| 1758 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1759 | // If Start and Step are constants, check if we can apply this |
| 1760 | // transformation: |
| 1761 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1762 | auto *SC1 = dyn_cast<SCEVConstant>(Start); |
| 1763 | auto *SC2 = dyn_cast<SCEVConstant>(Step); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1764 | if (SC1 && SC2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1765 | const APInt &C1 = SC1->getAPInt(); |
| 1766 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1767 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1768 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1769 | Start = getSignExtendExpr(Start, Ty); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1770 | const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, |
| 1771 | AR->getNoWrapFlags()); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1772 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1773 | } |
| 1774 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1775 | |
| 1776 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1777 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1778 | return getAddRecExpr( |
| 1779 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1780 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1781 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1782 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1783 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1784 | // The cast wasn't folded; create an explicit cast node. |
| 1785 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1786 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1787 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1788 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1789 | UniqueSCEVs.InsertNode(S, IP); |
| 1790 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1791 | } |
| 1792 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1793 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1794 | /// unspecified bits out to the given type. |
| 1795 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1796 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1797 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1798 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1799 | "This is not an extending conversion!"); |
| 1800 | assert(isSCEVable(Ty) && |
| 1801 | "This is not a conversion to a SCEVable type!"); |
| 1802 | Ty = getEffectiveSCEVType(Ty); |
| 1803 | |
| 1804 | // Sign-extend negative constants. |
| 1805 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1806 | if (SC->getAPInt().isNegative()) |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1807 | return getSignExtendExpr(Op, Ty); |
| 1808 | |
| 1809 | // Peel off a truncate cast. |
| 1810 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1811 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1812 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1813 | return getAnyExtendExpr(NewOp, Ty); |
| 1814 | return getTruncateOrNoop(NewOp, Ty); |
| 1815 | } |
| 1816 | |
| 1817 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1818 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1819 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1820 | return ZExt; |
| 1821 | |
| 1822 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1823 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1824 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1825 | return SExt; |
| 1826 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1827 | // Force the cast to be folded into the operands of an addrec. |
| 1828 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1829 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1830 | for (const SCEV *Op : AR->operands()) |
| 1831 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1832 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1833 | } |
| 1834 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1835 | // If the expression is obviously signed, use the sext cast value. |
| 1836 | if (isa<SCEVSMaxExpr>(Op)) |
| 1837 | return SExt; |
| 1838 | |
| 1839 | // Absent any other information, use the zext cast value. |
| 1840 | return ZExt; |
| 1841 | } |
| 1842 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1843 | /// CollectAddOperandsWithScales - Process the given Ops list, which is |
| 1844 | /// a list of operands to be added under the given scale, update the given |
| 1845 | /// map. This is a helper function for getAddRecExpr. As an example of |
| 1846 | /// what it does, given a sequence of operands that would form an add |
| 1847 | /// expression like this: |
| 1848 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1849 | /// 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] | 1850 | /// |
| 1851 | /// where A and B are constants, update the map with these values: |
| 1852 | /// |
| 1853 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1854 | /// |
| 1855 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1856 | /// This will allow getAddRecExpr to produce this: |
| 1857 | /// |
| 1858 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1859 | /// |
| 1860 | /// This form often exposes folding opportunities that are hidden in |
| 1861 | /// the original operand list. |
| 1862 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1863 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1864 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1865 | /// the common case where no interesting opportunities are present, and |
| 1866 | /// is also used as a check to avoid infinite recursion. |
| 1867 | /// |
| 1868 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1869 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1870 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1871 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1872 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1873 | const APInt &Scale, |
| 1874 | ScalarEvolution &SE) { |
| 1875 | bool Interesting = false; |
| 1876 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1877 | // Iterate over the add operands. They are sorted, with constants first. |
| 1878 | unsigned i = 0; |
| 1879 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1880 | ++i; |
| 1881 | // Pull a buried constant out to the outside. |
| 1882 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1883 | Interesting = true; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1884 | AccumulatedConstant += Scale * C->getAPInt(); |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1885 | } |
| 1886 | |
| 1887 | // Next comes everything else. We're especially interested in multiplies |
| 1888 | // here, but they're in the middle, so just visit the rest with one loop. |
| 1889 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1890 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 1891 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 1892 | APInt NewScale = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1893 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1894 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 1895 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1896 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1897 | Interesting |= |
| 1898 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1899 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1900 | NewScale, SE); |
| 1901 | } else { |
| 1902 | // A multiplication of a constant with some other value. Update |
| 1903 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1904 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 1905 | const SCEV *Key = SE.getMulExpr(MulOps); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1906 | auto Pair = M.insert({Key, NewScale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1907 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1908 | NewOps.push_back(Pair.first->first); |
| 1909 | } else { |
| 1910 | Pair.first->second += NewScale; |
| 1911 | // The map already had an entry for this value, which may indicate |
| 1912 | // a folding opportunity. |
| 1913 | Interesting = true; |
| 1914 | } |
| 1915 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1916 | } else { |
| 1917 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1918 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1919 | M.insert({Ops[i], Scale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1920 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1921 | NewOps.push_back(Pair.first->first); |
| 1922 | } else { |
| 1923 | Pair.first->second += Scale; |
| 1924 | // The map already had an entry for this value, which may indicate |
| 1925 | // a folding opportunity. |
| 1926 | Interesting = true; |
| 1927 | } |
| 1928 | } |
| 1929 | } |
| 1930 | |
| 1931 | return Interesting; |
| 1932 | } |
| 1933 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1934 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 1935 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 1936 | // can't-overflow flags for the operation if possible. |
| 1937 | static SCEV::NoWrapFlags |
| 1938 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 1939 | const SmallVectorImpl<const SCEV *> &Ops, |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1940 | SCEV::NoWrapFlags Flags) { |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1941 | using namespace std::placeholders; |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1942 | typedef OverflowingBinaryOperator OBO; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1943 | |
| 1944 | bool CanAnalyze = |
| 1945 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 1946 | (void)CanAnalyze; |
| 1947 | assert(CanAnalyze && "don't call from other places!"); |
| 1948 | |
| 1949 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 1950 | SCEV::NoWrapFlags SignOrUnsignWrap = |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1951 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1952 | |
| 1953 | // 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] | 1954 | auto IsKnownNonNegative = [&](const SCEV *S) { |
| 1955 | return SE->isKnownNonNegative(S); |
| 1956 | }; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1957 | |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 1958 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1959 | Flags = |
| 1960 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1961 | |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1962 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
| 1963 | |
| 1964 | if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && |
| 1965 | Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { |
| 1966 | |
| 1967 | // (A + C) --> (A + C)<nsw> if the addition does not sign overflow |
| 1968 | // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow |
| 1969 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1970 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1971 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { |
| 1972 | auto NSWRegion = |
| 1973 | ConstantRange::makeNoWrapRegion(Instruction::Add, C, OBO::NoSignedWrap); |
| 1974 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) |
| 1975 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 1976 | } |
| 1977 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { |
| 1978 | auto NUWRegion = |
| 1979 | ConstantRange::makeNoWrapRegion(Instruction::Add, C, |
| 1980 | OBO::NoUnsignedWrap); |
| 1981 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) |
| 1982 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 1983 | } |
| 1984 | } |
| 1985 | |
| 1986 | return Flags; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1987 | } |
| 1988 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 1989 | /// getAddExpr - Get a canonical add expression, or something simpler if |
| 1990 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 1991 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1992 | SCEV::NoWrapFlags Flags) { |
| 1993 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 1994 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1995 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 1996 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 1997 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1998 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 1999 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 2000 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2001 | "SCEVAddExpr operand types don't match!"); |
| 2002 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2003 | |
| 2004 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2005 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2006 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2007 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
| 2008 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2009 | // If there are any constants, fold them together. |
| 2010 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2011 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2012 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2013 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2014 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2015 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2016 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 2017 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2018 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2019 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2020 | } |
| 2021 | |
| 2022 | // 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] | 2023 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2024 | Ops.erase(Ops.begin()); |
| 2025 | --Idx; |
| 2026 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2027 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2028 | if (Ops.size() == 1) return Ops[0]; |
| 2029 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2030 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2031 | // Okay, check to see if the same value occurs in the operand list more than |
| 2032 | // once. If so, merge them together into an multiply expression. Since we |
| 2033 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2034 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2035 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2036 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2037 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2038 | // Scan ahead to count how many equal operands there are. |
| 2039 | unsigned Count = 2; |
| 2040 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2041 | ++Count; |
| 2042 | // Merge the values into a multiply. |
| 2043 | const SCEV *Scale = getConstant(Ty, Count); |
| 2044 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2045 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2046 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2047 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2048 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2049 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2050 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2051 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2052 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2053 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2054 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2055 | // Check for truncates. If all the operands are truncated from the same |
| 2056 | // type, see if factoring out the truncate would permit the result to be |
| 2057 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2058 | // if the contents of the resulting outer trunc fold to something simple. |
| 2059 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2060 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2061 | Type *DstType = Trunc->getType(); |
| 2062 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2063 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2064 | bool Ok = true; |
| 2065 | // Check all the operands to see if they can be represented in the |
| 2066 | // source type of the truncate. |
| 2067 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2068 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2069 | if (T->getOperand()->getType() != SrcType) { |
| 2070 | Ok = false; |
| 2071 | break; |
| 2072 | } |
| 2073 | LargeOps.push_back(T->getOperand()); |
| 2074 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2075 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2076 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2077 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2078 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2079 | if (const SCEVTruncateExpr *T = |
| 2080 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2081 | if (T->getOperand()->getType() != SrcType) { |
| 2082 | Ok = false; |
| 2083 | break; |
| 2084 | } |
| 2085 | LargeMulOps.push_back(T->getOperand()); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2086 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2087 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2088 | } else { |
| 2089 | Ok = false; |
| 2090 | break; |
| 2091 | } |
| 2092 | } |
| 2093 | if (Ok) |
| 2094 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2095 | } else { |
| 2096 | Ok = false; |
| 2097 | break; |
| 2098 | } |
| 2099 | } |
| 2100 | if (Ok) { |
| 2101 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2102 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2103 | // If it folds to something simple, use it. Otherwise, don't. |
| 2104 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2105 | return getTruncateExpr(Fold, DstType); |
| 2106 | } |
| 2107 | } |
| 2108 | |
| 2109 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2110 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2111 | ++Idx; |
| 2112 | |
| 2113 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2114 | if (Idx < Ops.size()) { |
| 2115 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2116 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2117 | // If we have an add, expand the add operands onto the end of the operands |
| 2118 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2119 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2120 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2121 | DeletedAdd = true; |
| 2122 | } |
| 2123 | |
| 2124 | // If we deleted at least one add, we added operands to the end of the list, |
| 2125 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2126 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2127 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2128 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2129 | } |
| 2130 | |
| 2131 | // Skip over the add expression until we get to a multiply. |
| 2132 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2133 | ++Idx; |
| 2134 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2135 | // Check to see if there are any folding opportunities present with |
| 2136 | // operands multiplied by constant values. |
| 2137 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2138 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2139 | DenseMap<const SCEV *, APInt> M; |
| 2140 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2141 | APInt AccumulatedConstant(BitWidth, 0); |
| 2142 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2143 | Ops.data(), Ops.size(), |
| 2144 | APInt(BitWidth, 1), *this)) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 2145 | struct APIntCompare { |
| 2146 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 2147 | return LHS.ult(RHS); |
| 2148 | } |
| 2149 | }; |
| 2150 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2151 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2152 | // re-generate the operands list. Group the operands by constant scale, |
| 2153 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2154 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2155 | for (const SCEV *NewOp : NewOps) |
| 2156 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2157 | // Re-generate the operands list. |
| 2158 | Ops.clear(); |
| 2159 | if (AccumulatedConstant != 0) |
| 2160 | Ops.push_back(getConstant(AccumulatedConstant)); |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2161 | for (auto &MulOp : MulOpLists) |
| 2162 | if (MulOp.first != 0) |
| 2163 | Ops.push_back(getMulExpr(getConstant(MulOp.first), |
| 2164 | getAddExpr(MulOp.second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2165 | if (Ops.empty()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2166 | return getZero(Ty); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2167 | if (Ops.size() == 1) |
| 2168 | return Ops[0]; |
| 2169 | return getAddExpr(Ops); |
| 2170 | } |
| 2171 | } |
| 2172 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2173 | // If we are adding something to a multiply expression, make sure the |
| 2174 | // something is not already an operand of the multiply. If so, merge it into |
| 2175 | // the multiply. |
| 2176 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2177 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2178 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2179 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2180 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2181 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2182 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2183 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2184 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2185 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2186 | if (Mul->getNumOperands() != 2) { |
| 2187 | // If the multiply has more than two operands, we must get the |
| 2188 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2189 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2190 | Mul->op_begin()+MulOp); |
| 2191 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2192 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2193 | } |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2194 | const SCEV *One = getOne(Ty); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2195 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2196 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2197 | if (Ops.size() == 2) return OuterMul; |
| 2198 | if (AddOp < Idx) { |
| 2199 | Ops.erase(Ops.begin()+AddOp); |
| 2200 | Ops.erase(Ops.begin()+Idx-1); |
| 2201 | } else { |
| 2202 | Ops.erase(Ops.begin()+Idx); |
| 2203 | Ops.erase(Ops.begin()+AddOp-1); |
| 2204 | } |
| 2205 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2206 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2207 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2208 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2209 | // Check this multiply against other multiplies being added together. |
| 2210 | for (unsigned OtherMulIdx = Idx+1; |
| 2211 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2212 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2213 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2214 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2215 | // together. |
| 2216 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2217 | OMulOp != e; ++OMulOp) |
| 2218 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2219 | // 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] | 2220 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2221 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2222 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2223 | Mul->op_begin()+MulOp); |
| 2224 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2225 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2226 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2227 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2228 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2229 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2230 | OtherMul->op_begin()+OMulOp); |
| 2231 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2232 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2233 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2234 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2235 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2236 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2237 | Ops.erase(Ops.begin()+Idx); |
| 2238 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2239 | Ops.push_back(OuterMul); |
| 2240 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2241 | } |
| 2242 | } |
| 2243 | } |
| 2244 | } |
| 2245 | |
| 2246 | // If there are any add recurrences in the operands list, see if any other |
| 2247 | // added values are loop invariant. If so, we can fold them into the |
| 2248 | // recurrence. |
| 2249 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2250 | ++Idx; |
| 2251 | |
| 2252 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2253 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2254 | // Scan all of the other operands to this add and add them to the vector if |
| 2255 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2256 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2257 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2258 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2259 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2260 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2261 | LIOps.push_back(Ops[i]); |
| 2262 | Ops.erase(Ops.begin()+i); |
| 2263 | --i; --e; |
| 2264 | } |
| 2265 | |
| 2266 | // If we found some loop invariants, fold them into the recurrence. |
| 2267 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2268 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2269 | LIOps.push_back(AddRec->getStart()); |
| 2270 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2271 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2272 | AddRec->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2273 | AddRecOps[0] = getAddExpr(LIOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2274 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2275 | // 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] | 2276 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2277 | // Always propagate NW. |
| 2278 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2279 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2280 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2281 | // If all of the other operands were loop invariant, we are done. |
| 2282 | if (Ops.size() == 1) return NewRec; |
| 2283 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2284 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2285 | for (unsigned i = 0;; ++i) |
| 2286 | if (Ops[i] == AddRec) { |
| 2287 | Ops[i] = NewRec; |
| 2288 | break; |
| 2289 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2290 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2291 | } |
| 2292 | |
| 2293 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2294 | // there are multiple AddRec's with the same loop induction variable being |
| 2295 | // added together. If so, we can fold them. |
| 2296 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2297 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2298 | ++OtherIdx) |
| 2299 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2300 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2301 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2302 | AddRec->op_end()); |
| 2303 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2304 | ++OtherIdx) |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2305 | if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2306 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2307 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2308 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2309 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2310 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2311 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2312 | break; |
| 2313 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2314 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2315 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2316 | } |
| 2317 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2318 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2319 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2320 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2321 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2322 | } |
| 2323 | |
| 2324 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2325 | // next one. |
| 2326 | } |
| 2327 | |
| 2328 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2329 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2330 | FoldingSetNodeID ID; |
| 2331 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2332 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2333 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2334 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2335 | SCEVAddExpr *S = |
| 2336 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2337 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2338 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2339 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2340 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2341 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2342 | UniqueSCEVs.InsertNode(S, IP); |
| 2343 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2344 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2345 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2346 | } |
| 2347 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2348 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2349 | uint64_t k = i*j; |
| 2350 | if (j > 1 && k / j != i) Overflow = true; |
| 2351 | return k; |
| 2352 | } |
| 2353 | |
| 2354 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2355 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2356 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2357 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2358 | // We use the multiplicative formula: |
| 2359 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2360 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2361 | // (k-n)th term of the denominator. This division will always produce an |
| 2362 | // integral result, and helps reduce the chance of overflow in the |
| 2363 | // intermediate computations. However, we can still overflow even when the |
| 2364 | // final result would fit. |
| 2365 | |
| 2366 | if (n == 0 || n == k) return 1; |
| 2367 | if (k > n) return 0; |
| 2368 | |
| 2369 | if (k > n/2) |
| 2370 | k = n-k; |
| 2371 | |
| 2372 | uint64_t r = 1; |
| 2373 | for (uint64_t i = 1; i <= k; ++i) { |
| 2374 | r = umul_ov(r, n-(i-1), Overflow); |
| 2375 | r /= i; |
| 2376 | } |
| 2377 | return r; |
| 2378 | } |
| 2379 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2380 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2381 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2382 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2383 | SmallVector<const SCEV *, 4> Ops; |
| 2384 | Ops.push_back(StartExpr); |
| 2385 | while (!Ops.empty()) { |
| 2386 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2387 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2388 | return true; |
| 2389 | |
| 2390 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2391 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2392 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2393 | } |
| 2394 | } |
| 2395 | return false; |
| 2396 | } |
| 2397 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2398 | /// getMulExpr - Get a canonical multiply expression, or something simpler if |
| 2399 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2400 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2401 | SCEV::NoWrapFlags Flags) { |
| 2402 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2403 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2404 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2405 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2406 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2407 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2408 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2409 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2410 | "SCEVMulExpr operand types don't match!"); |
| 2411 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2412 | |
| 2413 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2414 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2415 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2416 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
| 2417 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2418 | // If there are any constants, fold them together. |
| 2419 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2420 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2421 | |
| 2422 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2423 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2424 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2425 | // If any of Add's ops are Adds or Muls with a constant, |
| 2426 | // apply this transformation as well. |
| 2427 | if (Add->getNumOperands() == 2) |
| 2428 | if (containsConstantSomewhere(Add)) |
| 2429 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2430 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2431 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2432 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2433 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2434 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2435 | ConstantInt *Fold = |
| 2436 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2437 | Ops[0] = getConstant(Fold); |
| 2438 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2439 | if (Ops.size() == 1) return Ops[0]; |
| 2440 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2441 | } |
| 2442 | |
| 2443 | // If we are left with a constant one being multiplied, strip it off. |
| 2444 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2445 | Ops.erase(Ops.begin()); |
| 2446 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2447 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2448 | // If we have a multiply of zero, it will always be zero. |
| 2449 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2450 | } else if (Ops[0]->isAllOnesValue()) { |
| 2451 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2452 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2453 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2454 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2455 | SmallVector<const SCEV *, 4> NewOps; |
| 2456 | bool AnyFolded = false; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2457 | for (const SCEV *AddOp : Add->operands()) { |
| 2458 | const SCEV *Mul = getMulExpr(Ops[0], AddOp); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2459 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2460 | NewOps.push_back(Mul); |
| 2461 | } |
| 2462 | if (AnyFolded) |
| 2463 | return getAddExpr(NewOps); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2464 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2465 | // Negation preserves a recurrence's no self-wrap property. |
| 2466 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2467 | for (const SCEV *AddRecOp : AddRec->operands()) |
| 2468 | Operands.push_back(getMulExpr(Ops[0], AddRecOp)); |
| 2469 | |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2470 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2471 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2472 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2473 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2474 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2475 | |
| 2476 | if (Ops.size() == 1) |
| 2477 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2478 | } |
| 2479 | |
| 2480 | // Skip over the add expression until we get to a multiply. |
| 2481 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2482 | ++Idx; |
| 2483 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2484 | // If there are mul operands inline them all into this expression. |
| 2485 | if (Idx < Ops.size()) { |
| 2486 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2487 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2488 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2489 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2490 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2491 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2492 | DeletedMul = true; |
| 2493 | } |
| 2494 | |
| 2495 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2496 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2497 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2498 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2499 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2500 | } |
| 2501 | |
| 2502 | // If there are any add recurrences in the operands list, see if any other |
| 2503 | // added values are loop invariant. If so, we can fold them into the |
| 2504 | // recurrence. |
| 2505 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2506 | ++Idx; |
| 2507 | |
| 2508 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2509 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2510 | // Scan all of the other operands to this mul and add them to the vector if |
| 2511 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2512 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2513 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2514 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2515 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2516 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2517 | LIOps.push_back(Ops[i]); |
| 2518 | Ops.erase(Ops.begin()+i); |
| 2519 | --i; --e; |
| 2520 | } |
| 2521 | |
| 2522 | // If we found some loop invariants, fold them into the recurrence. |
| 2523 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2524 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2525 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2526 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2527 | const SCEV *Scale = getMulExpr(LIOps); |
| 2528 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2529 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2530 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2531 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2532 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2533 | // |
| 2534 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2535 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2536 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2537 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2538 | |
| 2539 | // If all of the other operands were loop invariant, we are done. |
| 2540 | if (Ops.size() == 1) return NewRec; |
| 2541 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2542 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2543 | for (unsigned i = 0;; ++i) |
| 2544 | if (Ops[i] == AddRec) { |
| 2545 | Ops[i] = NewRec; |
| 2546 | break; |
| 2547 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2548 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2549 | } |
| 2550 | |
| 2551 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2552 | // there are multiple AddRec's with the same loop induction variable being |
| 2553 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2554 | |
| 2555 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2556 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2557 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2558 | // ]]],+,...up to x=2n}. |
| 2559 | // Note that the arguments to choose() are always integers with values |
| 2560 | // known at compile time, never SCEV objects. |
| 2561 | // |
| 2562 | // The implementation avoids pointless extra computations when the two |
| 2563 | // addrec's are of different length (mathematically, it's equivalent to |
| 2564 | // an infinite stream of zeros on the right). |
| 2565 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2566 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2567 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2568 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2569 | const SCEVAddRecExpr *OtherAddRec = |
| 2570 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2571 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2572 | continue; |
| 2573 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2574 | bool Overflow = false; |
| 2575 | Type *Ty = AddRec->getType(); |
| 2576 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2577 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2578 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2579 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2580 | const SCEV *Term = getZero(Ty); |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2581 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2582 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2583 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2584 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2585 | z < ze && !Overflow; ++z) { |
| 2586 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2587 | uint64_t Coeff; |
| 2588 | if (LargerThan64Bits) |
| 2589 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2590 | else |
| 2591 | Coeff = Coeff1*Coeff2; |
| 2592 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2593 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2594 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2595 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2596 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2597 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2598 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2599 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2600 | if (!Overflow) { |
| 2601 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2602 | SCEV::FlagAnyWrap); |
| 2603 | if (Ops.size() == 2) return NewAddRec; |
| 2604 | Ops[Idx] = NewAddRec; |
| 2605 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2606 | OpsModified = true; |
| 2607 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2608 | if (!AddRec) |
| 2609 | break; |
| 2610 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2611 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2612 | if (OpsModified) |
| 2613 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2614 | |
| 2615 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2616 | // next one. |
| 2617 | } |
| 2618 | |
| 2619 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2620 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2621 | FoldingSetNodeID ID; |
| 2622 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2623 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2624 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2625 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2626 | SCEVMulExpr *S = |
| 2627 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2628 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2629 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2630 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2631 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2632 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2633 | UniqueSCEVs.InsertNode(S, IP); |
| 2634 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2635 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2636 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2637 | } |
| 2638 | |
Andreas Bolka | 7a5c8db | 2009-08-07 22:55:26 +0000 | [diff] [blame] | 2639 | /// getUDivExpr - Get a canonical unsigned division expression, or something |
| 2640 | /// simpler if possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2641 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2642 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2643 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2644 | getEffectiveSCEVType(RHS->getType()) && |
| 2645 | "SCEVUDivExpr operand types don't match!"); |
| 2646 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2647 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2648 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2649 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2650 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2651 | // try to analyze it, because the resolution chosen here may differ from |
| 2652 | // the resolution chosen in other parts of the compiler. |
| 2653 | if (!RHSC->getValue()->isZero()) { |
| 2654 | // Determine if the division can be folded into the operands of |
| 2655 | // its operands. |
| 2656 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2657 | Type *Ty = LHS->getType(); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2658 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2659 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2660 | // For non-power-of-two values, effectively round the value up to the |
| 2661 | // nearest power of two. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2662 | if (!RHSC->getAPInt().isPowerOf2()) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2663 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2664 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2665 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2666 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2667 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2668 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2669 | // {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] | 2670 | const APInt &StepInt = Step->getAPInt(); |
| 2671 | const APInt &DivInt = RHSC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2672 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2673 | getZeroExtendExpr(AR, ExtTy) == |
| 2674 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2675 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2676 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2677 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2678 | for (const SCEV *Op : AR->operands()) |
| 2679 | Operands.push_back(getUDivExpr(Op, RHS)); |
| 2680 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2681 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2682 | /// Get a canonical UDivExpr for a recurrence. |
| 2683 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2684 | // We can currently only fold X%N if X is constant. |
| 2685 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2686 | if (StartC && !DivInt.urem(StepInt) && |
| 2687 | getZeroExtendExpr(AR, ExtTy) == |
| 2688 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2689 | getZeroExtendExpr(Step, ExtTy), |
| 2690 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2691 | const APInt &StartInt = StartC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2692 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2693 | if (StartRem != 0) |
| 2694 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2695 | AR->getLoop(), SCEV::FlagNW); |
| 2696 | } |
| 2697 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2698 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2699 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2700 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2701 | for (const SCEV *Op : M->operands()) |
| 2702 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2703 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2704 | // Find an operand that's safely divisible. |
| 2705 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2706 | const SCEV *Op = M->getOperand(i); |
| 2707 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2708 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2709 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2710 | M->op_end()); |
| 2711 | Operands[i] = Div; |
| 2712 | return getMulExpr(Operands); |
| 2713 | } |
| 2714 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2715 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2716 | // (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] | 2717 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2718 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2719 | for (const SCEV *Op : A->operands()) |
| 2720 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2721 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2722 | Operands.clear(); |
| 2723 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2724 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2725 | if (isa<SCEVUDivExpr>(Op) || |
| 2726 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2727 | break; |
| 2728 | Operands.push_back(Op); |
| 2729 | } |
| 2730 | if (Operands.size() == A->getNumOperands()) |
| 2731 | return getAddExpr(Operands); |
| 2732 | } |
| 2733 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2734 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2735 | // Fold if both operands are constant. |
| 2736 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2737 | Constant *LHSCV = LHSC->getValue(); |
| 2738 | Constant *RHSCV = RHSC->getValue(); |
| 2739 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2740 | RHSCV))); |
| 2741 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2742 | } |
| 2743 | } |
| 2744 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2745 | FoldingSetNodeID ID; |
| 2746 | ID.AddInteger(scUDivExpr); |
| 2747 | ID.AddPointer(LHS); |
| 2748 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2749 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2750 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2751 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2752 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2753 | UniqueSCEVs.InsertNode(S, IP); |
| 2754 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2755 | } |
| 2756 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2757 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2758 | APInt A = C1->getAPInt().abs(); |
| 2759 | APInt B = C2->getAPInt().abs(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2760 | uint32_t ABW = A.getBitWidth(); |
| 2761 | uint32_t BBW = B.getBitWidth(); |
| 2762 | |
| 2763 | if (ABW > BBW) |
| 2764 | B = B.zext(ABW); |
| 2765 | else if (ABW < BBW) |
| 2766 | A = A.zext(BBW); |
| 2767 | |
| 2768 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2769 | } |
| 2770 | |
| 2771 | /// getUDivExactExpr - Get a canonical unsigned division expression, or |
| 2772 | /// something simpler if possible. There is no representation for an exact udiv |
| 2773 | /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS. |
| 2774 | /// We can't do this when it's not exact because the udiv may be clearing bits. |
| 2775 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2776 | const SCEV *RHS) { |
| 2777 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2778 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2779 | // end of this file for inspiration. |
| 2780 | |
| 2781 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2782 | if (!Mul) |
| 2783 | return getUDivExpr(LHS, RHS); |
| 2784 | |
| 2785 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2786 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2787 | // first element of the mulexpr. |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2788 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2789 | if (LHSCst == RHSCst) { |
| 2790 | SmallVector<const SCEV *, 2> Operands; |
| 2791 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2792 | return getMulExpr(Operands); |
| 2793 | } |
| 2794 | |
| 2795 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2796 | // that there's a factor provided by one of the other terms. We need to |
| 2797 | // check. |
| 2798 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2799 | if (!Factor.isIntN(1)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2800 | LHSCst = |
| 2801 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); |
| 2802 | RHSCst = |
| 2803 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2804 | SmallVector<const SCEV *, 2> Operands; |
| 2805 | Operands.push_back(LHSCst); |
| 2806 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2807 | LHS = getMulExpr(Operands); |
| 2808 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2809 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2810 | if (!Mul) |
| 2811 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2812 | } |
| 2813 | } |
| 2814 | } |
| 2815 | |
| 2816 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2817 | if (Mul->getOperand(i) == RHS) { |
| 2818 | SmallVector<const SCEV *, 2> Operands; |
| 2819 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2820 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2821 | return getMulExpr(Operands); |
| 2822 | } |
| 2823 | } |
| 2824 | |
| 2825 | return getUDivExpr(LHS, RHS); |
| 2826 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2827 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2828 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2829 | /// Simplify the expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2830 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2831 | const Loop *L, |
| 2832 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2833 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2834 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2835 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2836 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2837 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2838 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2839 | } |
| 2840 | |
| 2841 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2842 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2843 | } |
| 2844 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2845 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2846 | /// Simplify the expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2847 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2848 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2849 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2850 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2851 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2852 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2853 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2854 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2855 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2856 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2857 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2858 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2859 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2860 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2861 | if (Operands.back()->isZero()) { |
| 2862 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2863 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2864 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2865 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2866 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2867 | // use that information to infer NUW and NSW flags. However, computing a |
| 2868 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2869 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2870 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2871 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2872 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2873 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2874 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2875 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2876 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2877 | if (L->contains(NestedLoop) |
| 2878 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2879 | : (!NestedLoop->contains(L) && |
| 2880 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2881 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2882 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2883 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2884 | // AddRecs require their operands be loop-invariant with respect to their |
| 2885 | // loops. Don't perform this transformation if it would break this |
| 2886 | // requirement. |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2887 | bool AllInvariant = all_of( |
| 2888 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2889 | |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2890 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2891 | // Create a recurrence for the outer loop with the same step size. |
| 2892 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2893 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 2894 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2895 | SCEV::NoWrapFlags OuterFlags = |
| 2896 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2897 | |
| 2898 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2899 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { |
| 2900 | return isLoopInvariant(Op, NestedLoop); |
| 2901 | }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2902 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2903 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2904 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2905 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2906 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 2907 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2908 | SCEV::NoWrapFlags InnerFlags = |
| 2909 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2910 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 2911 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2912 | } |
| 2913 | // Reset Operands to its original state. |
| 2914 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2915 | } |
| 2916 | } |
| 2917 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 2918 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 2919 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2920 | FoldingSetNodeID ID; |
| 2921 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2922 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 2923 | ID.AddPointer(Operands[i]); |
| 2924 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2925 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2926 | SCEVAddRecExpr *S = |
| 2927 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2928 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2929 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 2930 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2931 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 2932 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2933 | UniqueSCEVs.InsertNode(S, IP); |
| 2934 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2935 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2936 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2937 | } |
| 2938 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2939 | const SCEV * |
| 2940 | ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, |
| 2941 | const SmallVectorImpl<const SCEV *> &IndexExprs, |
| 2942 | bool InBounds) { |
| 2943 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 2944 | // because SCEV::getType() preserves the address space. |
| 2945 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 2946 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 2947 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 2948 | // 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] | 2949 | // context. This can be fixed similarly to how these flags are handled for |
| 2950 | // adds. |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2951 | SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 2952 | |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2953 | const SCEV *TotalOffset = getZero(IntPtrTy); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2954 | // The address space is unimportant. The first thing we do on CurTy is getting |
| 2955 | // its element type. |
| 2956 | Type *CurTy = PointerType::getUnqual(PointeeType); |
| 2957 | for (const SCEV *IndexExpr : IndexExprs) { |
| 2958 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 2959 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 2960 | // For a struct, add the member offset. |
| 2961 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 2962 | unsigned FieldNo = Index->getZExtValue(); |
| 2963 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 2964 | |
| 2965 | // Add the field offset to the running total offset. |
| 2966 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 2967 | |
| 2968 | // Update CurTy to the type of the field at Index. |
| 2969 | CurTy = STy->getTypeAtIndex(Index); |
| 2970 | } else { |
| 2971 | // Update CurTy to its element type. |
| 2972 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 2973 | // For an array, add the element offset, explicitly scaled. |
| 2974 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 2975 | // Getelementptr indices are signed. |
| 2976 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 2977 | |
| 2978 | // Multiply the index by the element size to compute the element offset. |
| 2979 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 2980 | |
| 2981 | // Add the element offset to the running total offset. |
| 2982 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 2983 | } |
| 2984 | } |
| 2985 | |
| 2986 | // Add the total offset from all the GEP indices to the base. |
| 2987 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 2988 | } |
| 2989 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2990 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 2991 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2992 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2993 | Ops.push_back(LHS); |
| 2994 | Ops.push_back(RHS); |
| 2995 | return getSMaxExpr(Ops); |
| 2996 | } |
| 2997 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2998 | const SCEV * |
| 2999 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3000 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 3001 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3002 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3003 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3004 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3005 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3006 | "SCEVSMaxExpr operand types don't match!"); |
| 3007 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3008 | |
| 3009 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3010 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3011 | |
| 3012 | // If there are any constants, fold them together. |
| 3013 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3014 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3015 | ++Idx; |
| 3016 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3017 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3018 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3019 | ConstantInt *Fold = ConstantInt::get( |
| 3020 | getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3021 | Ops[0] = getConstant(Fold); |
| 3022 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3023 | if (Ops.size() == 1) return Ops[0]; |
| 3024 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3025 | } |
| 3026 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3027 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3028 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3029 | Ops.erase(Ops.begin()); |
| 3030 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3031 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3032 | // If we have an smax with a constant maximum-int, it will always be |
| 3033 | // maximum-int. |
| 3034 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3035 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3036 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3037 | if (Ops.size() == 1) return Ops[0]; |
| 3038 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3039 | |
| 3040 | // Find the first SMax |
| 3041 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3042 | ++Idx; |
| 3043 | |
| 3044 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3045 | // onto our operand list, and recurse to simplify. |
| 3046 | if (Idx < Ops.size()) { |
| 3047 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3048 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3049 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3050 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3051 | DeletedSMax = true; |
| 3052 | } |
| 3053 | |
| 3054 | if (DeletedSMax) |
| 3055 | return getSMaxExpr(Ops); |
| 3056 | } |
| 3057 | |
| 3058 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3059 | // so, delete one. Since we sorted the list, these values are required to |
| 3060 | // be adjacent. |
| 3061 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3062 | // X smax Y smax Y --> X smax Y |
| 3063 | // X smax Y --> X, if X is always greater than Y |
| 3064 | if (Ops[i] == Ops[i+1] || |
| 3065 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3066 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3067 | --i; --e; |
| 3068 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3069 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3070 | --i; --e; |
| 3071 | } |
| 3072 | |
| 3073 | if (Ops.size() == 1) return Ops[0]; |
| 3074 | |
| 3075 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3076 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3077 | // 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] | 3078 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3079 | FoldingSetNodeID ID; |
| 3080 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3081 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3082 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3083 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3084 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3085 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3086 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3087 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3088 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3089 | UniqueSCEVs.InsertNode(S, IP); |
| 3090 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3091 | } |
| 3092 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3093 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3094 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3095 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3096 | Ops.push_back(LHS); |
| 3097 | Ops.push_back(RHS); |
| 3098 | return getUMaxExpr(Ops); |
| 3099 | } |
| 3100 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3101 | const SCEV * |
| 3102 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3103 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3104 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3105 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3106 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3107 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3108 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3109 | "SCEVUMaxExpr operand types don't match!"); |
| 3110 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3111 | |
| 3112 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3113 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3114 | |
| 3115 | // If there are any constants, fold them together. |
| 3116 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3117 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3118 | ++Idx; |
| 3119 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3120 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3121 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3122 | ConstantInt *Fold = ConstantInt::get( |
| 3123 | getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3124 | Ops[0] = getConstant(Fold); |
| 3125 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3126 | if (Ops.size() == 1) return Ops[0]; |
| 3127 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3128 | } |
| 3129 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3130 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3131 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3132 | Ops.erase(Ops.begin()); |
| 3133 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3134 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3135 | // If we have an umax with a constant maximum-int, it will always be |
| 3136 | // maximum-int. |
| 3137 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3138 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3139 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3140 | if (Ops.size() == 1) return Ops[0]; |
| 3141 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3142 | |
| 3143 | // Find the first UMax |
| 3144 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3145 | ++Idx; |
| 3146 | |
| 3147 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3148 | // onto our operand list, and recurse to simplify. |
| 3149 | if (Idx < Ops.size()) { |
| 3150 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3151 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3152 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3153 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3154 | DeletedUMax = true; |
| 3155 | } |
| 3156 | |
| 3157 | if (DeletedUMax) |
| 3158 | return getUMaxExpr(Ops); |
| 3159 | } |
| 3160 | |
| 3161 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3162 | // so, delete one. Since we sorted the list, these values are required to |
| 3163 | // be adjacent. |
| 3164 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3165 | // X umax Y umax Y --> X umax Y |
| 3166 | // X umax Y --> X, if X is always greater than Y |
| 3167 | if (Ops[i] == Ops[i+1] || |
| 3168 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3169 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3170 | --i; --e; |
| 3171 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3172 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3173 | --i; --e; |
| 3174 | } |
| 3175 | |
| 3176 | if (Ops.size() == 1) return Ops[0]; |
| 3177 | |
| 3178 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3179 | |
| 3180 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3181 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3182 | FoldingSetNodeID ID; |
| 3183 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3184 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3185 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3186 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3187 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3188 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3189 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3190 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3191 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3192 | UniqueSCEVs.InsertNode(S, IP); |
| 3193 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3194 | } |
| 3195 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3196 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3197 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3198 | // ~smax(~x, ~y) == smin(x, y). |
| 3199 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3200 | } |
| 3201 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3202 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3203 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3204 | // ~umax(~x, ~y) == umin(x, y) |
| 3205 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3206 | } |
| 3207 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3208 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3209 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3210 | // constant expression and then folding it back into a ConstantInt. |
| 3211 | // This is just a compile-time optimization. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3212 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3213 | } |
| 3214 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3215 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3216 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3217 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3218 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3219 | // constant expression and then folding it back into a ConstantInt. |
| 3220 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3221 | return getConstant( |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3222 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3223 | } |
| 3224 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3225 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3226 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3227 | // here. createSCEV only calls getUnknown after checking for all other |
| 3228 | // interesting possibilities, and any other code that calls getUnknown |
| 3229 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3230 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3231 | FoldingSetNodeID ID; |
| 3232 | ID.AddInteger(scUnknown); |
| 3233 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3234 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3235 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3236 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3237 | "Stale SCEVUnknown in uniquing map!"); |
| 3238 | return S; |
| 3239 | } |
| 3240 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3241 | FirstUnknown); |
| 3242 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3243 | UniqueSCEVs.InsertNode(S, IP); |
| 3244 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3245 | } |
| 3246 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3247 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3248 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3249 | // |
| 3250 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3251 | /// isSCEVable - Test if values of the given type are analyzable within |
| 3252 | /// the SCEV framework. This primarily includes integer types, and it |
| 3253 | /// can optionally include pointer types if the ScalarEvolution class |
| 3254 | /// has access to target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3255 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3256 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3257 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3258 | } |
| 3259 | |
| 3260 | /// getTypeSizeInBits - Return the size in bits of the specified type, |
| 3261 | /// for which isSCEVable must return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3262 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3263 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3264 | return getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3265 | } |
| 3266 | |
| 3267 | /// getEffectiveSCEVType - Return a type with the same bitwidth as |
| 3268 | /// the given type and which represents how SCEV will treat the given |
| 3269 | /// type, for which isSCEVable must return true. For pointer types, |
| 3270 | /// this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3271 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3272 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3273 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3274 | if (Ty->isIntegerTy()) |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3275 | return Ty; |
| 3276 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3277 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3278 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3279 | return getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3280 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3281 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3282 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3283 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3284 | } |
| 3285 | |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 3286 | |
| 3287 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3288 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3289 | // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne |
| 3290 | // is set iff if find such SCEVUnknown. |
| 3291 | // |
| 3292 | struct FindInvalidSCEVUnknown { |
| 3293 | bool FindOne; |
| 3294 | FindInvalidSCEVUnknown() { FindOne = false; } |
| 3295 | bool follow(const SCEV *S) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 3296 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3297 | case scConstant: |
| 3298 | return false; |
| 3299 | case scUnknown: |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3300 | if (!cast<SCEVUnknown>(S)->getValue()) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3301 | FindOne = true; |
| 3302 | return false; |
| 3303 | default: |
| 3304 | return true; |
| 3305 | } |
| 3306 | } |
| 3307 | bool isDone() const { return FindOne; } |
| 3308 | }; |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3309 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3310 | FindInvalidSCEVUnknown F; |
| 3311 | SCEVTraversal<FindInvalidSCEVUnknown> ST(F); |
| 3312 | ST.visitAll(S); |
| 3313 | |
| 3314 | return !F.FindOne; |
| 3315 | } |
| 3316 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3317 | namespace { |
| 3318 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3319 | // a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set |
| 3320 | // iff if such sub scAddRecExpr type SCEV is found. |
| 3321 | struct FindAddRecurrence { |
| 3322 | bool FoundOne; |
| 3323 | FindAddRecurrence() : FoundOne(false) {} |
| 3324 | |
| 3325 | bool follow(const SCEV *S) { |
| 3326 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
| 3327 | case scAddRecExpr: |
| 3328 | FoundOne = true; |
| 3329 | case scConstant: |
| 3330 | case scUnknown: |
| 3331 | case scCouldNotCompute: |
| 3332 | return false; |
| 3333 | default: |
| 3334 | return true; |
| 3335 | } |
| 3336 | } |
| 3337 | bool isDone() const { return FoundOne; } |
| 3338 | }; |
| 3339 | } |
| 3340 | |
| 3341 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { |
| 3342 | HasRecMapType::iterator I = HasRecMap.find_as(S); |
| 3343 | if (I != HasRecMap.end()) |
| 3344 | return I->second; |
| 3345 | |
| 3346 | FindAddRecurrence F; |
| 3347 | SCEVTraversal<FindAddRecurrence> ST(F); |
| 3348 | ST.visitAll(S); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3349 | HasRecMap.insert({S, F.FoundOne}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3350 | return F.FoundOne; |
| 3351 | } |
| 3352 | |
| 3353 | /// getSCEVValues - Return the Value set from S. |
| 3354 | SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) { |
| 3355 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); |
| 3356 | if (SI == ExprValueMap.end()) |
| 3357 | return nullptr; |
| 3358 | #ifndef NDEBUG |
| 3359 | if (VerifySCEVMap) { |
| 3360 | // Check there is no dangling Value in the set returned. |
| 3361 | for (const auto &VE : SI->second) |
| 3362 | assert(ValueExprMap.count(VE)); |
| 3363 | } |
| 3364 | #endif |
| 3365 | return &SI->second; |
| 3366 | } |
| 3367 | |
| 3368 | /// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap. |
| 3369 | /// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S), |
| 3370 | /// eraseValueFromMap should be used instead to ensure whenever V->S is removed |
| 3371 | /// from ValueExprMap, V is also removed from the set of ExprValueMap[S]. |
| 3372 | void ScalarEvolution::eraseValueFromMap(Value *V) { |
| 3373 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3374 | if (I != ValueExprMap.end()) { |
| 3375 | const SCEV *S = I->second; |
| 3376 | SetVector<Value *> *SV = getSCEVValues(S); |
| 3377 | // Remove V from the set of ExprValueMap[S] |
| 3378 | if (SV) |
| 3379 | SV->remove(V); |
| 3380 | ValueExprMap.erase(V); |
| 3381 | } |
| 3382 | } |
| 3383 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3384 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 3385 | /// expression and create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3386 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3387 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3388 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3389 | const SCEV *S = getExistingSCEV(V); |
| 3390 | if (S == nullptr) { |
| 3391 | S = createSCEV(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3392 | // During PHI resolution, it is possible to create two SCEVs for the same |
| 3393 | // V, so it is needed to double check whether V->S is inserted into |
| 3394 | // ValueExprMap before insert S->V into ExprValueMap. |
| 3395 | std::pair<ValueExprMapType::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3396 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3397 | if (Pair.second) |
| 3398 | ExprValueMap[S].insert(V); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3399 | } |
| 3400 | return S; |
| 3401 | } |
| 3402 | |
| 3403 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3404 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3405 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3406 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3407 | if (I != ValueExprMap.end()) { |
| 3408 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3409 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3410 | return S; |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3411 | forgetMemoizedResults(S); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3412 | ValueExprMap.erase(I); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3413 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3414 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3415 | } |
| 3416 | |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3417 | /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V |
| 3418 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3419 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3420 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3421 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3422 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3423 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3424 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3425 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3426 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3427 | return getMulExpr( |
| 3428 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3429 | } |
| 3430 | |
| 3431 | /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3432 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3433 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3434 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3435 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3436 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3437 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3438 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3439 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3440 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3441 | return getMinusSCEV(AllOnes, V); |
| 3442 | } |
| 3443 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3444 | /// 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] | 3445 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3446 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3447 | // Fast path: X - X --> 0. |
| 3448 | if (LHS == RHS) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3449 | return getZero(LHS->getType()); |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3450 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3451 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3452 | // makes it so that we cannot make much use of NUW. |
| 3453 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3454 | const bool RHSIsNotMinSigned = |
| 3455 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3456 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3457 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3458 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3459 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3460 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3461 | // (-1)*RHS, we need to prove that RHS != M. |
| 3462 | // |
| 3463 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3464 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3465 | // either by proving that RHS > M or that LHS >= 0. |
| 3466 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3467 | AddFlags = SCEV::FlagNSW; |
| 3468 | } |
| 3469 | } |
| 3470 | |
| 3471 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3472 | // RHS is NSW and LHS >= 0. |
| 3473 | // |
| 3474 | // The difficulty here is that the NSW flag may have been proven |
| 3475 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3476 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3477 | // larger scope than intended. |
| 3478 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3479 | |
| 3480 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3481 | } |
| 3482 | |
| 3483 | /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3484 | /// input value to the specified type. If the type must be extended, it is zero |
| 3485 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3486 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3487 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3488 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3489 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3490 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3491 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3492 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3493 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3494 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3495 | return getTruncateExpr(V, Ty); |
| 3496 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3497 | } |
| 3498 | |
| 3499 | /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3500 | /// input value to the specified type. If the type must be extended, it is sign |
| 3501 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3502 | const SCEV * |
| 3503 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3504 | Type *Ty) { |
| 3505 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3506 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3507 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3508 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3509 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3510 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3511 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3512 | return getTruncateExpr(V, Ty); |
| 3513 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3514 | } |
| 3515 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3516 | /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3517 | /// input value to the specified type. If the type must be extended, it is zero |
| 3518 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3519 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3520 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3521 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3522 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3523 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3524 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3525 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3526 | "getNoopOrZeroExtend cannot truncate!"); |
| 3527 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3528 | return V; // No conversion |
| 3529 | return getZeroExtendExpr(V, Ty); |
| 3530 | } |
| 3531 | |
| 3532 | /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3533 | /// input value to the specified type. If the type must be extended, it is sign |
| 3534 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3535 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3536 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3537 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3538 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3539 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3540 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3541 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3542 | "getNoopOrSignExtend cannot truncate!"); |
| 3543 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3544 | return V; // No conversion |
| 3545 | return getSignExtendExpr(V, Ty); |
| 3546 | } |
| 3547 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3548 | /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of |
| 3549 | /// the input value to the specified type. If the type must be extended, |
| 3550 | /// it is extended with unspecified bits. The conversion must not be |
| 3551 | /// narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3552 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3553 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3554 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3555 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3556 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3557 | "Cannot noop or any extend with non-integer arguments!"); |
| 3558 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3559 | "getNoopOrAnyExtend cannot truncate!"); |
| 3560 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3561 | return V; // No conversion |
| 3562 | return getAnyExtendExpr(V, Ty); |
| 3563 | } |
| 3564 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3565 | /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the |
| 3566 | /// input value to the specified type. The conversion must not be widening. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3567 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3568 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3569 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3570 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3571 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3572 | "Cannot truncate or noop with non-integer arguments!"); |
| 3573 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3574 | "getTruncateOrNoop cannot extend!"); |
| 3575 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3576 | return V; // No conversion |
| 3577 | return getTruncateExpr(V, Ty); |
| 3578 | } |
| 3579 | |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3580 | /// getUMaxFromMismatchedTypes - Promote the operands to the wider of |
| 3581 | /// the types using zero-extension, and then perform a umax operation |
| 3582 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3583 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3584 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3585 | const SCEV *PromotedLHS = LHS; |
| 3586 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3587 | |
| 3588 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3589 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3590 | else |
| 3591 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3592 | |
| 3593 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3594 | } |
| 3595 | |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3596 | /// getUMinFromMismatchedTypes - Promote the operands to the wider of |
| 3597 | /// the types using zero-extension, and then perform a umin operation |
| 3598 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3599 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3600 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3601 | const SCEV *PromotedLHS = LHS; |
| 3602 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3603 | |
| 3604 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3605 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3606 | else |
| 3607 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3608 | |
| 3609 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3610 | } |
| 3611 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3612 | /// getPointerBase - Transitively follow the chain of pointer-type operands |
| 3613 | /// until reaching a SCEV that does not have a single pointer operand. This |
| 3614 | /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, |
| 3615 | /// but corner cases do exist. |
| 3616 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { |
| 3617 | // A pointer operand may evaluate to a nonpointer expression, such as null. |
| 3618 | if (!V->getType()->isPointerTy()) |
| 3619 | return V; |
| 3620 | |
| 3621 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { |
| 3622 | return getPointerBase(Cast->getOperand()); |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3623 | } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3624 | const SCEV *PtrOp = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3625 | for (const SCEV *NAryOp : NAry->operands()) { |
| 3626 | if (NAryOp->getType()->isPointerTy()) { |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3627 | // Cannot find the base of an expression with multiple pointer operands. |
| 3628 | if (PtrOp) |
| 3629 | return V; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3630 | PtrOp = NAryOp; |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3631 | } |
| 3632 | } |
| 3633 | if (!PtrOp) |
| 3634 | return V; |
| 3635 | return getPointerBase(PtrOp); |
| 3636 | } |
| 3637 | return V; |
| 3638 | } |
| 3639 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3640 | /// PushDefUseChildren - Push users of the given Instruction |
| 3641 | /// onto the given Worklist. |
| 3642 | static void |
| 3643 | PushDefUseChildren(Instruction *I, |
| 3644 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3645 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3646 | for (User *U : I->users()) |
| 3647 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3648 | } |
| 3649 | |
| 3650 | /// ForgetSymbolicValue - This looks up computed SCEV values for all |
| 3651 | /// instructions that depend on the given instruction and removes them from |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3652 | /// the ValueExprMapType map if they reference SymName. This is used during PHI |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3653 | /// resolution. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 3654 | void |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3655 | ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3656 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3657 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3658 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3659 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3660 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3661 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3662 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3663 | if (!Visited.insert(I).second) |
| 3664 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3665 | |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 3666 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3667 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3668 | const SCEV *Old = It->second; |
| 3669 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3670 | // Short-circuit the def-use traversal if the symbolic name |
| 3671 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3672 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3673 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3674 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3675 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3676 | // structure, it's a PHI that's in the progress of being computed |
| 3677 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3678 | // additional loop trip count information isn't going to change anything. |
| 3679 | // In the second case, createNodeForPHI will perform the necessary |
| 3680 | // updates on its own when it gets to that point. In the third, we do |
| 3681 | // want to forget the SCEVUnknown. |
| 3682 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3683 | !isa<SCEVUnknown>(Old) || |
| 3684 | (I != PN && Old == SymName)) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3685 | forgetMemoizedResults(Old); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3686 | ValueExprMap.erase(It); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3687 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3688 | } |
| 3689 | |
| 3690 | PushDefUseChildren(I, Worklist); |
| 3691 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3692 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3693 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3694 | namespace { |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3695 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { |
| 3696 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3697 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3698 | ScalarEvolution &SE) { |
| 3699 | SCEVInitRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3700 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3701 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3702 | } |
| 3703 | |
| 3704 | SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) |
| 3705 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3706 | |
| 3707 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3708 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3709 | Valid = false; |
| 3710 | return Expr; |
| 3711 | } |
| 3712 | |
| 3713 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3714 | // Only allow AddRecExprs for this loop. |
| 3715 | if (Expr->getLoop() == L) |
| 3716 | return Expr->getStart(); |
| 3717 | Valid = false; |
| 3718 | return Expr; |
| 3719 | } |
| 3720 | |
| 3721 | bool isValid() { return Valid; } |
| 3722 | |
| 3723 | private: |
| 3724 | const Loop *L; |
| 3725 | bool Valid; |
| 3726 | }; |
| 3727 | |
| 3728 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { |
| 3729 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3730 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3731 | ScalarEvolution &SE) { |
| 3732 | SCEVShiftRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3733 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3734 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3735 | } |
| 3736 | |
| 3737 | SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) |
| 3738 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3739 | |
| 3740 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3741 | // Only allow AddRecExprs for this loop. |
| 3742 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3743 | Valid = false; |
| 3744 | return Expr; |
| 3745 | } |
| 3746 | |
| 3747 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3748 | if (Expr->getLoop() == L && Expr->isAffine()) |
| 3749 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); |
| 3750 | Valid = false; |
| 3751 | return Expr; |
| 3752 | } |
| 3753 | bool isValid() { return Valid; } |
| 3754 | |
| 3755 | private: |
| 3756 | const Loop *L; |
| 3757 | bool Valid; |
| 3758 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3759 | } // end anonymous namespace |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3760 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3761 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { |
| 3762 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 3763 | if (!L || L->getHeader() != PN->getParent()) |
| 3764 | return nullptr; |
| 3765 | |
| 3766 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 3767 | // this phi as an addrec if it has a unique entry value and a unique |
| 3768 | // backedge value. |
| 3769 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
| 3770 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 3771 | Value *V = PN->getIncomingValue(i); |
| 3772 | if (L->contains(PN->getIncomingBlock(i))) { |
| 3773 | if (!BEValueV) { |
| 3774 | BEValueV = V; |
| 3775 | } else if (BEValueV != V) { |
| 3776 | BEValueV = nullptr; |
| 3777 | break; |
| 3778 | } |
| 3779 | } else if (!StartValueV) { |
| 3780 | StartValueV = V; |
| 3781 | } else if (StartValueV != V) { |
| 3782 | StartValueV = nullptr; |
| 3783 | break; |
| 3784 | } |
| 3785 | } |
| 3786 | if (BEValueV && StartValueV) { |
| 3787 | // While we are analyzing this PHI node, handle its value symbolically. |
| 3788 | const SCEV *SymbolicName = getUnknown(PN); |
| 3789 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
| 3790 | "PHI node already processed?"); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3791 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3792 | |
| 3793 | // Using this symbolic name for the PHI, analyze the value coming around |
| 3794 | // the back-edge. |
| 3795 | const SCEV *BEValue = getSCEV(BEValueV); |
| 3796 | |
| 3797 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 3798 | // has a special value for the first iteration of the loop. |
| 3799 | |
| 3800 | // If the value coming around the backedge is an add with the symbolic |
| 3801 | // value we just inserted, then we found a simple induction variable! |
| 3802 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 3803 | // If there is a single occurrence of the symbolic value, replace it |
| 3804 | // with a recurrence. |
| 3805 | unsigned FoundIndex = Add->getNumOperands(); |
| 3806 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3807 | if (Add->getOperand(i) == SymbolicName) |
| 3808 | if (FoundIndex == e) { |
| 3809 | FoundIndex = i; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3810 | break; |
| 3811 | } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3812 | |
| 3813 | if (FoundIndex != Add->getNumOperands()) { |
| 3814 | // Create an add with everything but the specified operand. |
| 3815 | SmallVector<const SCEV *, 8> Ops; |
| 3816 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3817 | if (i != FoundIndex) |
| 3818 | Ops.push_back(Add->getOperand(i)); |
| 3819 | const SCEV *Accum = getAddExpr(Ops); |
| 3820 | |
| 3821 | // This is not a valid addrec if the step amount is varying each |
| 3822 | // loop iteration, but is not itself an addrec in this loop. |
| 3823 | if (isLoopInvariant(Accum, L) || |
| 3824 | (isa<SCEVAddRecExpr>(Accum) && |
| 3825 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 3826 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 3827 | |
| 3828 | // If the increment doesn't overflow, then neither the addrec nor |
| 3829 | // the post-increment will overflow. |
| 3830 | if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) { |
| 3831 | if (OBO->getOperand(0) == PN) { |
| 3832 | if (OBO->hasNoUnsignedWrap()) |
| 3833 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 3834 | if (OBO->hasNoSignedWrap()) |
| 3835 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 3836 | } |
| 3837 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
| 3838 | // If the increment is an inbounds GEP, then we know the address |
| 3839 | // space cannot be wrapped around. We cannot make any guarantee |
| 3840 | // about signed or unsigned overflow because pointers are |
| 3841 | // unsigned but we may have a negative index from the base |
| 3842 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 3843 | // indices form a positive value. |
| 3844 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
| 3845 | Flags = setFlags(Flags, SCEV::FlagNW); |
| 3846 | |
| 3847 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 3848 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 3849 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 3850 | } |
| 3851 | |
| 3852 | // We cannot transfer nuw and nsw flags from subtraction |
| 3853 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 3854 | // for instance. |
| 3855 | } |
| 3856 | |
| 3857 | const SCEV *StartVal = getSCEV(StartValueV); |
| 3858 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
| 3859 | |
| 3860 | // Since the no-wrap flags are on the increment, they apply to the |
| 3861 | // post-incremented value as well. |
| 3862 | if (isLoopInvariant(Accum, L)) |
| 3863 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); |
| 3864 | |
| 3865 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 3866 | // to be symbolic. We now need to go back and purge all of the |
| 3867 | // entries for the scalars that use the symbolic expression. |
| 3868 | ForgetSymbolicName(PN, SymbolicName); |
| 3869 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
| 3870 | return PHISCEV; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3871 | } |
| 3872 | } |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3873 | } else { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3874 | // Otherwise, this could be a loop like this: |
| 3875 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 3876 | // In this case, j = {1,+,1} and BEValue is j. |
| 3877 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 3878 | // i really is an addrec evolution. |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3879 | // |
| 3880 | // We can generalize this saying that i is the shifted value of BEValue |
| 3881 | // by one iteration: |
| 3882 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) |
| 3883 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); |
| 3884 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); |
| 3885 | if (Shifted != getCouldNotCompute() && |
| 3886 | Start != getCouldNotCompute()) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3887 | const SCEV *StartVal = getSCEV(StartValueV); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3888 | if (Start == StartVal) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3889 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 3890 | // to be symbolic. We now need to go back and purge all of the |
| 3891 | // entries for the scalars that use the symbolic expression. |
| 3892 | ForgetSymbolicName(PN, SymbolicName); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3893 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; |
| 3894 | return Shifted; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3895 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3896 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3897 | } |
Tobias Grosser | 934fcf4 | 2016-02-21 18:50:09 +0000 | [diff] [blame^] | 3898 | |
| 3899 | // Remove the temporary PHI node SCEV that has been inserted while intending |
| 3900 | // to create an AddRecExpr for this PHI node. We can not keep this temporary |
| 3901 | // as it will prevent later (possibly simpler) SCEV expressions to be added |
| 3902 | // to the ValueExprMap. |
| 3903 | ValueExprMap.erase(PN); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3904 | } |
| 3905 | |
| 3906 | return nullptr; |
| 3907 | } |
| 3908 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3909 | // Checks if the SCEV S is available at BB. S is considered available at BB |
| 3910 | // if S can be materialized at BB without introducing a fault. |
| 3911 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, |
| 3912 | BasicBlock *BB) { |
| 3913 | struct CheckAvailable { |
| 3914 | bool TraversalDone = false; |
| 3915 | bool Available = true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3916 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3917 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) |
| 3918 | BasicBlock *BB = nullptr; |
| 3919 | DominatorTree &DT; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3920 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3921 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) |
| 3922 | : L(L), BB(BB), DT(DT) {} |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3923 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3924 | bool setUnavailable() { |
| 3925 | TraversalDone = true; |
| 3926 | Available = false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3927 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3928 | } |
| 3929 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3930 | bool follow(const SCEV *S) { |
| 3931 | switch (S->getSCEVType()) { |
| 3932 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: |
| 3933 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: |
Sanjoy Das | bb5ffc5 | 2015-10-24 05:37:28 +0000 | [diff] [blame] | 3934 | // These expressions are available if their operand(s) is/are. |
| 3935 | return true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3936 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3937 | case scAddRecExpr: { |
| 3938 | // We allow add recurrences that are on the loop BB is in, or some |
| 3939 | // outer loop. This guarantees availability because the value of the |
| 3940 | // add recurrence at BB is simply the "current" value of the induction |
| 3941 | // variable. We can relax this in the future; for instance an add |
| 3942 | // recurrence on a sibling dominating loop is also available at BB. |
| 3943 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); |
| 3944 | if (L && (ARLoop == L || ARLoop->contains(L))) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3945 | return true; |
| 3946 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3947 | return setUnavailable(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3948 | } |
| 3949 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3950 | case scUnknown: { |
| 3951 | // For SCEVUnknown, we check for simple dominance. |
| 3952 | const auto *SU = cast<SCEVUnknown>(S); |
| 3953 | Value *V = SU->getValue(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3954 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3955 | if (isa<Argument>(V)) |
| 3956 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3957 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3958 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) |
| 3959 | return false; |
| 3960 | |
| 3961 | return setUnavailable(); |
| 3962 | } |
| 3963 | |
| 3964 | case scUDivExpr: |
| 3965 | case scCouldNotCompute: |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3966 | // We do not try to smart about these at all. |
| 3967 | return setUnavailable(); |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3968 | } |
| 3969 | llvm_unreachable("switch should be fully covered!"); |
| 3970 | } |
| 3971 | |
| 3972 | bool isDone() { return TraversalDone; } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3973 | }; |
| 3974 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 3975 | CheckAvailable CA(L, BB, DT); |
| 3976 | SCEVTraversal<CheckAvailable> ST(CA); |
| 3977 | |
| 3978 | ST.visitAll(S); |
| 3979 | return CA.Available; |
| 3980 | } |
| 3981 | |
| 3982 | // Try to match a control flow sequence that branches out at BI and merges back |
| 3983 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful |
| 3984 | // match. |
| 3985 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, |
| 3986 | Value *&C, Value *&LHS, Value *&RHS) { |
| 3987 | C = BI->getCondition(); |
| 3988 | |
| 3989 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); |
| 3990 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); |
| 3991 | |
| 3992 | if (!LeftEdge.isSingleEdge()) |
| 3993 | return false; |
| 3994 | |
| 3995 | assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); |
| 3996 | |
| 3997 | Use &LeftUse = Merge->getOperandUse(0); |
| 3998 | Use &RightUse = Merge->getOperandUse(1); |
| 3999 | |
| 4000 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { |
| 4001 | LHS = LeftUse; |
| 4002 | RHS = RightUse; |
| 4003 | return true; |
| 4004 | } |
| 4005 | |
| 4006 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { |
| 4007 | LHS = RightUse; |
| 4008 | RHS = LeftUse; |
| 4009 | return true; |
| 4010 | } |
| 4011 | |
| 4012 | return false; |
| 4013 | } |
| 4014 | |
| 4015 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4016 | if (PN->getNumIncomingValues() == 2) { |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4017 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 4018 | |
Sanjoy Das | 337d478 | 2015-10-31 23:21:40 +0000 | [diff] [blame] | 4019 | // We don't want to break LCSSA, even in a SCEV expression tree. |
| 4020 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 4021 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) |
| 4022 | return nullptr; |
| 4023 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4024 | // Try to match |
| 4025 | // |
| 4026 | // br %cond, label %left, label %right |
| 4027 | // left: |
| 4028 | // br label %merge |
| 4029 | // right: |
| 4030 | // br label %merge |
| 4031 | // merge: |
| 4032 | // V = phi [ %x, %left ], [ %y, %right ] |
| 4033 | // |
| 4034 | // as "select %cond, %x, %y" |
| 4035 | |
| 4036 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); |
| 4037 | assert(IDom && "At least the entry block should dominate PN"); |
| 4038 | |
| 4039 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); |
| 4040 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; |
| 4041 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4042 | if (BI && BI->isConditional() && |
| 4043 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && |
| 4044 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && |
| 4045 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4046 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); |
| 4047 | } |
| 4048 | |
| 4049 | return nullptr; |
| 4050 | } |
| 4051 | |
| 4052 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
| 4053 | if (const SCEV *S = createAddRecFromPHI(PN)) |
| 4054 | return S; |
| 4055 | |
| 4056 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) |
| 4057 | return S; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 4058 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4059 | // If the PHI has a single incoming value, follow that value, unless the |
| 4060 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 4061 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 4062 | // it doesn't have DominatorTree information, so it may miss cases. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4063 | if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4064 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4065 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 4066 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4067 | // 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] | 4068 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4069 | } |
| 4070 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4071 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, |
| 4072 | Value *Cond, |
| 4073 | Value *TrueVal, |
| 4074 | Value *FalseVal) { |
Mehdi Amini | 044cb34 | 2015-10-07 18:14:25 +0000 | [diff] [blame] | 4075 | // Handle "constant" branch or select. This can occur for instance when a |
| 4076 | // loop pass transforms an inner loop and moves on to process the outer loop. |
| 4077 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) |
| 4078 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); |
| 4079 | |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4080 | // Try to match some simple smax or umax patterns. |
| 4081 | auto *ICI = dyn_cast<ICmpInst>(Cond); |
| 4082 | if (!ICI) |
| 4083 | return getUnknown(I); |
| 4084 | |
| 4085 | Value *LHS = ICI->getOperand(0); |
| 4086 | Value *RHS = ICI->getOperand(1); |
| 4087 | |
| 4088 | switch (ICI->getPredicate()) { |
| 4089 | case ICmpInst::ICMP_SLT: |
| 4090 | case ICmpInst::ICMP_SLE: |
| 4091 | std::swap(LHS, RHS); |
| 4092 | // fall through |
| 4093 | case ICmpInst::ICMP_SGT: |
| 4094 | case ICmpInst::ICMP_SGE: |
| 4095 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4096 | // a >s b ? b+x : a+x -> smin(a, b)+x |
| 4097 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4098 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); |
| 4099 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); |
| 4100 | const SCEV *LA = getSCEV(TrueVal); |
| 4101 | const SCEV *RA = getSCEV(FalseVal); |
| 4102 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4103 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4104 | if (LDiff == RDiff) |
| 4105 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4106 | LDiff = getMinusSCEV(LA, RS); |
| 4107 | RDiff = getMinusSCEV(RA, LS); |
| 4108 | if (LDiff == RDiff) |
| 4109 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4110 | } |
| 4111 | break; |
| 4112 | case ICmpInst::ICMP_ULT: |
| 4113 | case ICmpInst::ICMP_ULE: |
| 4114 | std::swap(LHS, RHS); |
| 4115 | // fall through |
| 4116 | case ICmpInst::ICMP_UGT: |
| 4117 | case ICmpInst::ICMP_UGE: |
| 4118 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4119 | // a >u b ? b+x : a+x -> umin(a, b)+x |
| 4120 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4121 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4122 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); |
| 4123 | const SCEV *LA = getSCEV(TrueVal); |
| 4124 | const SCEV *RA = getSCEV(FalseVal); |
| 4125 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4126 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4127 | if (LDiff == RDiff) |
| 4128 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4129 | LDiff = getMinusSCEV(LA, RS); |
| 4130 | RDiff = getMinusSCEV(RA, LS); |
| 4131 | if (LDiff == RDiff) |
| 4132 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4133 | } |
| 4134 | break; |
| 4135 | case ICmpInst::ICMP_NE: |
| 4136 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
| 4137 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4138 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4139 | const SCEV *One = getOne(I->getType()); |
| 4140 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4141 | const SCEV *LA = getSCEV(TrueVal); |
| 4142 | const SCEV *RA = getSCEV(FalseVal); |
| 4143 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4144 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4145 | if (LDiff == RDiff) |
| 4146 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4147 | } |
| 4148 | break; |
| 4149 | case ICmpInst::ICMP_EQ: |
| 4150 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
| 4151 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4152 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4153 | const SCEV *One = getOne(I->getType()); |
| 4154 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4155 | const SCEV *LA = getSCEV(TrueVal); |
| 4156 | const SCEV *RA = getSCEV(FalseVal); |
| 4157 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4158 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4159 | if (LDiff == RDiff) |
| 4160 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4161 | } |
| 4162 | break; |
| 4163 | default: |
| 4164 | break; |
| 4165 | } |
| 4166 | |
| 4167 | return getUnknown(I); |
| 4168 | } |
| 4169 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4170 | /// createNodeForGEP - Expand GEP instructions into add and multiply |
| 4171 | /// operations. This allows them to be analyzed by regular SCEV code. |
| 4172 | /// |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4173 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4174 | // Don't attempt to analyze GEPs over unsized objects. |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4175 | if (!GEP->getSourceElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4176 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 4177 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 4178 | SmallVector<const SCEV *, 4> IndexExprs; |
| 4179 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 4180 | IndexExprs.push_back(getSCEV(*Index)); |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4181 | return getGEPExpr(GEP->getSourceElementType(), |
| 4182 | getSCEV(GEP->getPointerOperand()), |
| 4183 | IndexExprs, GEP->isInBounds()); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4184 | } |
| 4185 | |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4186 | /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is |
| 4187 | /// guaranteed to end in (at every loop iteration). It is, at the same time, |
| 4188 | /// the minimum number of times S is divisible by 2. For example, given {4,+,8} |
| 4189 | /// 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] | 4190 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4191 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4192 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4193 | return C->getAPInt().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4194 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4195 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4196 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 4197 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4198 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4199 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4200 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4201 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4202 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4203 | } |
| 4204 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4205 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4206 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4207 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4208 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4209 | } |
| 4210 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4211 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4212 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4213 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4214 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4215 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4216 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4217 | } |
| 4218 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4219 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4220 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4221 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 4222 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4223 | for (unsigned i = 1, e = M->getNumOperands(); |
| 4224 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4225 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4226 | BitWidth); |
| 4227 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4228 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4229 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4230 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4231 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4232 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4233 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4234 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4235 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4236 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4237 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4238 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4239 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4240 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4241 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4242 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4243 | return MinOpRes; |
| 4244 | } |
| 4245 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4246 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4247 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4248 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4249 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4250 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4251 | return MinOpRes; |
| 4252 | } |
| 4253 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4254 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 4255 | // For a SCEVUnknown, ask ValueTracking. |
| 4256 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4257 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4258 | computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, |
| 4259 | nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4260 | return Zeros.countTrailingOnes(); |
| 4261 | } |
| 4262 | |
| 4263 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4264 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4265 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4266 | |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4267 | /// GetRangeFromMetadata - Helper method to assign a range to V from |
| 4268 | /// metadata present in the IR. |
| 4269 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
Sanjoy Das | a7e1378 | 2015-10-24 05:37:35 +0000 | [diff] [blame] | 4270 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4271 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) |
| 4272 | return getConstantRangeFromMetadata(*MD); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4273 | |
| 4274 | return None; |
| 4275 | } |
| 4276 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4277 | /// getRange - Determine the range for a particular SCEV. If SignHint is |
| 4278 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 4279 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4280 | /// |
| 4281 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4282 | ScalarEvolution::getRange(const SCEV *S, |
| 4283 | ScalarEvolution::RangeSignHint SignHint) { |
| 4284 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 4285 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 4286 | : SignedRanges; |
| 4287 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4288 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4289 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 4290 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4291 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4292 | |
| 4293 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4294 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4295 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4296 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 4297 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 4298 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4299 | // If the value has known zeros, the maximum value will have those known zeros |
| 4300 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4301 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4302 | if (TZ != 0) { |
| 4303 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 4304 | ConservativeResult = |
| 4305 | ConstantRange(APInt::getMinValue(BitWidth), |
| 4306 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 4307 | else |
| 4308 | ConservativeResult = ConstantRange( |
| 4309 | APInt::getSignedMinValue(BitWidth), |
| 4310 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 4311 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4312 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4313 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4314 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4315 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4316 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 4317 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4318 | } |
| 4319 | |
| 4320 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4321 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4322 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4323 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 4324 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4325 | } |
| 4326 | |
| 4327 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4328 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4329 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4330 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 4331 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4332 | } |
| 4333 | |
| 4334 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4335 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4336 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4337 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 4338 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4339 | } |
| 4340 | |
| 4341 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4342 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 4343 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 4344 | return setRange(UDiv, SignHint, |
| 4345 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4346 | } |
| 4347 | |
| 4348 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4349 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 4350 | return setRange(ZExt, SignHint, |
| 4351 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4352 | } |
| 4353 | |
| 4354 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4355 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 4356 | return setRange(SExt, SignHint, |
| 4357 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4358 | } |
| 4359 | |
| 4360 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4361 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 4362 | return setRange(Trunc, SignHint, |
| 4363 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4364 | } |
| 4365 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4366 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4367 | // If there's no unsigned wrap, the value will never be less than its |
| 4368 | // initial value. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4369 | if (AddRec->hasNoUnsignedWrap()) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4370 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 4371 | if (!C->getValue()->isZero()) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4372 | ConservativeResult = ConservativeResult.intersectWith( |
| 4373 | ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4374 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4375 | // If there's no signed wrap, and all the operands have the same sign or |
| 4376 | // zero, the value won't ever change sign. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4377 | if (AddRec->hasNoSignedWrap()) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4378 | bool AllNonNeg = true; |
| 4379 | bool AllNonPos = true; |
| 4380 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 4381 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 4382 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4383 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4384 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4385 | ConservativeResult = ConservativeResult.intersectWith( |
| 4386 | ConstantRange(APInt(BitWidth, 0), |
| 4387 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4388 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4389 | ConservativeResult = ConservativeResult.intersectWith( |
| 4390 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4391 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4392 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4393 | |
| 4394 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4395 | if (AddRec->isAffine()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4396 | Type *Ty = AddRec->getType(); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4397 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4398 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4399 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4400 | |
| 4401 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4402 | // because we could be called from within the ScalarEvolution overflow |
| 4403 | // checking code. |
| 4404 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4405 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4406 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
| 4407 | ConstantRange ZExtMaxBECountRange = |
| 4408 | MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4409 | |
| 4410 | const SCEV *Start = AddRec->getStart(); |
Dan Gohman | f76210e | 2010-04-12 07:39:33 +0000 | [diff] [blame] | 4411 | const SCEV *Step = AddRec->getStepRecurrence(*this); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4412 | ConstantRange StepSRange = getSignedRange(Step); |
| 4413 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4414 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4415 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4416 | ConstantRange EndURange = |
| 4417 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
Dan Gohman | f76210e | 2010-04-12 07:39:33 +0000 | [diff] [blame] | 4418 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4419 | // Check for unsigned overflow. |
| 4420 | ConstantRange ZExtStartURange = |
| 4421 | StartURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4422 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4423 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4424 | ZExtEndURange) { |
| 4425 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4426 | EndURange.getUnsignedMin()); |
| 4427 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4428 | EndURange.getUnsignedMax()); |
| 4429 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4430 | if (!IsFullRange) |
| 4431 | ConservativeResult = |
| 4432 | ConservativeResult.intersectWith(ConstantRange(Min, Max + 1)); |
| 4433 | } |
Dan Gohman | f76210e | 2010-04-12 07:39:33 +0000 | [diff] [blame] | 4434 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4435 | ConstantRange StartSRange = getSignedRange(Start); |
| 4436 | ConstantRange EndSRange = |
| 4437 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4438 | |
| 4439 | // Check for signed overflow. This must be done with ConstantRange |
| 4440 | // arithmetic because we could be called from within the ScalarEvolution |
| 4441 | // overflow checking code. |
| 4442 | ConstantRange SExtStartSRange = |
| 4443 | StartSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4444 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4445 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4446 | SExtEndSRange) { |
| 4447 | APInt Min = APIntOps::smin(StartSRange.getSignedMin(), |
| 4448 | EndSRange.getSignedMin()); |
| 4449 | APInt Max = APIntOps::smax(StartSRange.getSignedMax(), |
| 4450 | EndSRange.getSignedMax()); |
| 4451 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4452 | if (!IsFullRange) |
| 4453 | ConservativeResult = |
| 4454 | ConservativeResult.intersectWith(ConstantRange(Min, Max + 1)); |
| 4455 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4456 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4457 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4458 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4459 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4460 | } |
| 4461 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4462 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4463 | // Check if the IR explicitly contains !range metadata. |
| 4464 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4465 | if (MDRange.hasValue()) |
| 4466 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4467 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4468 | // Split here to avoid paying the compile-time cost of calling both |
| 4469 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4470 | // if needed. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4471 | const DataLayout &DL = getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4472 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4473 | // For a SCEVUnknown, ask ValueTracking. |
| 4474 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4475 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4476 | if (Ones != ~Zeros + 1) |
| 4477 | ConservativeResult = |
| 4478 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4479 | } else { |
| 4480 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4481 | "generalize as needed!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4482 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4483 | if (NS > 1) |
| 4484 | ConservativeResult = ConservativeResult.intersectWith( |
| 4485 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4486 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4487 | } |
| 4488 | |
| 4489 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4490 | } |
| 4491 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4492 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4493 | } |
| 4494 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4495 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4496 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4497 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4498 | |
| 4499 | // Return early if there are no flags to propagate to the SCEV. |
| 4500 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4501 | if (BinOp->hasNoUnsignedWrap()) |
| 4502 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4503 | if (BinOp->hasNoSignedWrap()) |
| 4504 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 4505 | if (Flags == SCEV::FlagAnyWrap) { |
| 4506 | return SCEV::FlagAnyWrap; |
| 4507 | } |
| 4508 | |
| 4509 | // Here we check that BinOp is in the header of the innermost loop |
| 4510 | // containing BinOp, since we only deal with instructions in the loop |
| 4511 | // header. The actual loop we need to check later will come from an add |
| 4512 | // recurrence, but getting that requires computing the SCEV of the operands, |
| 4513 | // which can be expensive. This check we can do cheaply to rule out some |
| 4514 | // cases early. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4515 | Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent()); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4516 | if (innermostContainingLoop == nullptr || |
| 4517 | innermostContainingLoop->getHeader() != BinOp->getParent()) |
| 4518 | return SCEV::FlagAnyWrap; |
| 4519 | |
| 4520 | // Only proceed if we can prove that BinOp does not yield poison. |
| 4521 | if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap; |
| 4522 | |
| 4523 | // At this point we know that if V is executed, then it does not wrap |
| 4524 | // according to at least one of NSW or NUW. If V is not executed, then we do |
| 4525 | // not know if the calculation that V represents would wrap. Multiple |
| 4526 | // instructions can map to the same SCEV. If we apply NSW or NUW from V to |
| 4527 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4528 | // derived from other instructions that map to the same SCEV. We cannot make |
| 4529 | // that guarantee for cases where V is not executed. So we need to find the |
| 4530 | // loop that V is considered in relation to and prove that V is executed for |
| 4531 | // every iteration of that loop. That implies that the value that V |
| 4532 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4533 | // flags to the SCEV. |
| 4534 | // |
| 4535 | // We check isLoopInvariant to disambiguate in case we are adding two |
| 4536 | // recurrences from different loops, so that we know which loop to prove |
| 4537 | // that V is executed in. |
| 4538 | for (int OpIndex = 0; OpIndex < 2; ++OpIndex) { |
| 4539 | const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex)); |
| 4540 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 4541 | const int OtherOpIndex = 1 - OpIndex; |
| 4542 | const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex)); |
| 4543 | if (isLoopInvariant(OtherOp, AddRec->getLoop()) && |
| 4544 | isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop())) |
| 4545 | return Flags; |
| 4546 | } |
| 4547 | } |
| 4548 | return SCEV::FlagAnyWrap; |
| 4549 | } |
| 4550 | |
| 4551 | /// createSCEV - We know that there is no SCEV for the specified value. Analyze |
| 4552 | /// the expression. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4553 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4554 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4555 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4556 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4557 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4558 | unsigned Opcode = Instruction::UserOp1; |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4559 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4560 | Opcode = I->getOpcode(); |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4561 | |
| 4562 | // Don't attempt to analyze instructions in blocks that aren't |
| 4563 | // reachable. Such instructions don't matter, and they aren't required |
| 4564 | // to obey basic rules for definitions dominating uses which this |
| 4565 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4566 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4567 | return getUnknown(V); |
| 4568 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4569 | Opcode = CE->getOpcode(); |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 4570 | else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
| 4571 | return getConstant(CI); |
| 4572 | else if (isa<ConstantPointerNull>(V)) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 4573 | return getZero(V->getType()); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 4574 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
| 4575 | return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4576 | else |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4577 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 4578 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 4579 | Operator *U = cast<Operator>(V); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4580 | switch (Opcode) { |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4581 | case Instruction::Add: { |
| 4582 | // The simple thing to do would be to just call getSCEV on both operands |
| 4583 | // and call getAddExpr with the result. However if we're looking at a |
| 4584 | // bunch of things all added together, this can be quite inefficient, |
| 4585 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 4586 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 4587 | // LLVM IR canonical form means we need only traverse the left operands. |
| 4588 | SmallVector<const SCEV *, 4> AddOps; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4589 | for (Value *Op = U;; Op = U->getOperand(0)) { |
| 4590 | U = dyn_cast<Operator>(Op); |
| 4591 | unsigned Opcode = U ? U->getOpcode() : 0; |
| 4592 | if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) { |
| 4593 | assert(Op != V && "V should be an add"); |
| 4594 | AddOps.push_back(getSCEV(Op)); |
Dan Gohman | 47308d5 | 2010-08-31 22:53:17 +0000 | [diff] [blame] | 4595 | break; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4596 | } |
| 4597 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4598 | if (auto *OpSCEV = getExistingSCEV(U)) { |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4599 | AddOps.push_back(OpSCEV); |
| 4600 | break; |
| 4601 | } |
| 4602 | |
| 4603 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 4604 | // addition, then compute the SCEV for this addition by itself |
| 4605 | // with a separate call to getAddExpr. We need to do that |
| 4606 | // instead of pushing the operands of the addition onto AddOps, |
| 4607 | // since the flags are only known to apply to this particular |
| 4608 | // addition - they may not apply to other additions that can be |
| 4609 | // formed with operands from AddOps. |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4610 | const SCEV *RHS = getSCEV(U->getOperand(1)); |
| 4611 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); |
| 4612 | if (Flags != SCEV::FlagAnyWrap) { |
| 4613 | const SCEV *LHS = getSCEV(U->getOperand(0)); |
| 4614 | if (Opcode == Instruction::Sub) |
| 4615 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 4616 | else |
| 4617 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 4618 | break; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4619 | } |
| 4620 | |
Dan Gohman | 47308d5 | 2010-08-31 22:53:17 +0000 | [diff] [blame] | 4621 | if (Opcode == Instruction::Sub) |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4622 | AddOps.push_back(getNegativeSCEV(RHS)); |
Dan Gohman | 47308d5 | 2010-08-31 22:53:17 +0000 | [diff] [blame] | 4623 | else |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4624 | AddOps.push_back(RHS); |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4625 | } |
Andrew Trick | d25089f | 2011-11-29 02:16:38 +0000 | [diff] [blame] | 4626 | return getAddExpr(AddOps); |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4627 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4628 | |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4629 | case Instruction::Mul: { |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4630 | SmallVector<const SCEV *, 4> MulOps; |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4631 | for (Value *Op = U;; Op = U->getOperand(0)) { |
| 4632 | U = dyn_cast<Operator>(Op); |
| 4633 | if (!U || U->getOpcode() != Instruction::Mul) { |
| 4634 | assert(Op != V && "V should be a mul"); |
| 4635 | MulOps.push_back(getSCEV(Op)); |
| 4636 | break; |
| 4637 | } |
| 4638 | |
| 4639 | if (auto *OpSCEV = getExistingSCEV(U)) { |
| 4640 | MulOps.push_back(OpSCEV); |
| 4641 | break; |
| 4642 | } |
| 4643 | |
| 4644 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); |
| 4645 | if (Flags != SCEV::FlagAnyWrap) { |
| 4646 | MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)), |
| 4647 | getSCEV(U->getOperand(1)), Flags)); |
| 4648 | break; |
| 4649 | } |
| 4650 | |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4651 | MulOps.push_back(getSCEV(U->getOperand(1))); |
| 4652 | } |
Dan Gohman | e5fb103 | 2010-08-16 16:03:49 +0000 | [diff] [blame] | 4653 | return getMulExpr(MulOps); |
| 4654 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4655 | case Instruction::UDiv: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4656 | return getUDivExpr(getSCEV(U->getOperand(0)), |
| 4657 | getSCEV(U->getOperand(1))); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4658 | case Instruction::Sub: |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4659 | return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)), |
| 4660 | getNoWrapFlagsFromUB(U)); |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4661 | case Instruction::And: |
| 4662 | // For an expression like x&255 that merely masks off the high bits, |
| 4663 | // use zext(trunc(x)) as the SCEV expression. |
| 4664 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | df19948 | 2009-04-25 17:05:40 +0000 | [diff] [blame] | 4665 | if (CI->isNullValue()) |
| 4666 | return getSCEV(U->getOperand(1)); |
Dan Gohman | 05c1d37 | 2009-04-27 01:41:10 +0000 | [diff] [blame] | 4667 | if (CI->isAllOnesValue()) |
| 4668 | return getSCEV(U->getOperand(0)); |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4669 | const APInt &A = CI->getValue(); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4670 | |
| 4671 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 4672 | // constants, obscuring what would otherwise be a low-bits mask. |
Jay Foad | a0653a3 | 2014-05-14 21:14:37 +0000 | [diff] [blame] | 4673 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4674 | // knew about to reconstruct a low-bits mask value. |
| 4675 | unsigned LZ = A.countLeadingZeros(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 4676 | unsigned TZ = A.countTrailingZeros(); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4677 | unsigned BitWidth = A.getBitWidth(); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4678 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4679 | computeKnownBits(U->getOperand(0), KnownZero, KnownOne, getDataLayout(), |
| 4680 | 0, &AC, nullptr, &DT); |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4681 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 4682 | APInt EffectiveMask = |
| 4683 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 4684 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
| 4685 | const SCEV *MulCount = getConstant( |
| 4686 | ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ))); |
| 4687 | return getMulExpr( |
| 4688 | getZeroExtendExpr( |
| 4689 | getTruncateExpr( |
| 4690 | getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount), |
| 4691 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 4692 | U->getType()), |
| 4693 | MulCount); |
| 4694 | } |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4695 | } |
| 4696 | break; |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 4697 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4698 | case Instruction::Or: |
| 4699 | // If the RHS of the Or is a constant, we may have something like: |
| 4700 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 4701 | // optimizations will transparently handle this case. |
| 4702 | // |
| 4703 | // In order for this transformation to be safe, the LHS must be of the |
| 4704 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 4705 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4706 | const SCEV *LHS = getSCEV(U->getOperand(0)); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4707 | const APInt &CIVal = CI->getValue(); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4708 | if (GetMinTrailingZeros(LHS) >= |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4709 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 4710 | // Build a plain add SCEV. |
| 4711 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 4712 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 4713 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 4714 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 4715 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 4716 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 4717 | OldAR->getNoWrapFlags()); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4718 | } |
| 4719 | return S; |
| 4720 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4721 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4722 | break; |
| 4723 | case Instruction::Xor: |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4724 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4725 | // If the RHS of the xor is a signbit, then this is just an add. |
| 4726 | // Instcombine turns add of signbit into xor as a strength reduction step. |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4727 | if (CI->getValue().isSignBit()) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4728 | return getAddExpr(getSCEV(U->getOperand(0)), |
| 4729 | getSCEV(U->getOperand(1))); |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4730 | |
| 4731 | // If the RHS of xor is -1, then this is a not operation. |
Dan Gohman | d277a1e | 2009-05-18 16:17:44 +0000 | [diff] [blame] | 4732 | if (CI->isAllOnesValue()) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4733 | return getNotSCEV(getSCEV(U->getOperand(0))); |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 4734 | |
| 4735 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 4736 | // This is a variant of the check for xor with -1, and it handles |
| 4737 | // the case where instcombine has trimmed non-demanded bits out |
| 4738 | // of an xor with -1. |
| 4739 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) |
| 4740 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1))) |
| 4741 | if (BO->getOpcode() == Instruction::And && |
| 4742 | LCI->getValue() == CI->getValue()) |
| 4743 | if (const SCEVZeroExtendExpr *Z = |
Dan Gohman | b50f5a4 | 2009-06-17 01:22:39 +0000 | [diff] [blame] | 4744 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4745 | Type *UTy = U->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4746 | const SCEV *Z0 = Z->getOperand(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4747 | Type *Z0Ty = Z0->getType(); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4748 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
| 4749 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 4750 | // If C is a low-bits mask, the zero extend is serving to |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4751 | // mask off the high bits. Complement the operand and |
| 4752 | // re-apply the zext. |
| 4753 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 4754 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 4755 | |
| 4756 | // If C is a single bit, it may be in the sign-bit position |
| 4757 | // before the zero-extend. In this case, represent the xor |
| 4758 | // using an add, which is equivalent, and re-apply the zext. |
Jay Foad | 583abbc | 2010-12-07 08:25:19 +0000 | [diff] [blame] | 4759 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 4760 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 4761 | Trunc.isSignBit()) |
| 4762 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 4763 | UTy); |
Dan Gohman | b50f5a4 | 2009-06-17 01:22:39 +0000 | [diff] [blame] | 4764 | } |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4765 | } |
| 4766 | break; |
| 4767 | |
| 4768 | case Instruction::Shl: |
| 4769 | // Turn shift left of a constant amount into a multiply. |
| 4770 | if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 4771 | uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4772 | |
| 4773 | // If the shift count is not less than the bitwidth, the result of |
| 4774 | // the shift is undefined. Don't try to analyze it, because the |
| 4775 | // resolution chosen here may differ from the resolution chosen in |
| 4776 | // other parts of the compiler. |
| 4777 | if (SA->getValue().uge(BitWidth)) |
| 4778 | break; |
| 4779 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4780 | // It is currently not resolved how to interpret NSW for left |
| 4781 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 4782 | // case. Remove this check (or this comment) once the situation |
| 4783 | // is resolved. See |
| 4784 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 4785 | // and http://reviews.llvm.org/D8890 . |
| 4786 | auto Flags = SCEV::FlagAnyWrap; |
| 4787 | if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U); |
| 4788 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4789 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 4790 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4791 | return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4792 | } |
| 4793 | break; |
| 4794 | |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4795 | case Instruction::LShr: |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 4796 | // Turn logical shift right of a constant into a unsigned divide. |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4797 | if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 4798 | uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4799 | |
| 4800 | // If the shift count is not less than the bitwidth, the result of |
| 4801 | // the shift is undefined. Don't try to analyze it, because the |
| 4802 | // resolution chosen here may differ from the resolution chosen in |
| 4803 | // other parts of the compiler. |
| 4804 | if (SA->getValue().uge(BitWidth)) |
| 4805 | break; |
| 4806 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4807 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 4808 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4809 | return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 4810 | } |
| 4811 | break; |
| 4812 | |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4813 | case Instruction::AShr: |
| 4814 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 4815 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4816 | if (Operator *L = dyn_cast<Operator>(U->getOperand(0))) |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4817 | if (L->getOpcode() == Instruction::Shl && |
| 4818 | L->getOperand(1) == U->getOperand(1)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4819 | uint64_t BitWidth = getTypeSizeInBits(U->getType()); |
| 4820 | |
| 4821 | // If the shift count is not less than the bitwidth, the result of |
| 4822 | // the shift is undefined. Don't try to analyze it, because the |
| 4823 | // resolution chosen here may differ from the resolution chosen in |
| 4824 | // other parts of the compiler. |
| 4825 | if (CI->getValue().uge(BitWidth)) |
| 4826 | break; |
| 4827 | |
Dan Gohman | df19948 | 2009-04-25 17:05:40 +0000 | [diff] [blame] | 4828 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 4829 | if (Amt == BitWidth) |
| 4830 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4831 | return |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4832 | getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 4833 | IntegerType::get(getContext(), |
| 4834 | Amt)), |
| 4835 | U->getType()); |
Dan Gohman | 0ec0537 | 2009-04-21 02:26:00 +0000 | [diff] [blame] | 4836 | } |
| 4837 | break; |
| 4838 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4839 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4840 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4841 | |
| 4842 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4843 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4844 | |
| 4845 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4846 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4847 | |
| 4848 | case Instruction::BitCast: |
| 4849 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4850 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4851 | return getSCEV(U->getOperand(0)); |
| 4852 | break; |
| 4853 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 4854 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 4855 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 4856 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 4857 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4858 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4859 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4860 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4861 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4862 | case Instruction::PHI: |
| 4863 | return createNodeForPHI(cast<PHINode>(U)); |
| 4864 | |
| 4865 | case Instruction::Select: |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4866 | // U can also be a select constant expr, which let fall through. Since |
| 4867 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and |
| 4868 | // constant expressions cannot have instructions as operands, we'd have |
| 4869 | // returned getUnknown for a select constant expressions anyway. |
| 4870 | if (isa<Instruction>(U)) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4871 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), |
| 4872 | U->getOperand(1), U->getOperand(2)); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 4873 | |
| 4874 | default: // We cannot analyze this expression. |
| 4875 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4876 | } |
| 4877 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4878 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4879 | } |
| 4880 | |
| 4881 | |
| 4882 | |
| 4883 | //===----------------------------------------------------------------------===// |
| 4884 | // Iteration Count Computation Code |
| 4885 | // |
| 4886 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4887 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 4888 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 4889 | return getSmallConstantTripCount(L, ExitingBB); |
| 4890 | |
| 4891 | // No trip count information for multiple exits. |
| 4892 | return 0; |
| 4893 | } |
| 4894 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4895 | /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 4896 | /// normal unsigned value. Returns 0 if the trip count is unknown or not |
| 4897 | /// constant. Will also return 0 if the maximum trip count is very large (>= |
| 4898 | /// 2^32). |
| 4899 | /// |
| 4900 | /// This "trip count" assumes that control exits via ExitingBlock. More |
| 4901 | /// precisely, it is the number of times that control may reach ExitingBlock |
| 4902 | /// before taking the branch. For loops with multiple exits, it may not be the |
| 4903 | /// number times that the loop header executes because the loop may exit |
| 4904 | /// prematurely via another branch. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4905 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 4906 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4907 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 4908 | assert(L->isLoopExiting(ExitingBlock) && |
| 4909 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4910 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4911 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4912 | if (!ExitCount) |
| 4913 | return 0; |
| 4914 | |
| 4915 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 4916 | |
| 4917 | // Guard against huge trip counts. |
| 4918 | if (ExitConst->getValue().getActiveBits() > 32) |
| 4919 | return 0; |
| 4920 | |
| 4921 | // In case of integer overflow, this returns 0, which is correct. |
| 4922 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 4923 | } |
| 4924 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4925 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 4926 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 4927 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 4928 | |
| 4929 | // No trip multiple information for multiple exits. |
| 4930 | return 0; |
| 4931 | } |
| 4932 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4933 | /// getSmallConstantTripMultiple - Returns the largest constant divisor of the |
| 4934 | /// trip count of this loop as a normal unsigned value, if possible. This |
| 4935 | /// means that the actual trip count is always a multiple of the returned |
| 4936 | /// value (don't forget the trip count could very well be zero as well!). |
| 4937 | /// |
| 4938 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 4939 | /// multiple of a constant (which is also the case if the trip count is simply |
| 4940 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 4941 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 4942 | /// |
| 4943 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 4944 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4945 | unsigned |
| 4946 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 4947 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 4948 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 4949 | assert(L->isLoopExiting(ExitingBlock) && |
| 4950 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 4951 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4952 | if (ExitCount == getCouldNotCompute()) |
| 4953 | return 1; |
| 4954 | |
| 4955 | // Get the trip count from the BE count by adding 1. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 4956 | const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4957 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 4958 | // to factor simple cases. |
| 4959 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 4960 | TCMul = Mul->getOperand(0); |
| 4961 | |
| 4962 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 4963 | if (!MulC) |
| 4964 | return 1; |
| 4965 | |
| 4966 | ConstantInt *Result = MulC->getValue(); |
| 4967 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 4968 | // Guard against huge trip counts (this requires checking |
| 4969 | // for zero to handle the case where the trip count == -1 and the |
| 4970 | // addition wraps). |
| 4971 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 4972 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 4973 | return 1; |
| 4974 | |
| 4975 | return (unsigned)Result->getZExtValue(); |
| 4976 | } |
| 4977 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4978 | // getExitCount - Get the expression for the number of loop iterations for which |
Andrew Trick | ee9143a | 2013-05-31 23:34:46 +0000 | [diff] [blame] | 4979 | // this loop is guaranteed not to exit via ExitingBlock. Otherwise return |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4980 | // SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 4981 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 4982 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4983 | } |
| 4984 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 4985 | /// getBackedgeTakenCount - If the specified loop has a predictable |
| 4986 | /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute |
| 4987 | /// object. The backedge-taken count is the number of times the loop header |
| 4988 | /// will be branched to from within the loop. This is one less than the |
| 4989 | /// trip count of the loop, since it doesn't count the first iteration, |
| 4990 | /// when the header is branched to from outside the loop. |
| 4991 | /// |
| 4992 | /// Note that it is not valid to call this method on a loop without a |
| 4993 | /// loop-invariant backedge-taken count (see |
| 4994 | /// hasLoopInvariantBackedgeTakenCount). |
| 4995 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4996 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 4997 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 4998 | } |
| 4999 | |
| 5000 | /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except |
| 5001 | /// return the least SCEV value that is known never to be less than the |
| 5002 | /// actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5003 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5004 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5005 | } |
| 5006 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5007 | /// PushLoopPHIs - Push PHI nodes in the header of the given loop |
| 5008 | /// onto the given Worklist. |
| 5009 | static void |
| 5010 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 5011 | BasicBlock *Header = L->getHeader(); |
| 5012 | |
| 5013 | // Push all Loop-header PHIs onto the Worklist stack. |
| 5014 | for (BasicBlock::iterator I = Header->begin(); |
| 5015 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 5016 | Worklist.push_back(PN); |
| 5017 | } |
| 5018 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5019 | const ScalarEvolution::BackedgeTakenInfo & |
| 5020 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5021 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5022 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5023 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 5024 | // code elsewhere that it shouldn't attempt to request a new |
| 5025 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5026 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5027 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5028 | if (!Pair.second) |
| 5029 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5030 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5031 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5032 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 5033 | // must be cleared in this scope. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5034 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5035 | |
| 5036 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 5037 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 5038 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5039 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 5040 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5041 | } |
| 5042 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 5043 | isa<PHINode>(L->getHeader()->begin())) { |
| 5044 | // Only count loops that have phi nodes as not being computable. |
| 5045 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5046 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5047 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5048 | // Now that we know more about the trip count for this loop, forget any |
| 5049 | // existing SCEV values for PHI nodes in this loop since they are only |
| 5050 | // conservative estimates made without the benefit of trip count |
| 5051 | // information. This is similar to the code in forgetLoop, except that |
| 5052 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5053 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5054 | SmallVector<Instruction *, 16> Worklist; |
| 5055 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5056 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5057 | SmallPtrSet<Instruction *, 8> Visited; |
| 5058 | while (!Worklist.empty()) { |
| 5059 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5060 | if (!Visited.insert(I).second) |
| 5061 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5062 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5063 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5064 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5065 | if (It != ValueExprMap.end()) { |
| 5066 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 5067 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5068 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 5069 | // structure, or it's a PHI that's in the progress of being computed |
| 5070 | // by createNodeForPHI. In the former case, additional loop trip |
| 5071 | // count information isn't going to change anything. In the later |
| 5072 | // case, createNodeForPHI will perform the necessary updates on its |
| 5073 | // own when it gets to that point. |
| 5074 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
| 5075 | forgetMemoizedResults(Old); |
| 5076 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5077 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5078 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5079 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5080 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5081 | |
| 5082 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5083 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5084 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5085 | |
| 5086 | // Re-lookup the insert position, since the call to |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5087 | // computeBackedgeTakenCount above could result in a |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5088 | // recusive call to getBackedgeTakenInfo (on a different |
| 5089 | // loop), which would invalidate the iterator computed |
| 5090 | // earlier. |
| 5091 | return BackedgeTakenCounts.find(L)->second = Result; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5092 | } |
| 5093 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5094 | /// forgetLoop - This method should be called by the client when it has |
| 5095 | /// changed a loop in a way that may effect ScalarEvolution's ability to |
| 5096 | /// compute a trip count, or if the loop is deleted. |
| 5097 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 5098 | // Drop any stored trip count value. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5099 | DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos = |
| 5100 | BackedgeTakenCounts.find(L); |
| 5101 | if (BTCPos != BackedgeTakenCounts.end()) { |
| 5102 | BTCPos->second.clear(); |
| 5103 | BackedgeTakenCounts.erase(BTCPos); |
| 5104 | } |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 5105 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5106 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5107 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5108 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5109 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5110 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5111 | while (!Worklist.empty()) { |
| 5112 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5113 | if (!Visited.insert(I).second) |
| 5114 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5115 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5116 | ValueExprMapType::iterator It = |
| 5117 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5118 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5119 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5120 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5121 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5122 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5123 | } |
| 5124 | |
| 5125 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5126 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 5127 | |
| 5128 | // Forget all contained loops too, to avoid dangling entries in the |
| 5129 | // ValuesAtScopes map. |
| 5130 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 5131 | forgetLoop(*I); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 5132 | } |
| 5133 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 5134 | /// forgetValue - This method should be called by the client when it has |
| 5135 | /// changed a value in a way that may effect its value, or which may |
| 5136 | /// disconnect it from a def-use chain linking it to a loop. |
| 5137 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5138 | Instruction *I = dyn_cast<Instruction>(V); |
| 5139 | if (!I) return; |
| 5140 | |
| 5141 | // Drop information about expressions based on loop-header PHIs. |
| 5142 | SmallVector<Instruction *, 16> Worklist; |
| 5143 | Worklist.push_back(I); |
| 5144 | |
| 5145 | SmallPtrSet<Instruction *, 8> Visited; |
| 5146 | while (!Worklist.empty()) { |
| 5147 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5148 | if (!Visited.insert(I).second) |
| 5149 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5150 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5151 | ValueExprMapType::iterator It = |
| 5152 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5153 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5154 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5155 | ValueExprMap.erase(It); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5156 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5157 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5158 | } |
| 5159 | |
| 5160 | PushDefUseChildren(I, Worklist); |
| 5161 | } |
| 5162 | } |
| 5163 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5164 | /// getExact - Get the exact loop backedge taken count considering all loop |
Sanjoy Das | 135e5b9 | 2015-07-21 20:59:22 +0000 | [diff] [blame] | 5165 | /// exits. A computable result can only be returned for loops with a single |
| 5166 | /// exit. Returning the minimum taken count among all exits is incorrect |
| 5167 | /// because one of the loop's exit limit's may have been skipped. HowFarToZero |
| 5168 | /// assumes that the limit of each loop test is never skipped. This is a valid |
| 5169 | /// assumption as long as the loop exits via that test. For precise results, it |
| 5170 | /// is the caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5171 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5172 | const SCEV * |
| 5173 | ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const { |
| 5174 | // If any exits were not computable, the loop is not computable. |
| 5175 | if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); |
| 5176 | |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5177 | // We need exactly one computable exit. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5178 | if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5179 | assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); |
| 5180 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5181 | const SCEV *BECount = nullptr; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5182 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5183 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5184 | |
| 5185 | assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
| 5186 | |
| 5187 | if (!BECount) |
| 5188 | BECount = ENT->ExactNotTaken; |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5189 | else if (BECount != ENT->ExactNotTaken) |
| 5190 | return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5191 | } |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 5192 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5193 | return BECount; |
| 5194 | } |
| 5195 | |
| 5196 | /// getExact - Get the exact not taken count for this loop exit. |
| 5197 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5198 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5199 | ScalarEvolution *SE) const { |
| 5200 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5201 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5202 | |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5203 | if (ENT->ExitingBlock == ExitingBlock) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5204 | return ENT->ExactNotTaken; |
| 5205 | } |
| 5206 | return SE->getCouldNotCompute(); |
| 5207 | } |
| 5208 | |
| 5209 | /// getMax - Get the max backedge taken count for the loop. |
| 5210 | const SCEV * |
| 5211 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
| 5212 | return Max ? Max : SE->getCouldNotCompute(); |
| 5213 | } |
| 5214 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5215 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 5216 | ScalarEvolution *SE) const { |
| 5217 | if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) |
| 5218 | return true; |
| 5219 | |
| 5220 | if (!ExitNotTaken.ExitingBlock) |
| 5221 | return false; |
| 5222 | |
| 5223 | for (const ExitNotTakenInfo *ENT = &ExitNotTaken; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5224 | ENT != nullptr; ENT = ENT->getNextExit()) { |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5225 | |
| 5226 | if (ENT->ExactNotTaken != SE->getCouldNotCompute() |
| 5227 | && SE->hasOperand(ENT->ExactNotTaken, S)) { |
| 5228 | return true; |
| 5229 | } |
| 5230 | } |
| 5231 | return false; |
| 5232 | } |
| 5233 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5234 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 5235 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 5236 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
| 5237 | SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, |
| 5238 | bool Complete, const SCEV *MaxCount) : Max(MaxCount) { |
| 5239 | |
| 5240 | if (!Complete) |
| 5241 | ExitNotTaken.setIncomplete(); |
| 5242 | |
| 5243 | unsigned NumExits = ExitCounts.size(); |
| 5244 | if (NumExits == 0) return; |
| 5245 | |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5246 | ExitNotTaken.ExitingBlock = ExitCounts[0].first; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5247 | ExitNotTaken.ExactNotTaken = ExitCounts[0].second; |
| 5248 | if (NumExits == 1) return; |
| 5249 | |
| 5250 | // Handle the rare case of multiple computable exits. |
| 5251 | ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1]; |
| 5252 | |
| 5253 | ExitNotTakenInfo *PrevENT = &ExitNotTaken; |
| 5254 | for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) { |
| 5255 | PrevENT->setNextExit(ENT); |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5256 | ENT->ExitingBlock = ExitCounts[i].first; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5257 | ENT->ExactNotTaken = ExitCounts[i].second; |
| 5258 | } |
| 5259 | } |
| 5260 | |
| 5261 | /// clear - Invalidate this result and free the ExitNotTakenInfo array. |
| 5262 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5263 | ExitNotTaken.ExitingBlock = nullptr; |
| 5264 | ExitNotTaken.ExactNotTaken = nullptr; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5265 | delete[] ExitNotTaken.getNextExit(); |
| 5266 | } |
| 5267 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5268 | /// computeBackedgeTakenCount - Compute the number of times the backedge |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5269 | /// of the specified loop will execute. |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5270 | ScalarEvolution::BackedgeTakenInfo |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5271 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5272 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5273 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5274 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5275 | SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5276 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 5277 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5278 | const SCEV *MustExitMaxBECount = nullptr; |
| 5279 | const SCEV *MayExitMaxBECount = nullptr; |
| 5280 | |
| 5281 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 5282 | // and compute maxBECount. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5283 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5284 | BasicBlock *ExitBB = ExitingBlocks[i]; |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5285 | ExitLimit EL = computeExitLimit(L, ExitBB); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5286 | |
| 5287 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 5288 | // CouldComputeBECount is true only if all exits can be computed. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5289 | if (EL.Exact == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5290 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 5291 | // 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] | 5292 | CouldComputeBECount = false; |
| 5293 | else |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5294 | ExitCounts.push_back({ExitBB, EL.Exact}); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5295 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5296 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 5297 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 5298 | // LoopMustExits and LoopMayExits. |
| 5299 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5300 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5301 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
| 5302 | // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, |
| 5303 | // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is |
| 5304 | // considered greater than any computable EL.Max. |
| 5305 | if (EL.Max != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5306 | DT.dominates(ExitBB, Latch)) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5307 | if (!MustExitMaxBECount) |
| 5308 | MustExitMaxBECount = EL.Max; |
| 5309 | else { |
| 5310 | MustExitMaxBECount = |
| 5311 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5312 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5313 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
| 5314 | if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) |
| 5315 | MayExitMaxBECount = EL.Max; |
| 5316 | else { |
| 5317 | MayExitMaxBECount = |
| 5318 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); |
| 5319 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5320 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5321 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5322 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5323 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5324 | return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5325 | } |
| 5326 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5327 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5328 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5329 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5330 | // Okay, we've chosen an exiting block. See what condition causes us to exit |
| 5331 | // 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] | 5332 | // lead to the loop header. |
| 5333 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5334 | BasicBlock *Exit = nullptr; |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5335 | for (auto *SBB : successors(ExitingBlock)) |
| 5336 | if (!L->contains(SBB)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5337 | if (Exit) // Multiple exit successors. |
| 5338 | return getCouldNotCompute(); |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5339 | Exit = SBB; |
| 5340 | } else if (SBB != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5341 | MustExecuteLoopHeader = false; |
| 5342 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5343 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5344 | // At this point, we know we have a conditional branch that determines whether |
| 5345 | // the loop is exited. However, we don't know if the branch is executed each |
| 5346 | // time through the loop. If not, then the execution count of the branch will |
| 5347 | // not be equal to the trip count of the loop. |
| 5348 | // |
| 5349 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5350 | // 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] | 5351 | // 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] | 5352 | // loop header. This is common for un-rotated loops. |
| 5353 | // |
| 5354 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5355 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5356 | // header is reached, the execution count of the branch will be equal to the |
| 5357 | // trip count of the loop. |
| 5358 | // |
| 5359 | // More extensive analysis could be done to handle more cases here. |
| 5360 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5361 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5362 | // The simple checks failed, try climbing the unique predecessor chain |
| 5363 | // up to the header. |
| 5364 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5365 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5366 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5367 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5368 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5369 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5370 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5371 | if (PredSucc == BB) |
| 5372 | continue; |
| 5373 | // If the predecessor has a successor that isn't BB and isn't |
| 5374 | // outside the loop, assume the worst. |
| 5375 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5376 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5377 | } |
| 5378 | if (Pred == L->getHeader()) { |
| 5379 | Ok = true; |
| 5380 | break; |
| 5381 | } |
| 5382 | BB = Pred; |
| 5383 | } |
| 5384 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5385 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5386 | } |
| 5387 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5388 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5389 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5390 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5391 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5392 | // Proceed to the next level to examine the exit condition expression. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5393 | return computeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0), |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5394 | BI->getSuccessor(1), |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5395 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5396 | } |
| 5397 | |
| 5398 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5399 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5400 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5401 | |
| 5402 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5403 | } |
| 5404 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5405 | /// computeExitLimitFromCond - Compute the number of times the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5406 | /// backedge of the specified loop will execute if its exit condition |
| 5407 | /// were a conditional branch of ExitCond, TBB, and FBB. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5408 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5409 | /// @param ControlsExit is true if ExitCond directly controls the exit |
| 5410 | /// branch. In this case, we can assume that the loop exits only if the |
| 5411 | /// condition is true and can infer that failing to meet the condition prior to |
| 5412 | /// integer wraparound results in undefined behavior. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5413 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5414 | ScalarEvolution::computeExitLimitFromCond(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5415 | Value *ExitCond, |
| 5416 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5417 | BasicBlock *FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5418 | bool ControlsExit) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5419 | // 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] | 5420 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5421 | if (BO->getOpcode() == Instruction::And) { |
| 5422 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5423 | bool EitherMayExit = L->contains(TBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5424 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5425 | ControlsExit && !EitherMayExit); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5426 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5427 | ControlsExit && !EitherMayExit); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5428 | const SCEV *BECount = getCouldNotCompute(); |
| 5429 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5430 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5431 | // Both conditions must be true for the loop to continue executing. |
| 5432 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5433 | if (EL0.Exact == getCouldNotCompute() || |
| 5434 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5435 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5436 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5437 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5438 | if (EL0.Max == getCouldNotCompute()) |
| 5439 | MaxBECount = EL1.Max; |
| 5440 | else if (EL1.Max == getCouldNotCompute()) |
| 5441 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5442 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5443 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5444 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5445 | // Both conditions must be true at the same time for the loop to exit. |
| 5446 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5447 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5448 | if (EL0.Max == EL1.Max) |
| 5449 | MaxBECount = EL0.Max; |
| 5450 | if (EL0.Exact == EL1.Exact) |
| 5451 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5452 | } |
| 5453 | |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5454 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able |
| 5455 | // to be more aggressive when computing BECount than when computing |
| 5456 | // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact |
| 5457 | // to match, but for EL0.Max and EL1.Max to not. |
| 5458 | if (isa<SCEVCouldNotCompute>(MaxBECount) && |
| 5459 | !isa<SCEVCouldNotCompute>(BECount)) |
| 5460 | MaxBECount = BECount; |
| 5461 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5462 | return ExitLimit(BECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5463 | } |
| 5464 | if (BO->getOpcode() == Instruction::Or) { |
| 5465 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5466 | bool EitherMayExit = L->contains(FBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5467 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5468 | ControlsExit && !EitherMayExit); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5469 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5470 | ControlsExit && !EitherMayExit); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5471 | const SCEV *BECount = getCouldNotCompute(); |
| 5472 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5473 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5474 | // Both conditions must be false for the loop to continue executing. |
| 5475 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5476 | if (EL0.Exact == getCouldNotCompute() || |
| 5477 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5478 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5479 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5480 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5481 | if (EL0.Max == getCouldNotCompute()) |
| 5482 | MaxBECount = EL1.Max; |
| 5483 | else if (EL1.Max == getCouldNotCompute()) |
| 5484 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5485 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5486 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5487 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5488 | // Both conditions must be false at the same time for the loop to exit. |
| 5489 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5490 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5491 | if (EL0.Max == EL1.Max) |
| 5492 | MaxBECount = EL0.Max; |
| 5493 | if (EL0.Exact == EL1.Exact) |
| 5494 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5495 | } |
| 5496 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5497 | return ExitLimit(BECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5498 | } |
| 5499 | } |
| 5500 | |
| 5501 | // 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] | 5502 | // Proceed to the next level to examine the icmp. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5503 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5504 | return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5505 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5506 | // Check for a constant condition. These are normally stripped out by |
| 5507 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 5508 | // preserve the CFG and is temporarily leaving constant conditions |
| 5509 | // in place. |
| 5510 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 5511 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 5512 | // The backedge is always taken. |
| 5513 | return getCouldNotCompute(); |
| 5514 | else |
| 5515 | // The backedge is never taken. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5516 | return getZero(CI->getType()); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5517 | } |
| 5518 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5519 | // 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] | 5520 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5521 | } |
| 5522 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5523 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5524 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5525 | ICmpInst *ExitCond, |
| 5526 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5527 | BasicBlock *FBB, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5528 | bool ControlsExit) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5529 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5530 | // If the condition was exit on true, convert the condition to exit on false |
| 5531 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5532 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5533 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5534 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5535 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5536 | |
| 5537 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 5538 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 5539 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5540 | ExitLimit ItCnt = |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5541 | computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 5542 | if (ItCnt.hasAnyInfo()) |
| 5543 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5544 | } |
| 5545 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 5546 | ExitLimit ShiftEL = computeShiftCompareExitLimit( |
| 5547 | ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond); |
| 5548 | if (ShiftEL.hasAnyInfo()) |
| 5549 | return ShiftEL; |
| 5550 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5551 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 5552 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5553 | |
| 5554 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5555 | LHS = getSCEVAtScope(LHS, L); |
| 5556 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5557 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5558 | // 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] | 5559 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5560 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 5561 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5562 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5563 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5564 | } |
| 5565 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 5566 | // Simplify the operands before analyzing them. |
| 5567 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 5568 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5569 | // If we have a comparison of a chrec against a constant, try to use value |
| 5570 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5571 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 5572 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5573 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5574 | // Form the constant range. |
| 5575 | ConstantRange CompRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 5576 | ICmpInst::makeConstantRange(Cond, RHSC->getAPInt())); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5577 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5578 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5579 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5580 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5581 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5582 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5583 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5584 | // Convert to: while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5585 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5586 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5587 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5588 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 5589 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 5590 | // Convert to: while (X-Y == 0) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5591 | ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); |
| 5592 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5593 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5594 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5595 | case ICmpInst::ICMP_SLT: |
| 5596 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 5597 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5598 | ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5599 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5600 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5601 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5602 | case ICmpInst::ICMP_SGT: |
| 5603 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 5604 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5605 | ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5606 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5607 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5608 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5609 | default: |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 5610 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5611 | } |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5612 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5613 | } |
| 5614 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5615 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5616 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5617 | SwitchInst *Switch, |
| 5618 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5619 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5620 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 5621 | |
| 5622 | // Give up if the exit is the default dest of a switch. |
| 5623 | if (Switch->getDefaultDest() == ExitingBlock) |
| 5624 | return getCouldNotCompute(); |
| 5625 | |
| 5626 | assert(L->contains(Switch->getDefaultDest()) && |
| 5627 | "Default case must not exit the loop!"); |
| 5628 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 5629 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 5630 | |
| 5631 | // while (X != Y) --> while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5632 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5633 | if (EL.hasAnyInfo()) |
| 5634 | return EL; |
| 5635 | |
| 5636 | return getCouldNotCompute(); |
| 5637 | } |
| 5638 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5639 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 5640 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 5641 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5642 | const SCEV *InVal = SE.getConstant(C); |
| 5643 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5644 | assert(isa<SCEVConstant>(Val) && |
| 5645 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 5646 | return cast<SCEVConstant>(Val)->getValue(); |
| 5647 | } |
| 5648 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5649 | /// computeLoadConstantCompareExitLimit - Given an exit condition of |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5650 | /// 'icmp op load X, cst', try to see if we can compute the backedge |
| 5651 | /// execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5652 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5653 | ScalarEvolution::computeLoadConstantCompareExitLimit( |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5654 | LoadInst *LI, |
| 5655 | Constant *RHS, |
| 5656 | const Loop *L, |
| 5657 | ICmpInst::Predicate predicate) { |
| 5658 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5659 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5660 | |
| 5661 | // 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] | 5662 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5663 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5664 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5665 | |
| 5666 | // Make sure that it is really a constant global we are gepping, with an |
| 5667 | // initializer, and make sure the first IDX is really 0. |
| 5668 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 5669 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5670 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 5671 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5672 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5673 | |
| 5674 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5675 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 5676 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5677 | unsigned VarIdxNum = 0; |
| 5678 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 5679 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 5680 | Indexes.push_back(CI); |
| 5681 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5682 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5683 | VarIdx = GEP->getOperand(i); |
| 5684 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5685 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5686 | } |
| 5687 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 5688 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 5689 | if (!VarIdx) |
| 5690 | return getCouldNotCompute(); |
| 5691 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5692 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 5693 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5694 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5695 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5696 | |
| 5697 | // We can only recognize very limited forms of loop index expressions, in |
| 5698 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5699 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5700 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5701 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 5702 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5703 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5704 | |
| 5705 | unsigned MaxSteps = MaxBruteForceIterations; |
| 5706 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5707 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 5708 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5709 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5710 | |
| 5711 | // Form the GEP offset. |
| 5712 | Indexes[VarIdxNum] = Val; |
| 5713 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 5714 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 5715 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5716 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5717 | |
| 5718 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5719 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 5720 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 5721 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5722 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5723 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5724 | } |
| 5725 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5726 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5727 | } |
| 5728 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 5729 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( |
| 5730 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { |
| 5731 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); |
| 5732 | if (!RHS) |
| 5733 | return getCouldNotCompute(); |
| 5734 | |
| 5735 | const BasicBlock *Latch = L->getLoopLatch(); |
| 5736 | if (!Latch) |
| 5737 | return getCouldNotCompute(); |
| 5738 | |
| 5739 | const BasicBlock *Predecessor = L->getLoopPredecessor(); |
| 5740 | if (!Predecessor) |
| 5741 | return getCouldNotCompute(); |
| 5742 | |
| 5743 | // Return true if V is of the form "LHS `shift_op` <positive constant>". |
| 5744 | // Return LHS in OutLHS and shift_opt in OutOpCode. |
| 5745 | auto MatchPositiveShift = |
| 5746 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { |
| 5747 | |
| 5748 | using namespace PatternMatch; |
| 5749 | |
| 5750 | ConstantInt *ShiftAmt; |
| 5751 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 5752 | OutOpCode = Instruction::LShr; |
| 5753 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 5754 | OutOpCode = Instruction::AShr; |
| 5755 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 5756 | OutOpCode = Instruction::Shl; |
| 5757 | else |
| 5758 | return false; |
| 5759 | |
| 5760 | return ShiftAmt->getValue().isStrictlyPositive(); |
| 5761 | }; |
| 5762 | |
| 5763 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in |
| 5764 | // |
| 5765 | // loop: |
| 5766 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] |
| 5767 | // %iv.shifted = lshr i32 %iv, <positive constant> |
| 5768 | // |
| 5769 | // Return true on a succesful match. Return the corresponding PHI node (%iv |
| 5770 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. |
| 5771 | auto MatchShiftRecurrence = |
| 5772 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { |
| 5773 | Optional<Instruction::BinaryOps> PostShiftOpCode; |
| 5774 | |
| 5775 | { |
| 5776 | Instruction::BinaryOps OpC; |
| 5777 | Value *V; |
| 5778 | |
| 5779 | // If we encounter a shift instruction, "peel off" the shift operation, |
| 5780 | // and remember that we did so. Later when we inspect %iv's backedge |
| 5781 | // value, we will make sure that the backedge value uses the same |
| 5782 | // operation. |
| 5783 | // |
| 5784 | // Note: the peeled shift operation does not have to be the same |
| 5785 | // instruction as the one feeding into the PHI's backedge value. We only |
| 5786 | // really care about it being the same *kind* of shift instruction -- |
| 5787 | // that's all that is required for our later inferences to hold. |
| 5788 | if (MatchPositiveShift(LHS, V, OpC)) { |
| 5789 | PostShiftOpCode = OpC; |
| 5790 | LHS = V; |
| 5791 | } |
| 5792 | } |
| 5793 | |
| 5794 | PNOut = dyn_cast<PHINode>(LHS); |
| 5795 | if (!PNOut || PNOut->getParent() != L->getHeader()) |
| 5796 | return false; |
| 5797 | |
| 5798 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); |
| 5799 | Value *OpLHS; |
| 5800 | |
| 5801 | return |
| 5802 | // The backedge value for the PHI node must be a shift by a positive |
| 5803 | // amount |
| 5804 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && |
| 5805 | |
| 5806 | // of the PHI node itself |
| 5807 | OpLHS == PNOut && |
| 5808 | |
| 5809 | // and the kind of shift should be match the kind of shift we peeled |
| 5810 | // off, if any. |
| 5811 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); |
| 5812 | }; |
| 5813 | |
| 5814 | PHINode *PN; |
| 5815 | Instruction::BinaryOps OpCode; |
| 5816 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) |
| 5817 | return getCouldNotCompute(); |
| 5818 | |
| 5819 | const DataLayout &DL = getDataLayout(); |
| 5820 | |
| 5821 | // The key rationale for this optimization is that for some kinds of shift |
| 5822 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 |
| 5823 | // within a finite number of iterations. If the condition guarding the |
| 5824 | // backedge (in the sense that the backedge is taken if the condition is true) |
| 5825 | // is false for the value the shift recurrence stabilizes to, then we know |
| 5826 | // that the backedge is taken only a finite number of times. |
| 5827 | |
| 5828 | ConstantInt *StableValue = nullptr; |
| 5829 | switch (OpCode) { |
| 5830 | default: |
| 5831 | llvm_unreachable("Impossible case!"); |
| 5832 | |
| 5833 | case Instruction::AShr: { |
| 5834 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most |
| 5835 | // bitwidth(K) iterations. |
| 5836 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); |
| 5837 | bool KnownZero, KnownOne; |
| 5838 | ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, |
| 5839 | Predecessor->getTerminator(), &DT); |
| 5840 | auto *Ty = cast<IntegerType>(RHS->getType()); |
| 5841 | if (KnownZero) |
| 5842 | StableValue = ConstantInt::get(Ty, 0); |
| 5843 | else if (KnownOne) |
| 5844 | StableValue = ConstantInt::get(Ty, -1, true); |
| 5845 | else |
| 5846 | return getCouldNotCompute(); |
| 5847 | |
| 5848 | break; |
| 5849 | } |
| 5850 | case Instruction::LShr: |
| 5851 | case Instruction::Shl: |
| 5852 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} |
| 5853 | // stabilize to 0 in at most bitwidth(K) iterations. |
| 5854 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); |
| 5855 | break; |
| 5856 | } |
| 5857 | |
| 5858 | auto *Result = |
| 5859 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); |
| 5860 | assert(Result->getType()->isIntegerTy(1) && |
| 5861 | "Otherwise cannot be an operand to a branch instruction"); |
| 5862 | |
| 5863 | if (Result->isZeroValue()) { |
| 5864 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 5865 | const SCEV *UpperBound = |
| 5866 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); |
| 5867 | return ExitLimit(getCouldNotCompute(), UpperBound); |
| 5868 | } |
| 5869 | |
| 5870 | return getCouldNotCompute(); |
| 5871 | } |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5872 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5873 | /// CanConstantFold - Return true if we can constant fold an instruction of the |
| 5874 | /// specified type, assuming that all operands were constants. |
| 5875 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 5876 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5877 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 5878 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5879 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5880 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5881 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 5882 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 5883 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5884 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5885 | } |
| 5886 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5887 | /// Determine whether this instruction can constant evolve within this loop |
| 5888 | /// assuming its operands can all constant evolve. |
| 5889 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 5890 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 5891 | if (!L->contains(I)) return false; |
| 5892 | |
| 5893 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 5894 | // We don't currently keep track of the control flow needed to evaluate |
| 5895 | // PHIs, so we cannot handle PHIs inside of loops. |
| 5896 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5897 | } |
| 5898 | |
| 5899 | // If we won't be able to constant fold this expression even if the operands |
| 5900 | // are constants, bail early. |
| 5901 | return CanConstantFold(I); |
| 5902 | } |
| 5903 | |
| 5904 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 5905 | /// recursing through each instruction operand until reaching a loop header phi. |
| 5906 | static PHINode * |
| 5907 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5908 | DenseMap<Instruction *, PHINode *> &PHIMap) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5909 | |
| 5910 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 5911 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5912 | PHINode *PHI = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 5913 | for (Value *Op : UseInst->operands()) { |
| 5914 | if (isa<Constant>(Op)) continue; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5915 | |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 5916 | Instruction *OpInst = dyn_cast<Instruction>(Op); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5917 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5918 | |
| 5919 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 5920 | if (!P) |
| 5921 | // If this operand is already visited, reuse the prior result. |
| 5922 | // We may have P != PHI if this is the deepest point at which the |
| 5923 | // inconsistent paths meet. |
| 5924 | P = PHIMap.lookup(OpInst); |
| 5925 | if (!P) { |
| 5926 | // Recurse and memoize the results, whether a phi is found or not. |
| 5927 | // This recursive call invalidates pointers into PHIMap. |
| 5928 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); |
| 5929 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5930 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5931 | if (!P) |
| 5932 | return nullptr; // Not evolving from PHI |
| 5933 | if (PHI && PHI != P) |
| 5934 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5935 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5936 | } |
| 5937 | // This is a expression evolving from a constant PHI! |
| 5938 | return PHI; |
| 5939 | } |
| 5940 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5941 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 5942 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 5943 | /// way, but the operands of an operation must either be constants or a value |
| 5944 | /// derived from a constant PHI. If this expression does not fit with these |
| 5945 | /// constraints, return null. |
| 5946 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5947 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5948 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5949 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 5950 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5951 | return PN; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5952 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5953 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5954 | DenseMap<Instruction *, PHINode *> PHIMap; |
| 5955 | return getConstantEvolvingPHIOperands(I, L, PHIMap); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5956 | } |
| 5957 | |
| 5958 | /// EvaluateExpression - Given an expression that passes the |
| 5959 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 5960 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 5961 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5962 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 5963 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5964 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 5965 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5966 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 5967 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5968 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5969 | if (!I) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5970 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 5971 | if (Constant *C = Vals.lookup(I)) return C; |
| 5972 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5973 | // An instruction inside the loop depends on a value outside the loop that we |
| 5974 | // 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] | 5975 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5976 | |
| 5977 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 5978 | // or due to this not being the initial iteration through a loop where we |
| 5979 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5980 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5981 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 5982 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5983 | |
| 5984 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5985 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 5986 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 5987 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5988 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5989 | continue; |
| 5990 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5991 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5992 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5993 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 5994 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 5995 | } |
| 5996 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 5997 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 5998 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 5999 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6000 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6001 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6002 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6003 | } |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6004 | return ConstantFoldInstOperands(I, Operands, DL, TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6005 | } |
| 6006 | |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6007 | |
| 6008 | // If every incoming value to PN except the one for BB is a specific Constant, |
| 6009 | // return that, else return nullptr. |
| 6010 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { |
| 6011 | Constant *IncomingVal = nullptr; |
| 6012 | |
| 6013 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 6014 | if (PN->getIncomingBlock(i) == BB) |
| 6015 | continue; |
| 6016 | |
| 6017 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 6018 | if (!CurrentVal) |
| 6019 | return nullptr; |
| 6020 | |
| 6021 | if (IncomingVal != CurrentVal) { |
| 6022 | if (IncomingVal) |
| 6023 | return nullptr; |
| 6024 | IncomingVal = CurrentVal; |
| 6025 | } |
| 6026 | } |
| 6027 | |
| 6028 | return IncomingVal; |
| 6029 | } |
| 6030 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6031 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 6032 | /// in the header of its containing loop, we know the loop executes a |
| 6033 | /// constant number of times, and the PHI node is just a recurrence |
| 6034 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6035 | Constant * |
| 6036 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 6037 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6038 | const Loop *L) { |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6039 | auto I = ConstantEvolutionLoopExitValue.find(PN); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6040 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 6041 | return I->second; |
| 6042 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 6043 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6044 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6045 | |
| 6046 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 6047 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6048 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6049 | BasicBlock *Header = L->getHeader(); |
| 6050 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6051 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6052 | BasicBlock *Latch = L->getLoopLatch(); |
| 6053 | if (!Latch) |
| 6054 | return nullptr; |
| 6055 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6056 | for (auto &I : *Header) { |
| 6057 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6058 | if (!PHI) break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6059 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6060 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6061 | CurrentIterVals[PHI] = StartCST; |
| 6062 | } |
| 6063 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6064 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6065 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6066 | Value *BEValue = PN->getIncomingValueForBlock(Latch); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6067 | |
| 6068 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6069 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6070 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6071 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6072 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6073 | unsigned IterationNum = 0; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6074 | const DataLayout &DL = getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6075 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6076 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6077 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6078 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6079 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6080 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6081 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6082 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6083 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6084 | if (!NextPHI) |
| 6085 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6086 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6087 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6088 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 6089 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6090 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 6091 | // cease to be able to evaluate one of them or if they stop evolving, |
| 6092 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6093 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6094 | for (const auto &I : CurrentIterVals) { |
| 6095 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 6096 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6097 | PHIsToCompute.emplace_back(PHI, I.second); |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6098 | } |
| 6099 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 6100 | // iterators into CurrentIterVals. |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6101 | for (const auto &I : PHIsToCompute) { |
| 6102 | PHINode *PHI = I.first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6103 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6104 | if (!NextPHI) { // Not already computed. |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6105 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6106 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6107 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6108 | if (NextPHI != I.second) |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6109 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6110 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6111 | |
| 6112 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 6113 | // iterating, the loop can't continue to change. |
| 6114 | if (StoppedEvolving) |
| 6115 | return RetVal = CurrentIterVals[PN]; |
| 6116 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6117 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6118 | } |
| 6119 | } |
| 6120 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6121 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6122 | Value *Cond, |
| 6123 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6124 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6125 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6126 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 6127 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 6128 | // That's the only form we support here. |
| 6129 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 6130 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6131 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 6132 | BasicBlock *Header = L->getHeader(); |
| 6133 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 6134 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6135 | BasicBlock *Latch = L->getLoopLatch(); |
| 6136 | assert(Latch && "Should follow from NumIncomingValues == 2!"); |
| 6137 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6138 | for (auto &I : *Header) { |
| 6139 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6140 | if (!PHI) |
| 6141 | break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6142 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6143 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6144 | CurrentIterVals[PHI] = StartCST; |
| 6145 | } |
| 6146 | if (!CurrentIterVals.count(PN)) |
| 6147 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6148 | |
| 6149 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 6150 | // the loop symbolically to determine when the condition gets a value of |
| 6151 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 6152 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6153 | const DataLayout &DL = getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6154 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6155 | auto *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6156 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6157 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6158 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6159 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6160 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6161 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6162 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 6163 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6164 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6165 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6166 | // Update all the PHI nodes for the next iteration. |
| 6167 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6168 | |
| 6169 | // Create a list of which PHIs we need to compute. We want to do this before |
| 6170 | // calling EvaluateExpression on them because that may invalidate iterators |
| 6171 | // into CurrentIterVals. |
| 6172 | SmallVector<PHINode *, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6173 | for (const auto &I : CurrentIterVals) { |
| 6174 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6175 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6176 | PHIsToCompute.push_back(PHI); |
| 6177 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6178 | for (PHINode *PHI : PHIsToCompute) { |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6179 | Constant *&NextPHI = NextIterVals[PHI]; |
| 6180 | if (NextPHI) continue; // Already computed! |
| 6181 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6182 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6183 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6184 | } |
| 6185 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6186 | } |
| 6187 | |
| 6188 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6189 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6190 | } |
| 6191 | |
Dan Gohman | 237d9e5 | 2009-09-03 15:00:26 +0000 | [diff] [blame] | 6192 | /// getSCEVAtScope - Return a SCEV expression for the specified value |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6193 | /// at the specified scope in the program. The L value specifies a loop |
| 6194 | /// nest to evaluate the expression at, where null is the top-level or a |
| 6195 | /// specified loop is immediately inside of the loop. |
| 6196 | /// |
| 6197 | /// This method can be used to compute the exit value for a variable defined |
| 6198 | /// in a loop by querying what the value will hold in the parent loop. |
| 6199 | /// |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6200 | /// In the case that a relevant loop exit value cannot be computed, the |
| 6201 | /// original value V is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6202 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6203 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = |
| 6204 | ValuesAtScopes[V]; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6205 | // 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] | 6206 | for (auto &LS : Values) |
| 6207 | if (LS.first == L) |
| 6208 | return LS.second ? LS.second : V; |
| 6209 | |
| 6210 | Values.emplace_back(L, nullptr); |
| 6211 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6212 | // Otherwise compute it. |
| 6213 | const SCEV *C = computeSCEVAtScope(V, L); |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6214 | for (auto &LS : reverse(ValuesAtScopes[V])) |
| 6215 | if (LS.first == L) { |
| 6216 | LS.second = C; |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 6217 | break; |
| 6218 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6219 | return C; |
| 6220 | } |
| 6221 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6222 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 6223 | /// will return Constants for objects which aren't represented by a |
| 6224 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 6225 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 6226 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6227 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6228 | case scCouldNotCompute: |
| 6229 | case scAddRecExpr: |
| 6230 | break; |
| 6231 | case scConstant: |
| 6232 | return cast<SCEVConstant>(V)->getValue(); |
| 6233 | case scUnknown: |
| 6234 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 6235 | case scSignExtend: { |
| 6236 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 6237 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 6238 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 6239 | break; |
| 6240 | } |
| 6241 | case scZeroExtend: { |
| 6242 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 6243 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 6244 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 6245 | break; |
| 6246 | } |
| 6247 | case scTruncate: { |
| 6248 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 6249 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 6250 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 6251 | break; |
| 6252 | } |
| 6253 | case scAddExpr: { |
| 6254 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 6255 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6256 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6257 | unsigned AS = PTy->getAddressSpace(); |
| 6258 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 6259 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 6260 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6261 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 6262 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6263 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6264 | |
| 6265 | // First pointer! |
| 6266 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6267 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6268 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6269 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6270 | // The offsets have been converted to bytes. We can add bytes to an |
| 6271 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6272 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6273 | } |
| 6274 | |
| 6275 | // Don't bother trying to sum two pointers. We probably can't |
| 6276 | // statically compute a load that results from it anyway. |
| 6277 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6278 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6279 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6280 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6281 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6282 | C2 = ConstantExpr::getIntegerCast( |
| 6283 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 6284 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6285 | } else |
| 6286 | C = ConstantExpr::getAdd(C, C2); |
| 6287 | } |
| 6288 | return C; |
| 6289 | } |
| 6290 | break; |
| 6291 | } |
| 6292 | case scMulExpr: { |
| 6293 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 6294 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 6295 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6296 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6297 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 6298 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6299 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6300 | C = ConstantExpr::getMul(C, C2); |
| 6301 | } |
| 6302 | return C; |
| 6303 | } |
| 6304 | break; |
| 6305 | } |
| 6306 | case scUDivExpr: { |
| 6307 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 6308 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 6309 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 6310 | if (LHS->getType() == RHS->getType()) |
| 6311 | return ConstantExpr::getUDiv(LHS, RHS); |
| 6312 | break; |
| 6313 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6314 | case scSMaxExpr: |
| 6315 | case scUMaxExpr: |
| 6316 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6317 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6318 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6319 | } |
| 6320 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6321 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6322 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6323 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6324 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6325 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6326 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6327 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6328 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6329 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 6330 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 6331 | if (PN->getParent() == LI->getHeader()) { |
| 6332 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6333 | // to see if the loop that contains it has a known backedge-taken |
| 6334 | // count. If so, we may be able to force computation of the exit |
| 6335 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6336 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6337 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6338 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6339 | // Okay, we know how many times the containing loop executes. If |
| 6340 | // this is a constant evolving PHI node, get the final value at |
| 6341 | // the specified iteration number. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6342 | Constant *RV = |
| 6343 | getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 6344 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6345 | } |
| 6346 | } |
| 6347 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6348 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6349 | // 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] | 6350 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6351 | // result. This is particularly useful for computing loop exit values. |
| 6352 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6353 | SmallVector<Constant *, 4> Operands; |
| 6354 | bool MadeImprovement = false; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 6355 | for (Value *Op : I->operands()) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6356 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 6357 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6358 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6359 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6360 | |
| 6361 | // If any of the operands is non-constant and if they are |
| 6362 | // non-integer and non-pointer, don't even try to analyze them |
| 6363 | // with scev techniques. |
| 6364 | if (!isSCEVable(Op->getType())) |
| 6365 | return V; |
| 6366 | |
| 6367 | const SCEV *OrigV = getSCEV(Op); |
| 6368 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 6369 | MadeImprovement |= OrigV != OpV; |
| 6370 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6371 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6372 | if (!C) return V; |
| 6373 | if (C->getType() != Op->getType()) |
| 6374 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 6375 | Op->getType(), |
| 6376 | false), |
| 6377 | C, Op->getType()); |
| 6378 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6379 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6380 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6381 | // Check to see if getSCEVAtScope actually made an improvement. |
| 6382 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6383 | Constant *C = nullptr; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6384 | const DataLayout &DL = getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6385 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6386 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6387 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6388 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6389 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6390 | C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6391 | } else |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6392 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6393 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 6394 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6395 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6396 | } |
| 6397 | } |
| 6398 | |
| 6399 | // This is some other type of SCEVUnknown, just return it. |
| 6400 | return V; |
| 6401 | } |
| 6402 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6403 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6404 | // Avoid performing the look-up in the common case where the specified |
| 6405 | // expression has no loop-variant portions. |
| 6406 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6407 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6408 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6409 | // Okay, at least one of these operands is loop variant but might be |
| 6410 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6411 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 6412 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6413 | NewOps.push_back(OpAtScope); |
| 6414 | |
| 6415 | for (++i; i != e; ++i) { |
| 6416 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6417 | NewOps.push_back(OpAtScope); |
| 6418 | } |
| 6419 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6420 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6421 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6422 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6423 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6424 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6425 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6426 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6427 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6428 | } |
| 6429 | } |
| 6430 | // If we got here, all operands are loop invariant. |
| 6431 | return Comm; |
| 6432 | } |
| 6433 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6434 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6435 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 6436 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 6437 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 6438 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6439 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6440 | } |
| 6441 | |
| 6442 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6443 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6444 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6445 | // First, attempt to evaluate each operand. |
| 6446 | // Avoid performing the look-up in the common case where the specified |
| 6447 | // expression has no loop-variant portions. |
| 6448 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6449 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6450 | if (OpAtScope == AddRec->getOperand(i)) |
| 6451 | continue; |
| 6452 | |
| 6453 | // Okay, at least one of these operands is loop variant but might be |
| 6454 | // foldable. Build a new instance of the folded commutative expression. |
| 6455 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6456 | AddRec->op_begin()+i); |
| 6457 | NewOps.push_back(OpAtScope); |
| 6458 | for (++i; i != e; ++i) |
| 6459 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6460 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6461 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6462 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6463 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6464 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6465 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6466 | // induction variable is multiplied by zero after constant folding. Go |
| 6467 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6468 | if (!AddRec) |
| 6469 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6470 | break; |
| 6471 | } |
| 6472 | |
| 6473 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6474 | // loop exit value of the addrec. |
| 6475 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6476 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6477 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6478 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6479 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6480 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6481 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6482 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6483 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6484 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6485 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6486 | } |
| 6487 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6488 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6489 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6490 | if (Op == Cast->getOperand()) |
| 6491 | return Cast; // must be loop invariant |
| 6492 | return getZeroExtendExpr(Op, Cast->getType()); |
| 6493 | } |
| 6494 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6495 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6496 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6497 | if (Op == Cast->getOperand()) |
| 6498 | return Cast; // must be loop invariant |
| 6499 | return getSignExtendExpr(Op, Cast->getType()); |
| 6500 | } |
| 6501 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6502 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6503 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6504 | if (Op == Cast->getOperand()) |
| 6505 | return Cast; // must be loop invariant |
| 6506 | return getTruncateExpr(Op, Cast->getType()); |
| 6507 | } |
| 6508 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6509 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6510 | } |
| 6511 | |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6512 | /// getSCEVAtScope - This is a convenience function which does |
| 6513 | /// getSCEVAtScope(getSCEV(V), L). |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6514 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6515 | return getSCEVAtScope(getSCEV(V), L); |
| 6516 | } |
| 6517 | |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6518 | /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the |
| 6519 | /// following equation: |
| 6520 | /// |
| 6521 | /// A * X = B (mod N) |
| 6522 | /// |
| 6523 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 6524 | /// A and B isn't important. |
| 6525 | /// |
| 6526 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6527 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6528 | ScalarEvolution &SE) { |
| 6529 | uint32_t BW = A.getBitWidth(); |
| 6530 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 6531 | assert(A != 0 && "A must be non-zero."); |
| 6532 | |
| 6533 | // 1. D = gcd(A, N) |
| 6534 | // |
| 6535 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 6536 | // trailing zeros in A is its multiplicity |
| 6537 | uint32_t Mult2 = A.countTrailingZeros(); |
| 6538 | // D = 2^Mult2 |
| 6539 | |
| 6540 | // 2. Check if B is divisible by D. |
| 6541 | // |
| 6542 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 6543 | // is not less than multiplicity of this prime factor for D. |
| 6544 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 6545 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6546 | |
| 6547 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 6548 | // modulo (N / D). |
| 6549 | // |
| 6550 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 6551 | // bit width during computations. |
| 6552 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 6553 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 6554 | Mod.setBit(BW - Mult2); // Mod = N / D |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6555 | APInt I = AD.multiplicativeInverse(Mod); |
| 6556 | |
| 6557 | // 4. Compute the minimum unsigned root of the equation: |
| 6558 | // I * (B / D) mod (N / D) |
| 6559 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 6560 | |
| 6561 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 6562 | // bits. |
| 6563 | return SE.getConstant(Result.trunc(BW)); |
| 6564 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6565 | |
| 6566 | /// SolveQuadraticEquation - Find the roots of the quadratic equation for the |
| 6567 | /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which |
| 6568 | /// might be the same) or two SCEVCouldNotCompute objects. |
| 6569 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6570 | static std::pair<const SCEV *,const SCEV *> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6571 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6572 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6573 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 6574 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 6575 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6576 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6577 | // We currently can only solve this if the coefficients are constants. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6578 | if (!LC || !MC || !NC) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6579 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6580 | return {CNC, CNC}; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6581 | } |
| 6582 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6583 | uint32_t BitWidth = LC->getAPInt().getBitWidth(); |
| 6584 | const APInt &L = LC->getAPInt(); |
| 6585 | const APInt &M = MC->getAPInt(); |
| 6586 | const APInt &N = NC->getAPInt(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6587 | APInt Two(BitWidth, 2); |
| 6588 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6589 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6590 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6591 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6592 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6593 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 6594 | // The B coefficient is M-N/2 |
| 6595 | APInt B(M); |
| 6596 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6597 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6598 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6599 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6600 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6601 | // Compute the B^2-4ac term. |
| 6602 | APInt SqrtTerm(B); |
| 6603 | SqrtTerm *= B; |
| 6604 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6605 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6606 | if (SqrtTerm.isNegative()) { |
| 6607 | // The loop is provably infinite. |
| 6608 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6609 | return {CNC, CNC}; |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6610 | } |
| 6611 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6612 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 6613 | // integer value or else APInt::sqrt() will assert. |
| 6614 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6615 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6616 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6617 | // The divisions must be performed as signed divisions. |
| 6618 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6619 | APInt TwoA(A << 1); |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6620 | if (TwoA.isMinValue()) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6621 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6622 | return {CNC, CNC}; |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6623 | } |
| 6624 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 6625 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6626 | |
| 6627 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6628 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6629 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6630 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6631 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6632 | return {SE.getConstant(Solution1), SE.getConstant(Solution2)}; |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6633 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6634 | } |
| 6635 | |
| 6636 | /// HowFarToZero - Return the number of times a backedge comparing the specified |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 6637 | /// value to zero will execute. If not computable, return CouldNotCompute. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6638 | /// |
| 6639 | /// This is only used for loops with a "x != y" exit test. The exit condition is |
| 6640 | /// now expressed as a single expression, V = x-y. So the exit test is |
| 6641 | /// effectively V != 0. We know and take advantage of the fact that this |
| 6642 | /// expression only being used in a comparison by zero context. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6643 | ScalarEvolution::ExitLimit |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6644 | ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6645 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6646 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6647 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 6648 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6649 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6650 | } |
| 6651 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6652 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6653 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6654 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6655 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6656 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 6657 | // the quadratic equation to solve it. |
| 6658 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
| 6659 | std::pair<const SCEV *,const SCEV *> Roots = |
| 6660 | SolveQuadraticEquation(AddRec, *this); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6661 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 6662 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6663 | if (R1 && R2) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6664 | // Pick the smallest positive root value. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6665 | if (ConstantInt *CB = |
Chris Lattner | 28f140a | 2011-01-09 22:58:47 +0000 | [diff] [blame] | 6666 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, |
| 6667 | R1->getValue(), |
| 6668 | R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6669 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6670 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 6671 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6672 | // We can only use this value if the chrec ends up with an exact zero |
| 6673 | // value at this index. When solving for "X*X != 5", for example, we |
| 6674 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6675 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 6676 | if (Val->isZero()) |
| 6677 | return R1; // We found a quadratic root! |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6678 | } |
| 6679 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6680 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6681 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6682 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6683 | // Otherwise we can only handle this if it is affine. |
| 6684 | if (!AddRec->isAffine()) |
| 6685 | return getCouldNotCompute(); |
| 6686 | |
| 6687 | // If this is an affine expression, the execution count of this branch is |
| 6688 | // the minimum unsigned root of the following equation: |
| 6689 | // |
| 6690 | // Start + Step*N = 0 (mod 2^BW) |
| 6691 | // |
| 6692 | // equivalent to: |
| 6693 | // |
| 6694 | // Step*N = -Start (mod 2^BW) |
| 6695 | // |
| 6696 | // where BW is the common bit width of Start and Step. |
| 6697 | |
| 6698 | // Get the initial value for the loop. |
| 6699 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 6700 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 6701 | |
| 6702 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6703 | // |
| 6704 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 6705 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 6706 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 6707 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6708 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6709 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6710 | return getCouldNotCompute(); |
| 6711 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6712 | // For positive steps (counting up until unsigned overflow): |
| 6713 | // N = -Start/Step (as unsigned) |
| 6714 | // For negative steps (counting down to zero): |
| 6715 | // N = Start/-Step |
| 6716 | // First compute the unsigned distance from zero in the direction of Step. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6717 | bool CountDown = StepC->getAPInt().isNegative(); |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 6718 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6719 | |
| 6720 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 6721 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 6722 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6723 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
| 6724 | ConstantRange CR = getUnsignedRange(Start); |
| 6725 | const SCEV *MaxBECount; |
| 6726 | if (!CountDown && CR.getUnsignedMin().isMinValue()) |
| 6727 | // When counting up, the worst starting value is 1, not 0. |
| 6728 | MaxBECount = CR.getUnsignedMax().isMinValue() |
| 6729 | ? getConstant(APInt::getMinValue(CR.getBitWidth())) |
| 6730 | : getConstant(APInt::getMaxValue(CR.getBitWidth())); |
| 6731 | else |
| 6732 | MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() |
| 6733 | : -CR.getUnsignedMin()); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6734 | return ExitLimit(Distance, MaxBECount); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6735 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 6736 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6737 | // As a special case, handle the instance where Step is a positive power of |
| 6738 | // two. In this case, determining whether Step divides Distance evenly can be |
| 6739 | // done by counting and comparing the number of trailing zeros of Step and |
| 6740 | // Distance. |
| 6741 | if (!CountDown) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6742 | const APInt &StepV = StepC->getAPInt(); |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6743 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 6744 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 6745 | // case is not handled as this code is guarded by !CountDown. |
| 6746 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 6747 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 6748 | // Here we've constrained the equation to be of the form |
| 6749 | // |
| 6750 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 6751 | // |
| 6752 | // where we're operating on a W bit wide integer domain and k is |
| 6753 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 6754 | // |
| 6755 | // (0) is equivalent to: |
| 6756 | // |
| 6757 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 6758 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 6759 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 6760 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 6761 | // |
| 6762 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 6763 | // by 2^(W - N). |
| 6764 | // |
| 6765 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 6766 | // |
| 6767 | // E.g. say we're solving |
| 6768 | // |
| 6769 | // 2 * Val = 2 * X (in i8) ... (3) |
| 6770 | // |
| 6771 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 6772 | // |
| 6773 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 6774 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 6775 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 6776 | // is i8 1, not i8 -127 |
| 6777 | |
| 6778 | const auto *ModuloResult = getUDivExactExpr(Distance, Step); |
| 6779 | |
| 6780 | // Since SCEV does not have a URem node, we construct one using a truncate |
| 6781 | // and a zero extend. |
| 6782 | |
| 6783 | unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); |
| 6784 | auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); |
| 6785 | auto *WideTy = Distance->getType(); |
| 6786 | |
| 6787 | return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); |
| 6788 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 6789 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 6790 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6791 | // If the condition controls loop exit (the loop exits only if the expression |
| 6792 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 6793 | // compute the backedge count. In this case, the step may not divide the |
| 6794 | // distance, but we don't care because if the condition is "missed" the loop |
| 6795 | // will have undefined behavior due to wrapping. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 6796 | if (ControlsExit && AddRec->hasNoSelfWrap()) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6797 | const SCEV *Exact = |
| 6798 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
| 6799 | return ExitLimit(Exact, Exact); |
| 6800 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 6801 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6802 | // Then, try to solve the above equation provided that Start is constant. |
| 6803 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6804 | return SolveLinEquationWithOverflow(StepC->getAPInt(), -StartC->getAPInt(), |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 6805 | *this); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6806 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6807 | } |
| 6808 | |
| 6809 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 6810 | /// specified value for nonzero will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 6811 | /// CouldNotCompute |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6812 | ScalarEvolution::ExitLimit |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 6813 | ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6814 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 6815 | // handle them yet except for the trivial case. This could be expanded in the |
| 6816 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6817 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6818 | // If the value is a constant, check to see if it is known to be non-zero |
| 6819 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6820 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 6821 | if (!C->getValue()->isNullValue()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 6822 | return getZero(C->getType()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6823 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6824 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6825 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6826 | // We could implement others, but I really doubt anyone writes loops like |
| 6827 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6828 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6829 | } |
| 6830 | |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6831 | /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB |
| 6832 | /// (which may not be an immediate predecessor) which has exactly one |
| 6833 | /// successor from which BB is reachable, or null if no such block is |
| 6834 | /// found. |
| 6835 | /// |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 6836 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6837 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 6838 | // If the block has a unique predecessor, then there is no path from the |
| 6839 | // predecessor to the block that does not go through the direct edge |
| 6840 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6841 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6842 | return {Pred, BB}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6843 | |
| 6844 | // 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] | 6845 | // If the header has a unique predecessor outside the loop, it must be |
| 6846 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6847 | if (Loop *L = LI.getLoopFor(BB)) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6848 | return {L->getLoopPredecessor(), L->getHeader()}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6849 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6850 | return {nullptr, nullptr}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 6851 | } |
| 6852 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6853 | /// HasSameValue - SCEV structural equivalence is usually sufficient for |
| 6854 | /// testing whether two expressions are equal, however for the purposes of |
| 6855 | /// looking for a condition guarding a loop, it can be useful to be a little |
| 6856 | /// more general, since a front-end may have replicated the controlling |
| 6857 | /// expression. |
| 6858 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6859 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6860 | // Quick check to see if they are the same SCEV. |
| 6861 | if (A == B) return true; |
| 6862 | |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 6863 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { |
| 6864 | // Not all instructions that are "identical" compute the same value. For |
| 6865 | // instance, two distinct alloca instructions allocating the same type are |
| 6866 | // identical and do not read memory; but compute distinct values. |
| 6867 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); |
| 6868 | }; |
| 6869 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6870 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 6871 | // two different instructions with the same value. Check for this case. |
| 6872 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 6873 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 6874 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 6875 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 6876 | if (ComputesEqualValues(AI, BI)) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 6877 | return true; |
| 6878 | |
| 6879 | // Otherwise assume they may have a different value. |
| 6880 | return false; |
| 6881 | } |
| 6882 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6883 | /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 6884 | /// predicate Pred. Return true iff any changes were made. |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6885 | /// |
| 6886 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6887 | const SCEV *&LHS, const SCEV *&RHS, |
| 6888 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6889 | bool Changed = false; |
| 6890 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6891 | // If we hit the max recursion limit bail out. |
| 6892 | if (Depth >= 3) |
| 6893 | return false; |
| 6894 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6895 | // Canonicalize a constant to the right side. |
| 6896 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 6897 | // Check for both operands constant. |
| 6898 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 6899 | if (ConstantExpr::getICmp(Pred, |
| 6900 | LHSC->getValue(), |
| 6901 | RHSC->getValue())->isNullValue()) |
| 6902 | goto trivially_false; |
| 6903 | else |
| 6904 | goto trivially_true; |
| 6905 | } |
| 6906 | // Otherwise swap the operands to put the constant on the right. |
| 6907 | std::swap(LHS, RHS); |
| 6908 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 6909 | Changed = true; |
| 6910 | } |
| 6911 | |
| 6912 | // 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] | 6913 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 6914 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 6915 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 6916 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 6917 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6918 | std::swap(LHS, RHS); |
| 6919 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 6920 | Changed = true; |
| 6921 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 6922 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6923 | |
| 6924 | // If there's a constant operand, canonicalize comparisons with boundary |
| 6925 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 6926 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6927 | const APInt &RA = RC->getAPInt(); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6928 | switch (Pred) { |
| 6929 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 6930 | case ICmpInst::ICMP_EQ: |
| 6931 | case ICmpInst::ICMP_NE: |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6932 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 6933 | if (!RA) |
| 6934 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 6935 | if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
Benjamin Kramer | 406a2db | 2012-05-30 18:42:43 +0000 | [diff] [blame] | 6936 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 6937 | ME->getOperand(0)->isAllOnesValue()) { |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 6938 | RHS = AE->getOperand(1); |
| 6939 | LHS = ME->getOperand(1); |
| 6940 | Changed = true; |
| 6941 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 6942 | break; |
| 6943 | case ICmpInst::ICMP_UGE: |
| 6944 | if ((RA - 1).isMinValue()) { |
| 6945 | Pred = ICmpInst::ICMP_NE; |
| 6946 | RHS = getConstant(RA - 1); |
| 6947 | Changed = true; |
| 6948 | break; |
| 6949 | } |
| 6950 | if (RA.isMaxValue()) { |
| 6951 | Pred = ICmpInst::ICMP_EQ; |
| 6952 | Changed = true; |
| 6953 | break; |
| 6954 | } |
| 6955 | if (RA.isMinValue()) goto trivially_true; |
| 6956 | |
| 6957 | Pred = ICmpInst::ICMP_UGT; |
| 6958 | RHS = getConstant(RA - 1); |
| 6959 | Changed = true; |
| 6960 | break; |
| 6961 | case ICmpInst::ICMP_ULE: |
| 6962 | if ((RA + 1).isMaxValue()) { |
| 6963 | Pred = ICmpInst::ICMP_NE; |
| 6964 | RHS = getConstant(RA + 1); |
| 6965 | Changed = true; |
| 6966 | break; |
| 6967 | } |
| 6968 | if (RA.isMinValue()) { |
| 6969 | Pred = ICmpInst::ICMP_EQ; |
| 6970 | Changed = true; |
| 6971 | break; |
| 6972 | } |
| 6973 | if (RA.isMaxValue()) goto trivially_true; |
| 6974 | |
| 6975 | Pred = ICmpInst::ICMP_ULT; |
| 6976 | RHS = getConstant(RA + 1); |
| 6977 | Changed = true; |
| 6978 | break; |
| 6979 | case ICmpInst::ICMP_SGE: |
| 6980 | if ((RA - 1).isMinSignedValue()) { |
| 6981 | Pred = ICmpInst::ICMP_NE; |
| 6982 | RHS = getConstant(RA - 1); |
| 6983 | Changed = true; |
| 6984 | break; |
| 6985 | } |
| 6986 | if (RA.isMaxSignedValue()) { |
| 6987 | Pred = ICmpInst::ICMP_EQ; |
| 6988 | Changed = true; |
| 6989 | break; |
| 6990 | } |
| 6991 | if (RA.isMinSignedValue()) goto trivially_true; |
| 6992 | |
| 6993 | Pred = ICmpInst::ICMP_SGT; |
| 6994 | RHS = getConstant(RA - 1); |
| 6995 | Changed = true; |
| 6996 | break; |
| 6997 | case ICmpInst::ICMP_SLE: |
| 6998 | if ((RA + 1).isMaxSignedValue()) { |
| 6999 | Pred = ICmpInst::ICMP_NE; |
| 7000 | RHS = getConstant(RA + 1); |
| 7001 | Changed = true; |
| 7002 | break; |
| 7003 | } |
| 7004 | if (RA.isMinSignedValue()) { |
| 7005 | Pred = ICmpInst::ICMP_EQ; |
| 7006 | Changed = true; |
| 7007 | break; |
| 7008 | } |
| 7009 | if (RA.isMaxSignedValue()) goto trivially_true; |
| 7010 | |
| 7011 | Pred = ICmpInst::ICMP_SLT; |
| 7012 | RHS = getConstant(RA + 1); |
| 7013 | Changed = true; |
| 7014 | break; |
| 7015 | case ICmpInst::ICMP_UGT: |
| 7016 | if (RA.isMinValue()) { |
| 7017 | Pred = ICmpInst::ICMP_NE; |
| 7018 | Changed = true; |
| 7019 | break; |
| 7020 | } |
| 7021 | if ((RA + 1).isMaxValue()) { |
| 7022 | Pred = ICmpInst::ICMP_EQ; |
| 7023 | RHS = getConstant(RA + 1); |
| 7024 | Changed = true; |
| 7025 | break; |
| 7026 | } |
| 7027 | if (RA.isMaxValue()) goto trivially_false; |
| 7028 | break; |
| 7029 | case ICmpInst::ICMP_ULT: |
| 7030 | if (RA.isMaxValue()) { |
| 7031 | Pred = ICmpInst::ICMP_NE; |
| 7032 | Changed = true; |
| 7033 | break; |
| 7034 | } |
| 7035 | if ((RA - 1).isMinValue()) { |
| 7036 | Pred = ICmpInst::ICMP_EQ; |
| 7037 | RHS = getConstant(RA - 1); |
| 7038 | Changed = true; |
| 7039 | break; |
| 7040 | } |
| 7041 | if (RA.isMinValue()) goto trivially_false; |
| 7042 | break; |
| 7043 | case ICmpInst::ICMP_SGT: |
| 7044 | if (RA.isMinSignedValue()) { |
| 7045 | Pred = ICmpInst::ICMP_NE; |
| 7046 | Changed = true; |
| 7047 | break; |
| 7048 | } |
| 7049 | if ((RA + 1).isMaxSignedValue()) { |
| 7050 | Pred = ICmpInst::ICMP_EQ; |
| 7051 | RHS = getConstant(RA + 1); |
| 7052 | Changed = true; |
| 7053 | break; |
| 7054 | } |
| 7055 | if (RA.isMaxSignedValue()) goto trivially_false; |
| 7056 | break; |
| 7057 | case ICmpInst::ICMP_SLT: |
| 7058 | if (RA.isMaxSignedValue()) { |
| 7059 | Pred = ICmpInst::ICMP_NE; |
| 7060 | Changed = true; |
| 7061 | break; |
| 7062 | } |
| 7063 | if ((RA - 1).isMinSignedValue()) { |
| 7064 | Pred = ICmpInst::ICMP_EQ; |
| 7065 | RHS = getConstant(RA - 1); |
| 7066 | Changed = true; |
| 7067 | break; |
| 7068 | } |
| 7069 | if (RA.isMinSignedValue()) goto trivially_false; |
| 7070 | break; |
| 7071 | } |
| 7072 | } |
| 7073 | |
| 7074 | // Check for obvious equality. |
| 7075 | if (HasSameValue(LHS, RHS)) { |
| 7076 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7077 | goto trivially_true; |
| 7078 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 7079 | goto trivially_false; |
| 7080 | } |
| 7081 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7082 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 7083 | // adding or subtracting 1 from one of the operands. |
| 7084 | switch (Pred) { |
| 7085 | case ICmpInst::ICMP_SLE: |
| 7086 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 7087 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7088 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7089 | Pred = ICmpInst::ICMP_SLT; |
| 7090 | Changed = true; |
| 7091 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7092 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7093 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7094 | Pred = ICmpInst::ICMP_SLT; |
| 7095 | Changed = true; |
| 7096 | } |
| 7097 | break; |
| 7098 | case ICmpInst::ICMP_SGE: |
| 7099 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7100 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7101 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7102 | Pred = ICmpInst::ICMP_SGT; |
| 7103 | Changed = true; |
| 7104 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 7105 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7106 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7107 | Pred = ICmpInst::ICMP_SGT; |
| 7108 | Changed = true; |
| 7109 | } |
| 7110 | break; |
| 7111 | case ICmpInst::ICMP_ULE: |
| 7112 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7113 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7114 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7115 | Pred = ICmpInst::ICMP_ULT; |
| 7116 | Changed = true; |
| 7117 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7118 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7119 | Pred = ICmpInst::ICMP_ULT; |
| 7120 | Changed = true; |
| 7121 | } |
| 7122 | break; |
| 7123 | case ICmpInst::ICMP_UGE: |
| 7124 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7125 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7126 | Pred = ICmpInst::ICMP_UGT; |
| 7127 | Changed = true; |
| 7128 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7129 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7130 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7131 | Pred = ICmpInst::ICMP_UGT; |
| 7132 | Changed = true; |
| 7133 | } |
| 7134 | break; |
| 7135 | default: |
| 7136 | break; |
| 7137 | } |
| 7138 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7139 | // TODO: More simplifications are possible here. |
| 7140 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7141 | // Recursively simplify until we either hit a recursion limit or nothing |
| 7142 | // changes. |
| 7143 | if (Changed) |
| 7144 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 7145 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7146 | return Changed; |
| 7147 | |
| 7148 | trivially_true: |
| 7149 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7150 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7151 | Pred = ICmpInst::ICMP_EQ; |
| 7152 | return true; |
| 7153 | |
| 7154 | trivially_false: |
| 7155 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7156 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7157 | Pred = ICmpInst::ICMP_NE; |
| 7158 | return true; |
| 7159 | } |
| 7160 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7161 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 7162 | return getSignedRange(S).getSignedMax().isNegative(); |
| 7163 | } |
| 7164 | |
| 7165 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 7166 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 7167 | } |
| 7168 | |
| 7169 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 7170 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 7171 | } |
| 7172 | |
| 7173 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 7174 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 7175 | } |
| 7176 | |
| 7177 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 7178 | return isKnownNegative(S) || isKnownPositive(S); |
| 7179 | } |
| 7180 | |
| 7181 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 7182 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 7183 | // Canonicalize the inputs first. |
| 7184 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 7185 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7186 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 7187 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 7188 | // If LHS and RHS are both addrec, both conditions must be true in |
| 7189 | // every iteration of the loop. |
| 7190 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7191 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7192 | bool LeftGuarded = false; |
| 7193 | bool RightGuarded = false; |
| 7194 | if (LAR) { |
| 7195 | const Loop *L = LAR->getLoop(); |
| 7196 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 7197 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 7198 | if (!RAR) return true; |
| 7199 | LeftGuarded = true; |
| 7200 | } |
| 7201 | } |
| 7202 | if (RAR) { |
| 7203 | const Loop *L = RAR->getLoop(); |
| 7204 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 7205 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 7206 | if (!LAR) return true; |
| 7207 | RightGuarded = true; |
| 7208 | } |
| 7209 | } |
| 7210 | if (LeftGuarded && RightGuarded) |
| 7211 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7212 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7213 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) |
| 7214 | return true; |
| 7215 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7216 | // Otherwise see what can be done with known constant ranges. |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7217 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7218 | } |
| 7219 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7220 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 7221 | ICmpInst::Predicate Pred, |
| 7222 | bool &Increasing) { |
| 7223 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 7224 | |
| 7225 | #ifndef NDEBUG |
| 7226 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 7227 | // increasing change to a monotonically decreasing one, and vice versa. |
| 7228 | bool IncreasingSwapped; |
| 7229 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 7230 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 7231 | |
| 7232 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 7233 | if (ResultSwapped) |
| 7234 | assert(Increasing == !IncreasingSwapped && |
| 7235 | "monotonicity should flip as we flip the predicate"); |
| 7236 | #endif |
| 7237 | |
| 7238 | return Result; |
| 7239 | } |
| 7240 | |
| 7241 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 7242 | ICmpInst::Predicate Pred, |
| 7243 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7244 | |
| 7245 | // A zero step value for LHS means the induction variable is essentially a |
| 7246 | // loop invariant value. We don't really depend on the predicate actually |
| 7247 | // flipping from false to true (for increasing predicates, and the other way |
| 7248 | // around for decreasing predicates), all we care about is that *if* the |
| 7249 | // predicate changes then it only changes from false to true. |
| 7250 | // |
| 7251 | // A zero step value in itself is not very useful, but there may be places |
| 7252 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 7253 | // as general as possible. |
| 7254 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7255 | switch (Pred) { |
| 7256 | default: |
| 7257 | return false; // Conservative answer |
| 7258 | |
| 7259 | case ICmpInst::ICMP_UGT: |
| 7260 | case ICmpInst::ICMP_UGE: |
| 7261 | case ICmpInst::ICMP_ULT: |
| 7262 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7263 | if (!LHS->hasNoUnsignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7264 | return false; |
| 7265 | |
| 7266 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7267 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7268 | |
| 7269 | case ICmpInst::ICMP_SGT: |
| 7270 | case ICmpInst::ICMP_SGE: |
| 7271 | case ICmpInst::ICMP_SLT: |
| 7272 | case ICmpInst::ICMP_SLE: { |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7273 | if (!LHS->hasNoSignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7274 | return false; |
| 7275 | |
| 7276 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 7277 | |
| 7278 | if (isKnownNonNegative(Step)) { |
| 7279 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 7280 | return true; |
| 7281 | } |
| 7282 | |
| 7283 | if (isKnownNonPositive(Step)) { |
| 7284 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 7285 | return true; |
| 7286 | } |
| 7287 | |
| 7288 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7289 | } |
| 7290 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7291 | } |
| 7292 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7293 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7294 | } |
| 7295 | |
| 7296 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 7297 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 7298 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 7299 | const SCEV *&InvariantRHS) { |
| 7300 | |
| 7301 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 7302 | if (!isLoopInvariant(RHS, L)) { |
| 7303 | if (!isLoopInvariant(LHS, L)) |
| 7304 | return false; |
| 7305 | |
| 7306 | std::swap(LHS, RHS); |
| 7307 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7308 | } |
| 7309 | |
| 7310 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7311 | if (!ArLHS || ArLHS->getLoop() != L) |
| 7312 | return false; |
| 7313 | |
| 7314 | bool Increasing; |
| 7315 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 7316 | return false; |
| 7317 | |
| 7318 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 7319 | // true as the loop iterates, and the backedge is control dependent on |
| 7320 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 7321 | // |
| 7322 | // * if the predicate was false in the first iteration then the predicate |
| 7323 | // is never evaluated again, since the loop exits without taking the |
| 7324 | // backedge. |
| 7325 | // * if the predicate was true in the first iteration then it will |
| 7326 | // continue to be true for all future iterations since it is |
| 7327 | // monotonically increasing. |
| 7328 | // |
| 7329 | // For both the above possibilities, we can replace the loop varying |
| 7330 | // predicate with its value on the first iteration of the loop (which is |
| 7331 | // loop invariant). |
| 7332 | // |
| 7333 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 7334 | // replacing true with false and false with true in the above two bullets. |
| 7335 | |
| 7336 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 7337 | |
| 7338 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 7339 | return false; |
| 7340 | |
| 7341 | InvariantPred = Pred; |
| 7342 | InvariantLHS = ArLHS->getStart(); |
| 7343 | InvariantRHS = RHS; |
| 7344 | return true; |
| 7345 | } |
| 7346 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7347 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( |
| 7348 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7349 | if (HasSameValue(LHS, RHS)) |
| 7350 | return ICmpInst::isTrueWhenEqual(Pred); |
| 7351 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7352 | // This code is split out from isKnownPredicate because it is called from |
| 7353 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7354 | |
Sanjoy Das | 4c7b6d7 | 2016-02-01 20:48:14 +0000 | [diff] [blame] | 7355 | auto CheckRanges = |
| 7356 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { |
| 7357 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) |
| 7358 | .contains(RangeLHS); |
| 7359 | }; |
| 7360 | |
| 7361 | // The check at the top of the function catches the case where the values are |
| 7362 | // known to be equal. |
| 7363 | if (Pred == CmpInst::ICMP_EQ) |
| 7364 | return false; |
| 7365 | |
| 7366 | if (Pred == CmpInst::ICMP_NE) |
| 7367 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || |
| 7368 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || |
| 7369 | isKnownNonZero(getMinusSCEV(LHS, RHS)); |
| 7370 | |
| 7371 | if (CmpInst::isSigned(Pred)) |
| 7372 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); |
| 7373 | |
| 7374 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7375 | } |
| 7376 | |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7377 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, |
| 7378 | const SCEV *LHS, |
| 7379 | const SCEV *RHS) { |
| 7380 | |
| 7381 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. |
| 7382 | // Return Y via OutY. |
| 7383 | auto MatchBinaryAddToConst = |
| 7384 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, |
| 7385 | SCEV::NoWrapFlags ExpectedFlags) { |
| 7386 | const SCEV *NonConstOp, *ConstOp; |
| 7387 | SCEV::NoWrapFlags FlagsPresent; |
| 7388 | |
| 7389 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || |
| 7390 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) |
| 7391 | return false; |
| 7392 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7393 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7394 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; |
| 7395 | }; |
| 7396 | |
| 7397 | APInt C; |
| 7398 | |
| 7399 | switch (Pred) { |
| 7400 | default: |
| 7401 | break; |
| 7402 | |
| 7403 | case ICmpInst::ICMP_SGE: |
| 7404 | std::swap(LHS, RHS); |
| 7405 | case ICmpInst::ICMP_SLE: |
| 7406 | // X s<= (X + C)<nsw> if C >= 0 |
| 7407 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) |
| 7408 | return true; |
| 7409 | |
| 7410 | // (X + C)<nsw> s<= X if C <= 0 |
| 7411 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && |
| 7412 | !C.isStrictlyPositive()) |
| 7413 | return true; |
| 7414 | break; |
| 7415 | |
| 7416 | case ICmpInst::ICMP_SGT: |
| 7417 | std::swap(LHS, RHS); |
| 7418 | case ICmpInst::ICMP_SLT: |
| 7419 | // X s< (X + C)<nsw> if C > 0 |
| 7420 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && |
| 7421 | C.isStrictlyPositive()) |
| 7422 | return true; |
| 7423 | |
| 7424 | // (X + C)<nsw> s< X if C < 0 |
| 7425 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) |
| 7426 | return true; |
| 7427 | break; |
| 7428 | } |
| 7429 | |
| 7430 | return false; |
| 7431 | } |
| 7432 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7433 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, |
| 7434 | const SCEV *LHS, |
| 7435 | const SCEV *RHS) { |
Sanjoy Das | 10dffcb | 2015-10-08 03:46:00 +0000 | [diff] [blame] | 7436 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7437 | return false; |
| 7438 | |
| 7439 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on |
| 7440 | // the stack can result in exponential time complexity. |
| 7441 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); |
| 7442 | |
| 7443 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L |
| 7444 | // |
| 7445 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use |
| 7446 | // isKnownPredicate. isKnownPredicate is more powerful, but also more |
| 7447 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the |
| 7448 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to |
| 7449 | // use isKnownPredicate later if needed. |
Alexander Kornienko | 484e48e3 | 2015-11-05 21:07:12 +0000 | [diff] [blame] | 7450 | return isKnownNonNegative(RHS) && |
| 7451 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && |
| 7452 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7453 | } |
| 7454 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7455 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 7456 | /// protected by a conditional between LHS and RHS. This is used to |
| 7457 | /// to eliminate casts. |
| 7458 | bool |
| 7459 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 7460 | ICmpInst::Predicate Pred, |
| 7461 | const SCEV *LHS, const SCEV *RHS) { |
| 7462 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7463 | // (interprocedural conditions notwithstanding). |
| 7464 | if (!L) return true; |
| 7465 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7466 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7467 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7468 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7469 | BasicBlock *Latch = L->getLoopLatch(); |
| 7470 | if (!Latch) |
| 7471 | return false; |
| 7472 | |
| 7473 | BranchInst *LoopContinuePredicate = |
| 7474 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7475 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 7476 | isImpliedCond(Pred, LHS, RHS, |
| 7477 | LoopContinuePredicate->getCondition(), |
| 7478 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 7479 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7480 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7481 | // 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] | 7482 | // -- that can lead to O(n!) time complexity. |
| 7483 | if (WalkingBEDominatingConds) |
| 7484 | return false; |
| 7485 | |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 7486 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7487 | |
Sanjoy Das | b174f9a | 2015-09-25 23:53:50 +0000 | [diff] [blame] | 7488 | // See if we can exploit a trip count to prove the predicate. |
| 7489 | const auto &BETakenInfo = getBackedgeTakenInfo(L); |
| 7490 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); |
| 7491 | if (LatchBECount != getCouldNotCompute()) { |
| 7492 | // We know that Latch branches back to the loop header exactly |
| 7493 | // LatchBECount times. This means the backdege condition at Latch is |
| 7494 | // equivalent to "{0,+,1} u< LatchBECount". |
| 7495 | Type *Ty = LatchBECount->getType(); |
| 7496 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); |
| 7497 | const SCEV *LoopCounter = |
| 7498 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); |
| 7499 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, |
| 7500 | LatchBECount)) |
| 7501 | return true; |
| 7502 | } |
| 7503 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7504 | // Check conditions due to any @llvm.assume intrinsics. |
| 7505 | for (auto &AssumeVH : AC.assumptions()) { |
| 7506 | if (!AssumeVH) |
| 7507 | continue; |
| 7508 | auto *CI = cast<CallInst>(AssumeVH); |
| 7509 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7510 | continue; |
| 7511 | |
| 7512 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7513 | return true; |
| 7514 | } |
| 7515 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7516 | // If the loop is not reachable from the entry block, we risk running into an |
| 7517 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7518 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7519 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7520 | return false; |
| 7521 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7522 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7523 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7524 | |
| 7525 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7526 | |
| 7527 | BasicBlock *BB = DTN->getBlock(); |
| 7528 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7529 | if (!PBB) |
| 7530 | continue; |
| 7531 | |
| 7532 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7533 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7534 | continue; |
| 7535 | |
| 7536 | Value *Condition = ContinuePredicate->getCondition(); |
| 7537 | |
| 7538 | // If we have an edge `E` within the loop body that dominates the only |
| 7539 | // latch, the condition guarding `E` also guards the backedge. This |
| 7540 | // reasoning works only for loops with a single latch. |
| 7541 | |
| 7542 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 7543 | if (DominatingEdge.isSingleEdge()) { |
| 7544 | // We're constructively (and conservatively) enumerating edges within the |
| 7545 | // loop body that dominate the latch. The dominator tree better agree |
| 7546 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7547 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7548 | |
| 7549 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 7550 | BB != ContinuePredicate->getSuccessor(0))) |
| 7551 | return true; |
| 7552 | } |
| 7553 | } |
| 7554 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7555 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7556 | } |
| 7557 | |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7558 | /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7559 | /// by a conditional between LHS and RHS. This is used to help avoid max |
| 7560 | /// expressions in loop trip counts, and to eliminate casts. |
| 7561 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7562 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 7563 | ICmpInst::Predicate Pred, |
| 7564 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 7565 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7566 | // (interprocedural conditions notwithstanding). |
| 7567 | if (!L) return false; |
| 7568 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7569 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7570 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7571 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 7572 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 7573 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7574 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7575 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 7576 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7577 | Pair.first; |
| 7578 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7579 | |
| 7580 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7581 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7582 | if (!LoopEntryPredicate || |
| 7583 | LoopEntryPredicate->isUnconditional()) |
| 7584 | continue; |
| 7585 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7586 | if (isImpliedCond(Pred, LHS, RHS, |
| 7587 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7588 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7589 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7590 | } |
| 7591 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7592 | // Check conditions due to any @llvm.assume intrinsics. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7593 | for (auto &AssumeVH : AC.assumptions()) { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 7594 | if (!AssumeVH) |
| 7595 | continue; |
| 7596 | auto *CI = cast<CallInst>(AssumeVH); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7597 | if (!DT.dominates(CI, L->getHeader())) |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7598 | continue; |
| 7599 | |
| 7600 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7601 | return true; |
| 7602 | } |
| 7603 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7604 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7605 | } |
| 7606 | |
Benjamin Kramer | 039b104 | 2015-10-28 13:54:36 +0000 | [diff] [blame] | 7607 | namespace { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7608 | /// RAII wrapper to prevent recursive application of isImpliedCond. |
| 7609 | /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are |
| 7610 | /// currently evaluating isImpliedCond. |
| 7611 | struct MarkPendingLoopPredicate { |
| 7612 | Value *Cond; |
| 7613 | DenseSet<Value*> &LoopPreds; |
| 7614 | bool Pending; |
| 7615 | |
| 7616 | MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) |
| 7617 | : Cond(C), LoopPreds(LP) { |
| 7618 | Pending = !LoopPreds.insert(Cond).second; |
| 7619 | } |
| 7620 | ~MarkPendingLoopPredicate() { |
| 7621 | if (!Pending) |
| 7622 | LoopPreds.erase(Cond); |
| 7623 | } |
| 7624 | }; |
Benjamin Kramer | 039b104 | 2015-10-28 13:54:36 +0000 | [diff] [blame] | 7625 | } // end anonymous namespace |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7626 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7627 | /// isImpliedCond - Test whether the condition described by Pred, LHS, |
| 7628 | /// and RHS is true whenever the given Cond value evaluates to true. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7629 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7630 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7631 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7632 | bool Inverse) { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 7633 | MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); |
| 7634 | if (Mark.Pending) |
| 7635 | return false; |
| 7636 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 7637 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7638 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7639 | if (BO->getOpcode() == Instruction::And) { |
| 7640 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7641 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 7642 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7643 | } else if (BO->getOpcode() == Instruction::Or) { |
| 7644 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7645 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 7646 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7647 | } |
| 7648 | } |
| 7649 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7650 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 7651 | if (!ICI) return false; |
| 7652 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 7653 | // Now that we found a conditional branch that dominates the loop or controls |
| 7654 | // 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] | 7655 | ICmpInst::Predicate FoundPred; |
| 7656 | if (Inverse) |
| 7657 | FoundPred = ICI->getInversePredicate(); |
| 7658 | else |
| 7659 | FoundPred = ICI->getPredicate(); |
| 7660 | |
| 7661 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 7662 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7663 | |
Sanjoy Das | df1635d | 2015-09-25 19:59:52 +0000 | [diff] [blame] | 7664 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); |
| 7665 | } |
| 7666 | |
| 7667 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, |
| 7668 | const SCEV *RHS, |
| 7669 | ICmpInst::Predicate FoundPred, |
| 7670 | const SCEV *FoundLHS, |
| 7671 | const SCEV *FoundRHS) { |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 7672 | // Balance the types. |
| 7673 | if (getTypeSizeInBits(LHS->getType()) < |
| 7674 | getTypeSizeInBits(FoundLHS->getType())) { |
| 7675 | if (CmpInst::isSigned(Pred)) { |
| 7676 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 7677 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 7678 | } else { |
| 7679 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 7680 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 7681 | } |
| 7682 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7683 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 7684 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7685 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 7686 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 7687 | } else { |
| 7688 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 7689 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 7690 | } |
| 7691 | } |
| 7692 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7693 | // Canonicalize the query to match the way instcombine will have |
| 7694 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 7695 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 7696 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 7697 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 7698 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 7699 | if (FoundLHS == FoundRHS) |
| 7700 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7701 | |
| 7702 | // Check to see if we can make the LHS or RHS match. |
| 7703 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 7704 | if (isa<SCEVConstant>(RHS)) { |
| 7705 | std::swap(FoundLHS, FoundRHS); |
| 7706 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 7707 | } else { |
| 7708 | std::swap(LHS, RHS); |
| 7709 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7710 | } |
| 7711 | } |
| 7712 | |
| 7713 | // Check whether the found predicate is the same as the desired predicate. |
| 7714 | if (FoundPred == Pred) |
| 7715 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 7716 | |
| 7717 | // Check whether swapping the found predicate makes it the same as the |
| 7718 | // desired predicate. |
| 7719 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 7720 | if (isa<SCEVConstant>(RHS)) |
| 7721 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 7722 | else |
| 7723 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 7724 | RHS, LHS, FoundLHS, FoundRHS); |
| 7725 | } |
| 7726 | |
Sanjoy Das | 6e78b17 | 2015-10-22 19:57:34 +0000 | [diff] [blame] | 7727 | // Unsigned comparison is the same as signed comparison when both the operands |
| 7728 | // are non-negative. |
| 7729 | if (CmpInst::isUnsigned(FoundPred) && |
| 7730 | CmpInst::getSignedPredicate(FoundPred) == Pred && |
| 7731 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) |
| 7732 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 7733 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 7734 | // Check if we can make progress by sharpening ranges. |
| 7735 | if (FoundPred == ICmpInst::ICMP_NE && |
| 7736 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 7737 | |
| 7738 | const SCEVConstant *C = nullptr; |
| 7739 | const SCEV *V = nullptr; |
| 7740 | |
| 7741 | if (isa<SCEVConstant>(FoundLHS)) { |
| 7742 | C = cast<SCEVConstant>(FoundLHS); |
| 7743 | V = FoundRHS; |
| 7744 | } else { |
| 7745 | C = cast<SCEVConstant>(FoundRHS); |
| 7746 | V = FoundLHS; |
| 7747 | } |
| 7748 | |
| 7749 | // The guarding predicate tells us that C != V. If the known range |
| 7750 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 7751 | // range we consider has to correspond to same signedness as the |
| 7752 | // predicate we're interested in folding. |
| 7753 | |
| 7754 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 7755 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 7756 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7757 | if (Min == C->getAPInt()) { |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 7758 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 7759 | // This is true even if (Min + 1) wraps around -- in case of |
| 7760 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 7761 | |
| 7762 | APInt SharperMin = Min + 1; |
| 7763 | |
| 7764 | switch (Pred) { |
| 7765 | case ICmpInst::ICMP_SGE: |
| 7766 | case ICmpInst::ICMP_UGE: |
| 7767 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 7768 | // RHS, we're done. |
| 7769 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 7770 | getConstant(SharperMin))) |
| 7771 | return true; |
| 7772 | |
| 7773 | case ICmpInst::ICMP_SGT: |
| 7774 | case ICmpInst::ICMP_UGT: |
| 7775 | // We know from the range information that (V `Pred` Min || |
| 7776 | // V == Min). We know from the guarding condition that !(V |
| 7777 | // == Min). This gives us |
| 7778 | // |
| 7779 | // V `Pred` Min || V == Min && !(V == Min) |
| 7780 | // => V `Pred` Min |
| 7781 | // |
| 7782 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 7783 | |
| 7784 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 7785 | return true; |
| 7786 | |
| 7787 | default: |
| 7788 | // No change |
| 7789 | break; |
| 7790 | } |
| 7791 | } |
| 7792 | } |
| 7793 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7794 | // Check whether the actual condition is beyond sufficient. |
| 7795 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 7796 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7797 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7798 | return true; |
| 7799 | if (Pred == ICmpInst::ICMP_NE) |
| 7800 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 7801 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7802 | return true; |
| 7803 | |
| 7804 | // Otherwise assume the worst. |
| 7805 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7806 | } |
| 7807 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 7808 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, |
| 7809 | const SCEV *&L, const SCEV *&R, |
| 7810 | SCEV::NoWrapFlags &Flags) { |
| 7811 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); |
| 7812 | if (!AE || AE->getNumOperands() != 2) |
| 7813 | return false; |
| 7814 | |
| 7815 | L = AE->getOperand(0); |
| 7816 | R = AE->getOperand(1); |
| 7817 | Flags = AE->getNoWrapFlags(); |
| 7818 | return true; |
| 7819 | } |
| 7820 | |
| 7821 | bool ScalarEvolution::computeConstantDifference(const SCEV *Less, |
| 7822 | const SCEV *More, |
| 7823 | APInt &C) { |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7824 | // We avoid subtracting expressions here because this function is usually |
| 7825 | // fairly deep in the call stack (i.e. is called many times). |
| 7826 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7827 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { |
| 7828 | const auto *LAR = cast<SCEVAddRecExpr>(Less); |
| 7829 | const auto *MAR = cast<SCEVAddRecExpr>(More); |
| 7830 | |
| 7831 | if (LAR->getLoop() != MAR->getLoop()) |
| 7832 | return false; |
| 7833 | |
| 7834 | // We look at affine expressions only; not for correctness but to keep |
| 7835 | // getStepRecurrence cheap. |
| 7836 | if (!LAR->isAffine() || !MAR->isAffine()) |
| 7837 | return false; |
| 7838 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 7839 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7840 | return false; |
| 7841 | |
| 7842 | Less = LAR->getStart(); |
| 7843 | More = MAR->getStart(); |
| 7844 | |
| 7845 | // fall through |
| 7846 | } |
| 7847 | |
| 7848 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7849 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); |
| 7850 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7851 | C = M - L; |
| 7852 | return true; |
| 7853 | } |
| 7854 | |
| 7855 | const SCEV *L, *R; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 7856 | SCEV::NoWrapFlags Flags; |
| 7857 | if (splitBinaryAdd(Less, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7858 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
| 7859 | if (R == More) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7860 | C = -(LC->getAPInt()); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7861 | return true; |
| 7862 | } |
| 7863 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 7864 | if (splitBinaryAdd(More, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7865 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
| 7866 | if (R == Less) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7867 | C = LC->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7868 | return true; |
| 7869 | } |
| 7870 | |
| 7871 | return false; |
| 7872 | } |
| 7873 | |
| 7874 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( |
| 7875 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 7876 | const SCEV *FoundLHS, const SCEV *FoundRHS) { |
| 7877 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) |
| 7878 | return false; |
| 7879 | |
| 7880 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7881 | if (!AddRecLHS) |
| 7882 | return false; |
| 7883 | |
| 7884 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); |
| 7885 | if (!AddRecFoundLHS) |
| 7886 | return false; |
| 7887 | |
| 7888 | // We'd like to let SCEV reason about control dependencies, so we constrain |
| 7889 | // both the inequalities to be about add recurrences on the same loop. This |
| 7890 | // way we can use isLoopEntryGuardedByCond later. |
| 7891 | |
| 7892 | const Loop *L = AddRecFoundLHS->getLoop(); |
| 7893 | if (L != AddRecLHS->getLoop()) |
| 7894 | return false; |
| 7895 | |
| 7896 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) |
| 7897 | // |
| 7898 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) |
| 7899 | // ... (2) |
| 7900 | // |
| 7901 | // Informal proof for (2), assuming (1) [*]: |
| 7902 | // |
| 7903 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] |
| 7904 | // |
| 7905 | // Then |
| 7906 | // |
| 7907 | // FoundLHS s< FoundRHS s< INT_MIN - C |
| 7908 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] |
| 7909 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] |
| 7910 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< |
| 7911 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] |
| 7912 | // <=> FoundLHS + C s< FoundRHS + C |
| 7913 | // |
| 7914 | // [*]: (1) can be proved by ruling out overflow. |
| 7915 | // |
| 7916 | // [**]: This can be proved by analyzing all the four possibilities: |
| 7917 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and |
| 7918 | // (A s>= 0, B s>= 0). |
| 7919 | // |
| 7920 | // Note: |
| 7921 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" |
| 7922 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS |
| 7923 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS |
| 7924 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is |
| 7925 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + |
| 7926 | // C)". |
| 7927 | |
| 7928 | APInt LDiff, RDiff; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 7929 | if (!computeConstantDifference(FoundLHS, LHS, LDiff) || |
| 7930 | !computeConstantDifference(FoundRHS, RHS, RDiff) || |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7931 | LDiff != RDiff) |
| 7932 | return false; |
| 7933 | |
| 7934 | if (LDiff == 0) |
| 7935 | return true; |
| 7936 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7937 | APInt FoundRHSLimit; |
| 7938 | |
| 7939 | if (Pred == CmpInst::ICMP_ULT) { |
| 7940 | FoundRHSLimit = -RDiff; |
| 7941 | } else { |
| 7942 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); |
Sanjoy Das | 4f1c459 | 2015-09-28 21:14:32 +0000 | [diff] [blame] | 7943 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7944 | } |
| 7945 | |
| 7946 | // Try to prove (1) or (2), as needed. |
| 7947 | return isLoopEntryGuardedByCond(L, Pred, FoundRHS, |
| 7948 | getConstant(FoundRHSLimit)); |
| 7949 | } |
| 7950 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7951 | /// isImpliedCondOperands - Test whether the condition described by Pred, |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 7952 | /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7953 | /// and FoundRHS is true. |
| 7954 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 7955 | const SCEV *LHS, const SCEV *RHS, |
| 7956 | const SCEV *FoundLHS, |
| 7957 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 7958 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7959 | return true; |
| 7960 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 7961 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 7962 | return true; |
| 7963 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 7964 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 7965 | FoundLHS, FoundRHS) || |
| 7966 | // ~x < ~y --> x > y |
| 7967 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 7968 | getNotSCEV(FoundRHS), |
| 7969 | getNotSCEV(FoundLHS)); |
| 7970 | } |
| 7971 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7972 | |
| 7973 | /// If Expr computes ~A, return A else return nullptr |
| 7974 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 7975 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 7976 | if (!Add || Add->getNumOperands() != 2 || |
| 7977 | !Add->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7978 | return nullptr; |
| 7979 | |
| 7980 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 7981 | if (!AddRHS || AddRHS->getNumOperands() != 2 || |
| 7982 | !AddRHS->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7983 | return nullptr; |
| 7984 | |
| 7985 | return AddRHS->getOperand(1); |
| 7986 | } |
| 7987 | |
| 7988 | |
| 7989 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 7990 | template<typename MaxExprType> |
| 7991 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 7992 | const SCEV *Candidate) { |
| 7993 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 7994 | if (!MaxExpr) return false; |
| 7995 | |
Sanjoy Das | 347d272 | 2015-12-01 07:49:27 +0000 | [diff] [blame] | 7996 | return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 7997 | } |
| 7998 | |
| 7999 | |
| 8000 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 8001 | template<typename MaxExprType> |
| 8002 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 8003 | const SCEV *MaybeMinExpr, |
| 8004 | const SCEV *Candidate) { |
| 8005 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 8006 | if (!MaybeMaxExpr) |
| 8007 | return false; |
| 8008 | |
| 8009 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 8010 | } |
| 8011 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8012 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 8013 | ICmpInst::Predicate Pred, |
| 8014 | const SCEV *LHS, const SCEV *RHS) { |
| 8015 | |
| 8016 | // If both sides are affine addrecs for the same loop, with equal |
| 8017 | // steps, and we know the recurrences don't wrap, then we only |
| 8018 | // need to check the predicate on the starting values. |
| 8019 | |
| 8020 | if (!ICmpInst::isRelational(Pred)) |
| 8021 | return false; |
| 8022 | |
| 8023 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8024 | if (!LAR) |
| 8025 | return false; |
| 8026 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 8027 | if (!RAR) |
| 8028 | return false; |
| 8029 | if (LAR->getLoop() != RAR->getLoop()) |
| 8030 | return false; |
| 8031 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 8032 | return false; |
| 8033 | |
| 8034 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 8035 | return false; |
| 8036 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 8037 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 8038 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 8039 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8040 | return false; |
| 8041 | |
| 8042 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 8043 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8044 | |
| 8045 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 8046 | /// expression? |
| 8047 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 8048 | ICmpInst::Predicate Pred, |
| 8049 | const SCEV *LHS, const SCEV *RHS) { |
| 8050 | switch (Pred) { |
| 8051 | default: |
| 8052 | return false; |
| 8053 | |
| 8054 | case ICmpInst::ICMP_SGE: |
| 8055 | std::swap(LHS, RHS); |
| 8056 | // fall through |
| 8057 | case ICmpInst::ICMP_SLE: |
| 8058 | return |
| 8059 | // min(A, ...) <= A |
| 8060 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 8061 | // A <= max(A, ...) |
| 8062 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 8063 | |
| 8064 | case ICmpInst::ICMP_UGE: |
| 8065 | std::swap(LHS, RHS); |
| 8066 | // fall through |
| 8067 | case ICmpInst::ICMP_ULE: |
| 8068 | return |
| 8069 | // min(A, ...) <= A |
| 8070 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 8071 | // A <= max(A, ...) |
| 8072 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 8073 | } |
| 8074 | |
| 8075 | llvm_unreachable("covered switch fell through?!"); |
| 8076 | } |
| 8077 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8078 | /// isImpliedCondOperandsHelper - Test whether the condition described by |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8079 | /// Pred, LHS, and RHS is true whenever the condition described by Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8080 | /// FoundLHS, and FoundRHS is true. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8081 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8082 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 8083 | const SCEV *LHS, const SCEV *RHS, |
| 8084 | const SCEV *FoundLHS, |
| 8085 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8086 | auto IsKnownPredicateFull = |
| 8087 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8088 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || |
Sanjoy Das | 1123148 | 2015-10-22 19:57:29 +0000 | [diff] [blame] | 8089 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 8090 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || |
| 8091 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8092 | }; |
| 8093 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8094 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8095 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 8096 | case ICmpInst::ICMP_EQ: |
| 8097 | case ICmpInst::ICMP_NE: |
| 8098 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 8099 | return true; |
| 8100 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8101 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8102 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8103 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 8104 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8105 | return true; |
| 8106 | break; |
| 8107 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8108 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8109 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 8110 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8111 | return true; |
| 8112 | break; |
| 8113 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8114 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8115 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 8116 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8117 | return true; |
| 8118 | break; |
| 8119 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8120 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8121 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 8122 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8123 | return true; |
| 8124 | break; |
| 8125 | } |
| 8126 | |
| 8127 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8128 | } |
| 8129 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8130 | /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands. |
| 8131 | /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1". |
| 8132 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 8133 | const SCEV *LHS, |
| 8134 | const SCEV *RHS, |
| 8135 | const SCEV *FoundLHS, |
| 8136 | const SCEV *FoundRHS) { |
| 8137 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 8138 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 8139 | // reduce the compile time impact of this optimization. |
| 8140 | return false; |
| 8141 | |
| 8142 | const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS); |
| 8143 | if (!AddLHS || AddLHS->getOperand(1) != FoundLHS || |
| 8144 | !isa<SCEVConstant>(AddLHS->getOperand(0))) |
| 8145 | return false; |
| 8146 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8147 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8148 | |
| 8149 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 8150 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 8151 | ConstantRange FoundLHSRange = |
| 8152 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 8153 | |
| 8154 | // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range |
| 8155 | // for `LHS`: |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8156 | APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8157 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend)); |
| 8158 | |
| 8159 | // We can also compute the range of values for `LHS` that satisfy the |
| 8160 | // consequent, "`LHS` `Pred` `RHS`": |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8161 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8162 | ConstantRange SatisfyingLHSRange = |
| 8163 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 8164 | |
| 8165 | // The antecedent implies the consequent if every value of `LHS` that |
| 8166 | // satisfies the antecedent also satisfies the consequent. |
| 8167 | return SatisfyingLHSRange.contains(LHSRange); |
| 8168 | } |
| 8169 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8170 | // Verify if an linear IV with positive stride can overflow when in a |
| 8171 | // less-than comparison, knowing the invariant term of the comparison, the |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8172 | // stride and the knowledge of NSW/NUW flags on the recurrence. |
| 8173 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 8174 | bool IsSigned, bool NoWrap) { |
| 8175 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8176 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8177 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8178 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8179 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8180 | if (IsSigned) { |
| 8181 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 8182 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 8183 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8184 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8185 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8186 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 8187 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 8188 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8189 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8190 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 8191 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 8192 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8193 | .getUnsignedMax(); |
| 8194 | |
| 8195 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 8196 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 8197 | } |
| 8198 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8199 | // 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] | 8200 | // greater-than comparison, knowing the invariant term of the comparison, |
| 8201 | // the stride and the knowledge of NSW/NUW flags on the recurrence. |
| 8202 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 8203 | bool IsSigned, bool NoWrap) { |
| 8204 | if (NoWrap) return false; |
| 8205 | |
| 8206 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8207 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8208 | |
| 8209 | if (IsSigned) { |
| 8210 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 8211 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 8212 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8213 | .getSignedMax(); |
| 8214 | |
| 8215 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 8216 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 8217 | } |
| 8218 | |
| 8219 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 8220 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 8221 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8222 | .getUnsignedMax(); |
| 8223 | |
| 8224 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 8225 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 8226 | } |
| 8227 | |
| 8228 | // Compute the backedge taken count knowing the interval difference, the |
| 8229 | // stride and presence of the equality in the comparison. |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8230 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8231 | bool Equality) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8232 | const SCEV *One = getOne(Step->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8233 | Delta = Equality ? getAddExpr(Delta, Step) |
| 8234 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 8235 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8236 | } |
| 8237 | |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8238 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 8239 | /// specified less-than comparison will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 8240 | /// CouldNotCompute. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 8241 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8242 | /// @param ControlsExit is true when the LHS < RHS condition directly controls |
| 8243 | /// the branch (loops exits only if condition is true). In this case, we can use |
| 8244 | /// NoWrapFlags to skip overflow checks. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8245 | ScalarEvolution::ExitLimit |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8246 | ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8247 | const Loop *L, bool IsSigned, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8248 | bool ControlsExit) { |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8249 | // We handle only IV < Invariant |
| 8250 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 8251 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8252 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8253 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8254 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8255 | // Avoid weird loops |
| 8256 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8257 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8258 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8259 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8260 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8261 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8262 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8263 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8264 | // Avoid negative or zero stride values |
| 8265 | if (!isKnownPositive(Stride)) |
| 8266 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8267 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8268 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8269 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8270 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8271 | // behaviors like the case of C language. |
| 8272 | if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 8273 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8274 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8275 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 8276 | : ICmpInst::ICMP_ULT; |
| 8277 | const SCEV *Start = IV->getStart(); |
| 8278 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8279 | if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) { |
| 8280 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 8281 | // If we have NoWrap set, then we can assume that the increment won't |
| 8282 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 8283 | // do a max operation since we can just figure it out statically |
| 8284 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8285 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8286 | if (D.isNegative()) |
| 8287 | End = Start; |
| 8288 | } else |
| 8289 | End = IsSigned ? getSMaxExpr(RHS, Start) |
| 8290 | : getUMaxExpr(RHS, Start); |
| 8291 | } |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8292 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8293 | const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8294 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8295 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 8296 | : getUnsignedRange(Start).getUnsignedMin(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8297 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8298 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8299 | : getUnsignedRange(Stride).getUnsignedMin(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8300 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8301 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8302 | APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1) |
| 8303 | : APInt::getMaxValue(BitWidth) - (MinStride - 1); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8304 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8305 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 8306 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 8307 | // is zero, leading to a zero maximum backedge taken count. |
| 8308 | APInt MaxEnd = |
| 8309 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 8310 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 8311 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 8312 | const SCEV *MaxBECount; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8313 | if (isa<SCEVConstant>(BECount)) |
| 8314 | MaxBECount = BECount; |
| 8315 | else |
| 8316 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
| 8317 | getConstant(MinStride), false); |
| 8318 | |
| 8319 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8320 | MaxBECount = BECount; |
| 8321 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8322 | return ExitLimit(BECount, MaxBECount); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8323 | } |
| 8324 | |
| 8325 | ScalarEvolution::ExitLimit |
| 8326 | ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
| 8327 | const Loop *L, bool IsSigned, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8328 | bool ControlsExit) { |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8329 | // We handle only IV > Invariant |
| 8330 | if (!isLoopInvariant(RHS, L)) |
| 8331 | return getCouldNotCompute(); |
| 8332 | |
| 8333 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8334 | |
| 8335 | // Avoid weird loops |
| 8336 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8337 | return getCouldNotCompute(); |
| 8338 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8339 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8340 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 8341 | |
| 8342 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 8343 | |
| 8344 | // Avoid negative or zero stride values |
| 8345 | if (!isKnownPositive(Stride)) |
| 8346 | return getCouldNotCompute(); |
| 8347 | |
| 8348 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8349 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8350 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8351 | // behaviors like the case of C language. |
| 8352 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 8353 | return getCouldNotCompute(); |
| 8354 | |
| 8355 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 8356 | : ICmpInst::ICMP_UGT; |
| 8357 | |
| 8358 | const SCEV *Start = IV->getStart(); |
| 8359 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8360 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { |
| 8361 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 8362 | // If we have NoWrap set, then we can assume that the increment won't |
| 8363 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 8364 | // do a max operation since we can just figure it out statically |
| 8365 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8366 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8367 | if (!D.isNegative()) |
| 8368 | End = Start; |
| 8369 | } else |
| 8370 | End = IsSigned ? getSMinExpr(RHS, Start) |
| 8371 | : getUMinExpr(RHS, Start); |
| 8372 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8373 | |
| 8374 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 8375 | |
| 8376 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 8377 | : getUnsignedRange(Start).getUnsignedMax(); |
| 8378 | |
| 8379 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8380 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8381 | |
| 8382 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8383 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 8384 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 8385 | |
| 8386 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 8387 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 8388 | // is zero, leading to a zero maximum backedge taken count. |
| 8389 | APInt MinEnd = |
| 8390 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 8391 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 8392 | |
| 8393 | |
| 8394 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 8395 | if (isa<SCEVConstant>(BECount)) |
| 8396 | MaxBECount = BECount; |
| 8397 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8398 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8399 | getConstant(MinStride), false); |
| 8400 | |
| 8401 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8402 | MaxBECount = BECount; |
| 8403 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8404 | return ExitLimit(BECount, MaxBECount); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8405 | } |
| 8406 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8407 | /// getNumIterationsInRange - Return the number of iterations of this loop that |
| 8408 | /// produce values in the specified constant range. Another way of looking at |
| 8409 | /// this is that it returns the first iteration number where the value is not in |
| 8410 | /// the condition, thus computing the exit count. If the iteration count can't |
| 8411 | /// be computed, an instance of SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8412 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8413 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8414 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8415 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8416 | |
| 8417 | // 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] | 8418 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 8419 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8420 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8421 | Operands[0] = SE.getZero(SC->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8422 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 8423 | getNoWrapFlags(FlagNW)); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 8424 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8425 | return ShiftedAddRec->getNumIterationsInRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8426 | Range.subtract(SC->getAPInt()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8427 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8428 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8429 | } |
| 8430 | |
| 8431 | // The only time we can solve this is when we have all constant indices. |
| 8432 | // Otherwise, we cannot determine the overflow conditions. |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 8433 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 8434 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8435 | |
| 8436 | // Okay at this point we know that all elements of the chrec are constants and |
| 8437 | // that the start element is zero. |
| 8438 | |
| 8439 | // First check to see if the range contains zero. If not, the first |
| 8440 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 8441 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8442 | if (!Range.contains(APInt(BitWidth, 0))) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8443 | return SE.getZero(getType()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8444 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8445 | if (isAffine()) { |
| 8446 | // If this is an affine expression then we have this situation: |
| 8447 | // Solve {0,+,A} in Range === Ax in Range |
| 8448 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8449 | // We know that zero is in the range. If A is positive then we know that |
| 8450 | // the upper value of the range must be the first possible exit value. |
| 8451 | // If A is negative then the lower of the range is the last possible loop |
| 8452 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8453 | APInt One(BitWidth,1); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8454 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8455 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8456 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8457 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 8458 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8459 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8460 | |
| 8461 | // Evaluate at the exit value. If we really did fall out of the valid |
| 8462 | // range, then we computed our trip count, otherwise wrap around or other |
| 8463 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8464 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8465 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8466 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8467 | |
| 8468 | // 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] | 8469 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8470 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8471 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8472 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8473 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8474 | } else if (isQuadratic()) { |
| 8475 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 8476 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 8477 | // terms of figuring out when zero is crossed, instead of when |
| 8478 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8479 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8480 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8481 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), |
| 8482 | // getNoWrapFlags(FlagNW) |
| 8483 | FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8484 | |
| 8485 | // Next, solve the constructed addrec |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8486 | auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8487 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 8488 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8489 | if (R1) { |
| 8490 | // Pick the smallest positive root value. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8491 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 8492 | ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 8493 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8494 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8495 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8496 | // Make sure the root is not off by one. The returned iteration should |
| 8497 | // not be in the range, but the previous one should be. When solving |
| 8498 | // for "X*X < 5", for example, we should not return a root of 2. |
| 8499 | ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8500 | R1->getValue(), |
| 8501 | SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8502 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8503 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8504 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8505 | ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8506 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8507 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8508 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8509 | return SE.getConstant(NextVal); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8510 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8511 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8512 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8513 | // If R1 was not in the range, then it is a good return value. Make |
| 8514 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8515 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8516 | ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8517 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8518 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8519 | return R1; |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8520 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8521 | } |
| 8522 | } |
| 8523 | } |
| 8524 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8525 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8526 | } |
| 8527 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8528 | namespace { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8529 | struct FindUndefs { |
| 8530 | bool Found; |
| 8531 | FindUndefs() : Found(false) {} |
| 8532 | |
| 8533 | bool follow(const SCEV *S) { |
| 8534 | if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { |
| 8535 | if (isa<UndefValue>(C->getValue())) |
| 8536 | Found = true; |
| 8537 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
| 8538 | if (isa<UndefValue>(C->getValue())) |
| 8539 | Found = true; |
| 8540 | } |
| 8541 | |
| 8542 | // Keep looking if we haven't found it yet. |
| 8543 | return !Found; |
| 8544 | } |
| 8545 | bool isDone() const { |
| 8546 | // Stop recursion if we have found an undef. |
| 8547 | return Found; |
| 8548 | } |
| 8549 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8550 | } |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8551 | |
| 8552 | // Return true when S contains at least an undef value. |
| 8553 | static inline bool |
| 8554 | containsUndefs(const SCEV *S) { |
| 8555 | FindUndefs F; |
| 8556 | SCEVTraversal<FindUndefs> ST(F); |
| 8557 | ST.visitAll(S); |
| 8558 | |
| 8559 | return F.Found; |
| 8560 | } |
| 8561 | |
| 8562 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8563 | // Collect all steps of SCEV expressions. |
| 8564 | struct SCEVCollectStrides { |
| 8565 | ScalarEvolution &SE; |
| 8566 | SmallVectorImpl<const SCEV *> &Strides; |
| 8567 | |
| 8568 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 8569 | : SE(SE), Strides(S) {} |
| 8570 | |
| 8571 | bool follow(const SCEV *S) { |
| 8572 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 8573 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 8574 | return true; |
| 8575 | } |
| 8576 | bool isDone() const { return false; } |
| 8577 | }; |
| 8578 | |
| 8579 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 8580 | struct SCEVCollectTerms { |
| 8581 | SmallVectorImpl<const SCEV *> &Terms; |
| 8582 | |
| 8583 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 8584 | : Terms(T) {} |
| 8585 | |
| 8586 | bool follow(const SCEV *S) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8587 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8588 | if (!containsUndefs(S)) |
| 8589 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8590 | |
| 8591 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8592 | return false; |
| 8593 | } |
| 8594 | |
| 8595 | // Keep looking. |
| 8596 | return true; |
| 8597 | } |
| 8598 | bool isDone() const { return false; } |
| 8599 | }; |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8600 | |
| 8601 | // Check if a SCEV contains an AddRecExpr. |
| 8602 | struct SCEVHasAddRec { |
| 8603 | bool &ContainsAddRec; |
| 8604 | |
| 8605 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { |
| 8606 | ContainsAddRec = false; |
| 8607 | } |
| 8608 | |
| 8609 | bool follow(const SCEV *S) { |
| 8610 | if (isa<SCEVAddRecExpr>(S)) { |
| 8611 | ContainsAddRec = true; |
| 8612 | |
| 8613 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8614 | return false; |
| 8615 | } |
| 8616 | |
| 8617 | // Keep looking. |
| 8618 | return true; |
| 8619 | } |
| 8620 | bool isDone() const { return false; } |
| 8621 | }; |
| 8622 | |
| 8623 | // Find factors that are multiplied with an expression that (possibly as a |
| 8624 | // subexpression) contains an AddRecExpr. In the expression: |
| 8625 | // |
| 8626 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) |
| 8627 | // |
| 8628 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" |
| 8629 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size |
| 8630 | // parameters as they form a product with an induction variable. |
| 8631 | // |
| 8632 | // This collector expects all array size parameters to be in the same MulExpr. |
| 8633 | // It might be necessary to later add support for collecting parameters that are |
| 8634 | // spread over different nested MulExpr. |
| 8635 | struct SCEVCollectAddRecMultiplies { |
| 8636 | SmallVectorImpl<const SCEV *> &Terms; |
| 8637 | ScalarEvolution &SE; |
| 8638 | |
| 8639 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) |
| 8640 | : Terms(T), SE(SE) {} |
| 8641 | |
| 8642 | bool follow(const SCEV *S) { |
| 8643 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { |
| 8644 | bool HasAddRec = false; |
| 8645 | SmallVector<const SCEV *, 0> Operands; |
| 8646 | for (auto Op : Mul->operands()) { |
| 8647 | if (isa<SCEVUnknown>(Op)) { |
| 8648 | Operands.push_back(Op); |
| 8649 | } else { |
| 8650 | bool ContainsAddRec; |
| 8651 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); |
| 8652 | visitAll(Op, ContiansAddRec); |
| 8653 | HasAddRec |= ContainsAddRec; |
| 8654 | } |
| 8655 | } |
| 8656 | if (Operands.size() == 0) |
| 8657 | return true; |
| 8658 | |
| 8659 | if (!HasAddRec) |
| 8660 | return false; |
| 8661 | |
| 8662 | Terms.push_back(SE.getMulExpr(Operands)); |
| 8663 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8664 | return false; |
| 8665 | } |
| 8666 | |
| 8667 | // Keep looking. |
| 8668 | return true; |
| 8669 | } |
| 8670 | bool isDone() const { return false; } |
| 8671 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8672 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8673 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8674 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in |
| 8675 | /// two places: |
| 8676 | /// 1) The strides of AddRec expressions. |
| 8677 | /// 2) Unknowns that are multiplied with AddRec expressions. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8678 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 8679 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8680 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8681 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 8682 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8683 | |
| 8684 | DEBUG({ |
| 8685 | dbgs() << "Strides:\n"; |
| 8686 | for (const SCEV *S : Strides) |
| 8687 | dbgs() << *S << "\n"; |
| 8688 | }); |
| 8689 | |
| 8690 | for (const SCEV *S : Strides) { |
| 8691 | SCEVCollectTerms TermCollector(Terms); |
| 8692 | visitAll(S, TermCollector); |
| 8693 | } |
| 8694 | |
| 8695 | DEBUG({ |
| 8696 | dbgs() << "Terms:\n"; |
| 8697 | for (const SCEV *T : Terms) |
| 8698 | dbgs() << *T << "\n"; |
| 8699 | }); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8700 | |
| 8701 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); |
| 8702 | visitAll(Expr, MulCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8703 | } |
| 8704 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8705 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8706 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 8707 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8708 | int Last = Terms.size() - 1; |
| 8709 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8710 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8711 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8712 | if (Last == 0) { |
| 8713 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8714 | SmallVector<const SCEV *, 2> Qs; |
| 8715 | for (const SCEV *Op : M->operands()) |
| 8716 | if (!isa<SCEVConstant>(Op)) |
| 8717 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8718 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8719 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8720 | } |
| 8721 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8722 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8723 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8724 | } |
| 8725 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 8726 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8727 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 8728 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 8729 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8730 | |
| 8731 | // Bail out when GCD does not evenly divide one of the terms. |
| 8732 | if (!R->isZero()) |
| 8733 | return false; |
| 8734 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 8735 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8736 | } |
| 8737 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 8738 | // Remove all SCEVConstants. |
Tobias Grosser | 1e9db7e | 2014-05-08 21:43:19 +0000 | [diff] [blame] | 8739 | Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) { |
| 8740 | return isa<SCEVConstant>(E); |
| 8741 | }), |
| 8742 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8743 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8744 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8745 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 8746 | return false; |
| 8747 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 8748 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8749 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8750 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8751 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8752 | // Returns true when S contains at least a SCEVUnknown parameter. |
| 8753 | static inline bool |
| 8754 | containsParameters(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 8755 | struct FindParameter { |
| 8756 | bool FoundParameter; |
| 8757 | FindParameter() : FoundParameter(false) {} |
| 8758 | |
| 8759 | bool follow(const SCEV *S) { |
| 8760 | if (isa<SCEVUnknown>(S)) { |
| 8761 | FoundParameter = true; |
| 8762 | // Stop recursion: we found a parameter. |
| 8763 | return false; |
| 8764 | } |
| 8765 | // Keep looking. |
| 8766 | return true; |
| 8767 | } |
| 8768 | bool isDone() const { |
| 8769 | // Stop recursion if we have found a parameter. |
| 8770 | return FoundParameter; |
| 8771 | } |
| 8772 | }; |
| 8773 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8774 | FindParameter F; |
| 8775 | SCEVTraversal<FindParameter> ST(F); |
| 8776 | ST.visitAll(S); |
| 8777 | |
| 8778 | return F.FoundParameter; |
| 8779 | } |
| 8780 | |
| 8781 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
| 8782 | static inline bool |
| 8783 | containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
| 8784 | for (const SCEV *T : Terms) |
| 8785 | if (containsParameters(T)) |
| 8786 | return true; |
| 8787 | return false; |
| 8788 | } |
| 8789 | |
| 8790 | // Return the number of product terms in S. |
| 8791 | static inline int numberOfTerms(const SCEV *S) { |
| 8792 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 8793 | return Expr->getNumOperands(); |
| 8794 | return 1; |
| 8795 | } |
| 8796 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8797 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 8798 | if (isa<SCEVConstant>(T)) |
| 8799 | return nullptr; |
| 8800 | |
| 8801 | if (isa<SCEVUnknown>(T)) |
| 8802 | return T; |
| 8803 | |
| 8804 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 8805 | SmallVector<const SCEV *, 2> Factors; |
| 8806 | for (const SCEV *Op : M->operands()) |
| 8807 | if (!isa<SCEVConstant>(Op)) |
| 8808 | Factors.push_back(Op); |
| 8809 | |
| 8810 | return SE.getMulExpr(Factors); |
| 8811 | } |
| 8812 | |
| 8813 | return T; |
| 8814 | } |
| 8815 | |
| 8816 | /// Return the size of an element read or written by Inst. |
| 8817 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 8818 | Type *Ty; |
| 8819 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 8820 | Ty = Store->getValueOperand()->getType(); |
| 8821 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 8822 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8823 | else |
| 8824 | return nullptr; |
| 8825 | |
| 8826 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 8827 | return getSizeOfExpr(ETy, Ty); |
| 8828 | } |
| 8829 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8830 | /// Second step of delinearization: compute the array dimensions Sizes from the |
| 8831 | /// set of Terms extracted from the memory access function of this SCEVAddRec. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8832 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 8833 | SmallVectorImpl<const SCEV *> &Sizes, |
| 8834 | const SCEV *ElementSize) const { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8835 | |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 8836 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8837 | return; |
| 8838 | |
| 8839 | // Early return when Terms do not contain parameters: we do not delinearize |
| 8840 | // non parametric SCEVs. |
| 8841 | if (!containsParameters(Terms)) |
| 8842 | return; |
| 8843 | |
| 8844 | DEBUG({ |
| 8845 | dbgs() << "Terms:\n"; |
| 8846 | for (const SCEV *T : Terms) |
| 8847 | dbgs() << *T << "\n"; |
| 8848 | }); |
| 8849 | |
| 8850 | // Remove duplicates. |
| 8851 | std::sort(Terms.begin(), Terms.end()); |
| 8852 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 8853 | |
| 8854 | // Put larger terms first. |
| 8855 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 8856 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 8857 | }); |
| 8858 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8859 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 8860 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8861 | // Try to divide all terms by the element size. If term is not divisible by |
| 8862 | // element size, proceed with the original term. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8863 | for (const SCEV *&Term : Terms) { |
| 8864 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 8865 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8866 | if (!Q->isZero()) |
| 8867 | Term = Q; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8868 | } |
| 8869 | |
| 8870 | SmallVector<const SCEV *, 4> NewTerms; |
| 8871 | |
| 8872 | // Remove constant factors. |
| 8873 | for (const SCEV *T : Terms) |
| 8874 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 8875 | NewTerms.push_back(NewT); |
| 8876 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8877 | DEBUG({ |
| 8878 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8879 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8880 | dbgs() << *T << "\n"; |
| 8881 | }); |
| 8882 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8883 | if (NewTerms.empty() || |
| 8884 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8885 | Sizes.clear(); |
| 8886 | return; |
| 8887 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8888 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8889 | // The last element to be pushed into Sizes is the size of an element. |
| 8890 | Sizes.push_back(ElementSize); |
| 8891 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8892 | DEBUG({ |
| 8893 | dbgs() << "Sizes:\n"; |
| 8894 | for (const SCEV *S : Sizes) |
| 8895 | dbgs() << *S << "\n"; |
| 8896 | }); |
| 8897 | } |
| 8898 | |
| 8899 | /// Third step of delinearization: compute the access functions for the |
| 8900 | /// Subscripts based on the dimensions in Sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8901 | void ScalarEvolution::computeAccessFunctions( |
| 8902 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 8903 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8904 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8905 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8906 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8907 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 8908 | |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 8909 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8910 | if (!AR->isAffine()) |
| 8911 | return; |
| 8912 | |
| 8913 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8914 | int Last = Sizes.size() - 1; |
| 8915 | for (int i = Last; i >= 0; i--) { |
| 8916 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 8917 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8918 | |
| 8919 | DEBUG({ |
| 8920 | dbgs() << "Res: " << *Res << "\n"; |
| 8921 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 8922 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 8923 | dbgs() << "Quotient: " << *Q << "\n"; |
| 8924 | dbgs() << "Remainder: " << *R << "\n"; |
| 8925 | }); |
| 8926 | |
| 8927 | Res = Q; |
| 8928 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8929 | // Do not record the last subscript corresponding to the size of elements in |
| 8930 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8931 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8932 | |
| 8933 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 8934 | if (isa<SCEVAddRecExpr>(R)) { |
| 8935 | Subscripts.clear(); |
| 8936 | Sizes.clear(); |
| 8937 | return; |
| 8938 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 8939 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8940 | continue; |
| 8941 | } |
| 8942 | |
| 8943 | // Record the access function for the current subscript. |
| 8944 | Subscripts.push_back(R); |
| 8945 | } |
| 8946 | |
| 8947 | // Also push in last position the remainder of the last division: it will be |
| 8948 | // the access function of the innermost dimension. |
| 8949 | Subscripts.push_back(Res); |
| 8950 | |
| 8951 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 8952 | |
| 8953 | DEBUG({ |
| 8954 | dbgs() << "Subscripts:\n"; |
| 8955 | for (const SCEV *S : Subscripts) |
| 8956 | dbgs() << *S << "\n"; |
| 8957 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8958 | } |
| 8959 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 8960 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 8961 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 8962 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 8963 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 8964 | /// expressions in the stride and base of a SCEV corresponding to the |
| 8965 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 8966 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 8967 | /// |
| 8968 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 8969 | /// |
| 8970 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 8971 | /// |
| 8972 | /// for (long i = 0; i < n; i++) |
| 8973 | /// for (long j = 0; j < m; j++) |
| 8974 | /// for (long k = 0; k < o; k++) |
| 8975 | /// A[i][j][k] = 1.0; |
| 8976 | /// } |
| 8977 | /// |
| 8978 | /// the delinearization input is the following AddRec SCEV: |
| 8979 | /// |
| 8980 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 8981 | /// |
| 8982 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 8983 | /// because it appears as an offset that does not divide any of the strides in |
| 8984 | /// the loops: |
| 8985 | /// |
| 8986 | /// CHECK: Base offset: %A |
| 8987 | /// |
| 8988 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 8989 | /// the array as these are the multiples by which the strides are happening: |
| 8990 | /// |
| 8991 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 8992 | /// |
| 8993 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 8994 | /// no strides that would help identifying the size of the last dimension: when |
| 8995 | /// the array has been statically allocated, one could compute the size of that |
| 8996 | /// dimension by dividing the overall size of the array by the size of the known |
| 8997 | /// dimensions: %m * %o * 8. |
| 8998 | /// |
| 8999 | /// Finally delinearize provides the access functions for the array reference |
| 9000 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 9001 | /// |
| 9002 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 9003 | /// |
| 9004 | /// The testcases are checking the output of a function pass: |
| 9005 | /// DelinearizationPass that walks through all loads and stores of a function |
| 9006 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 9007 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 9008 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9009 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9010 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 9011 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9012 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9013 | // First step: collect parametric terms. |
| 9014 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9015 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9016 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9017 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9018 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9019 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9020 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9021 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9022 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9023 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9024 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9025 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9026 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9027 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9028 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9029 | if (Subscripts.empty()) |
| 9030 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9031 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9032 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9033 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9034 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 9035 | for (const SCEV *S : Sizes) |
| 9036 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9037 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 9038 | dbgs() << "\nArrayRef"; |
| 9039 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9040 | dbgs() << "[" << *S << "]"; |
| 9041 | dbgs() << "\n"; |
| 9042 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9043 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9044 | |
| 9045 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9046 | // SCEVCallbackVH Class Implementation |
| 9047 | //===----------------------------------------------------------------------===// |
| 9048 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9049 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9050 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9051 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 9052 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9053 | SE->eraseValueFromMap(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9054 | // this now dangles! |
| 9055 | } |
| 9056 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 9057 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9058 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 9059 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9060 | // Forget all the expressions associated with users of the old value, |
| 9061 | // so that future queries will recompute the expressions using the new |
| 9062 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9063 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9064 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9065 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9066 | while (!Worklist.empty()) { |
| 9067 | User *U = Worklist.pop_back_val(); |
| 9068 | // Deleting the Old value will cause this to dangle. Postpone |
| 9069 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9070 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9071 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 9072 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9073 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9074 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 9075 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9076 | SE->eraseValueFromMap(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9077 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9078 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9079 | // Delete the Old value. |
| 9080 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 9081 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9082 | SE->eraseValueFromMap(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9083 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9084 | } |
| 9085 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9086 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9087 | : CallbackVH(V), SE(se) {} |
| 9088 | |
| 9089 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9090 | // ScalarEvolution Class Implementation |
| 9091 | //===----------------------------------------------------------------------===// |
| 9092 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9093 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
| 9094 | AssumptionCache &AC, DominatorTree &DT, |
| 9095 | LoopInfo &LI) |
| 9096 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
| 9097 | CouldNotCompute(new SCEVCouldNotCompute()), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9098 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
| 9099 | ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), |
| 9100 | FirstUnknown(nullptr) {} |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9101 | |
| 9102 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
| 9103 | : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), |
| 9104 | CouldNotCompute(std::move(Arg.CouldNotCompute)), |
| 9105 | ValueExprMap(std::move(Arg.ValueExprMap)), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9106 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9107 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
| 9108 | ConstantEvolutionLoopExitValue( |
| 9109 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 9110 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 9111 | LoopDispositions(std::move(Arg.LoopDispositions)), |
| 9112 | BlockDispositions(std::move(Arg.BlockDispositions)), |
| 9113 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 9114 | SignedRanges(std::move(Arg.SignedRanges)), |
| 9115 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9116 | UniquePreds(std::move(Arg.UniquePreds)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9117 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 9118 | FirstUnknown(Arg.FirstUnknown) { |
| 9119 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9120 | } |
| 9121 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9122 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9123 | // Iterate through all the SCEVUnknown instances and call their |
| 9124 | // destructors, so that they release their references to their values. |
Naomi Musgrave | f90c1be | 2015-09-16 23:46:40 +0000 | [diff] [blame] | 9125 | for (SCEVUnknown *U = FirstUnknown; U;) { |
| 9126 | SCEVUnknown *Tmp = U; |
| 9127 | U = U->Next; |
| 9128 | Tmp->~SCEVUnknown(); |
| 9129 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 9130 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9131 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9132 | ExprValueMap.clear(); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 9133 | ValueExprMap.clear(); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9134 | HasRecMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9135 | |
| 9136 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 9137 | // that a loop had multiple computable exits. |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9138 | for (auto &BTCI : BackedgeTakenCounts) |
| 9139 | BTCI.second.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9140 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 9141 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 9142 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9143 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 9144 | } |
| 9145 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9146 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9147 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9148 | } |
| 9149 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9150 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9151 | const Loop *L) { |
| 9152 | // Print all inner loops first |
| 9153 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 9154 | PrintLoopInfo(OS, SE, *I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9155 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9156 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9157 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9158 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9159 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9160 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9161 | L->getExitBlocks(ExitBlocks); |
| 9162 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 9163 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9164 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9165 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 9166 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9167 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9168 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9169 | } |
| 9170 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9171 | OS << "\n" |
| 9172 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9173 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9174 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9175 | |
| 9176 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 9177 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
| 9178 | } else { |
| 9179 | OS << "Unpredictable max backedge-taken count. "; |
| 9180 | } |
| 9181 | |
| 9182 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9183 | } |
| 9184 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9185 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 9186 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9187 | // out SCEV values of all instructions that are interesting. Doing |
| 9188 | // this potentially causes it to create new SCEV objects though, |
| 9189 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 9190 | // observable from outside the class though, so casting away the |
| 9191 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9192 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9193 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9194 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9195 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9196 | OS << "\n"; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9197 | for (Instruction &I : instructions(F)) |
| 9198 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { |
| 9199 | OS << I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 9200 | OS << " --> "; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9201 | const SCEV *SV = SE.getSCEV(&I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9202 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9203 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 9204 | OS << " U: "; |
| 9205 | SE.getUnsignedRange(SV).print(OS); |
| 9206 | OS << " S: "; |
| 9207 | SE.getSignedRange(SV).print(OS); |
| 9208 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9209 | |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9210 | const Loop *L = LI.getLoopFor(I.getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9211 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9212 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9213 | if (AtUse != SV) { |
| 9214 | OS << " --> "; |
| 9215 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9216 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 9217 | OS << " U: "; |
| 9218 | SE.getUnsignedRange(AtUse).print(OS); |
| 9219 | OS << " S: "; |
| 9220 | SE.getSignedRange(AtUse).print(OS); |
| 9221 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9222 | } |
| 9223 | |
| 9224 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 9225 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9226 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9227 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9228 | OS << "<<Unknown>>"; |
| 9229 | } else { |
| 9230 | OS << *ExitValue; |
| 9231 | } |
| 9232 | } |
| 9233 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9234 | OS << "\n"; |
| 9235 | } |
| 9236 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9237 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9238 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9239 | OS << "\n"; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9240 | for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9241 | PrintLoopInfo(OS, &SE, *I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9242 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 9243 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9244 | ScalarEvolution::LoopDisposition |
| 9245 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9246 | auto &Values = LoopDispositions[S]; |
| 9247 | for (auto &V : Values) { |
| 9248 | if (V.getPointer() == L) |
| 9249 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9250 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9251 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9252 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9253 | auto &Values2 = LoopDispositions[S]; |
| 9254 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9255 | if (V.getPointer() == L) { |
| 9256 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9257 | break; |
| 9258 | } |
| 9259 | } |
| 9260 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9261 | } |
| 9262 | |
| 9263 | ScalarEvolution::LoopDisposition |
| 9264 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9265 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9266 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9267 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9268 | case scTruncate: |
| 9269 | case scZeroExtend: |
| 9270 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9271 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9272 | case scAddRecExpr: { |
| 9273 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 9274 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9275 | // If L is the addrec's loop, it's computable. |
| 9276 | if (AR->getLoop() == L) |
| 9277 | return LoopComputable; |
| 9278 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9279 | // Add recurrences are never invariant in the function-body (null loop). |
| 9280 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9281 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9282 | |
| 9283 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 9284 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9285 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9286 | |
| 9287 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 9288 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9289 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9290 | |
| 9291 | // This recurrence is variant w.r.t. L if any of its operands |
| 9292 | // are variant. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9293 | for (auto *Op : AR->operands()) |
| 9294 | if (!isLoopInvariant(Op, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9295 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9296 | |
| 9297 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9298 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9299 | } |
| 9300 | case scAddExpr: |
| 9301 | case scMulExpr: |
| 9302 | case scUMaxExpr: |
| 9303 | case scSMaxExpr: { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9304 | bool HasVarying = false; |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9305 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { |
| 9306 | LoopDisposition D = getLoopDisposition(Op, L); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9307 | if (D == LoopVariant) |
| 9308 | return LoopVariant; |
| 9309 | if (D == LoopComputable) |
| 9310 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9311 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9312 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9313 | } |
| 9314 | case scUDivExpr: { |
| 9315 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9316 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 9317 | if (LD == LoopVariant) |
| 9318 | return LoopVariant; |
| 9319 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 9320 | if (RD == LoopVariant) |
| 9321 | return LoopVariant; |
| 9322 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 9323 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9324 | } |
| 9325 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9326 | // All non-instruction values are loop invariant. All instructions are loop |
| 9327 | // invariant if they are not contained in the specified loop. |
| 9328 | // Instructions are never considered invariant in the function body |
| 9329 | // (null loop) because they are defined within the "loop". |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9330 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9331 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 9332 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9333 | case scCouldNotCompute: |
| 9334 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9335 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9336 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9337 | } |
| 9338 | |
| 9339 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 9340 | return getLoopDisposition(S, L) == LoopInvariant; |
| 9341 | } |
| 9342 | |
| 9343 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 9344 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9345 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9346 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9347 | ScalarEvolution::BlockDisposition |
| 9348 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9349 | auto &Values = BlockDispositions[S]; |
| 9350 | for (auto &V : Values) { |
| 9351 | if (V.getPointer() == BB) |
| 9352 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9353 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9354 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9355 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9356 | auto &Values2 = BlockDispositions[S]; |
| 9357 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9358 | if (V.getPointer() == BB) { |
| 9359 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9360 | break; |
| 9361 | } |
| 9362 | } |
| 9363 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9364 | } |
| 9365 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9366 | ScalarEvolution::BlockDisposition |
| 9367 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9368 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9369 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9370 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9371 | case scTruncate: |
| 9372 | case scZeroExtend: |
| 9373 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9374 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9375 | case scAddRecExpr: { |
| 9376 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9377 | // to test for proper dominance too, because the instruction which |
| 9378 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 9379 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9380 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9381 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9382 | return DoesNotDominateBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9383 | } |
| 9384 | // FALL THROUGH into SCEVNAryExpr handling. |
| 9385 | case scAddExpr: |
| 9386 | case scMulExpr: |
| 9387 | case scUMaxExpr: |
| 9388 | case scSMaxExpr: { |
| 9389 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9390 | bool Proper = true; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 9391 | for (const SCEV *NAryOp : NAry->operands()) { |
| 9392 | BlockDisposition D = getBlockDisposition(NAryOp, BB); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9393 | if (D == DoesNotDominateBlock) |
| 9394 | return DoesNotDominateBlock; |
| 9395 | if (D == DominatesBlock) |
| 9396 | Proper = false; |
| 9397 | } |
| 9398 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9399 | } |
| 9400 | case scUDivExpr: { |
| 9401 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9402 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 9403 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 9404 | if (LD == DoesNotDominateBlock) |
| 9405 | return DoesNotDominateBlock; |
| 9406 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 9407 | if (RD == DoesNotDominateBlock) |
| 9408 | return DoesNotDominateBlock; |
| 9409 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 9410 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9411 | } |
| 9412 | case scUnknown: |
| 9413 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9414 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 9415 | if (I->getParent() == BB) |
| 9416 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9417 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9418 | return ProperlyDominatesBlock; |
| 9419 | return DoesNotDominateBlock; |
| 9420 | } |
| 9421 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9422 | case scCouldNotCompute: |
| 9423 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9424 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9425 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9426 | } |
| 9427 | |
| 9428 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 9429 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 9430 | } |
| 9431 | |
| 9432 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 9433 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9434 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9435 | |
| 9436 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 9437 | // Search for a SCEV expression node within an expression tree. |
| 9438 | // Implements SCEVTraversal::Visitor. |
| 9439 | struct SCEVSearch { |
| 9440 | const SCEV *Node; |
| 9441 | bool IsFound; |
| 9442 | |
| 9443 | SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} |
| 9444 | |
| 9445 | bool follow(const SCEV *S) { |
| 9446 | IsFound |= (S == Node); |
| 9447 | return !IsFound; |
| 9448 | } |
| 9449 | bool isDone() const { return IsFound; } |
| 9450 | }; |
| 9451 | |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 9452 | SCEVSearch Search(Op); |
| 9453 | visitAll(S, Search); |
| 9454 | return Search.IsFound; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9455 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9456 | |
| 9457 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 9458 | ValuesAtScopes.erase(S); |
| 9459 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9460 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9461 | UnsignedRanges.erase(S); |
| 9462 | SignedRanges.erase(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9463 | ExprValueMap.erase(S); |
| 9464 | HasRecMap.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 9465 | |
| 9466 | for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = |
| 9467 | BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) { |
| 9468 | BackedgeTakenInfo &BEInfo = I->second; |
| 9469 | if (BEInfo.hasOperand(S, this)) { |
| 9470 | BEInfo.clear(); |
| 9471 | BackedgeTakenCounts.erase(I++); |
| 9472 | } |
| 9473 | else |
| 9474 | ++I; |
| 9475 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9476 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9477 | |
| 9478 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9479 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 9480 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9481 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 9482 | size_t Pos = 0; |
| 9483 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 9484 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 9485 | Pos += To.size(); |
| 9486 | } |
| 9487 | } |
| 9488 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9489 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 9490 | static void |
| 9491 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9492 | std::string &S = Map[L]; |
| 9493 | if (S.empty()) { |
| 9494 | raw_string_ostream OS(S); |
| 9495 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9496 | |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9497 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 9498 | replaceSubString(OS.str(), "false", "0"); |
| 9499 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 9500 | // FIXME: Remove this when SCEV gets smarter about them. |
| 9501 | replaceSubString(OS.str(), "<nw>", ""); |
| 9502 | replaceSubString(OS.str(), "<nsw>", ""); |
| 9503 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9504 | } |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9505 | |
JF Bastien | 61ad8b3 | 2015-12-23 18:18:53 +0000 | [diff] [blame] | 9506 | for (auto *R : reverse(*L)) |
| 9507 | getLoopBackedgeTakenCounts(R, Map, SE); // recurse. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9508 | } |
| 9509 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9510 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9511 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9512 | |
| 9513 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 9514 | // FIXME: It would be much better to store actual values instead of strings, |
| 9515 | // but SCEV pointers will change if we drop the caches. |
| 9516 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9517 | 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] | 9518 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 9519 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9520 | // Gather stringified backedge taken counts for all loops using a fresh |
| 9521 | // ScalarEvolution object. |
| 9522 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
| 9523 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 9524 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9525 | |
| 9526 | // Now compare whether they're the same with and without caches. This allows |
| 9527 | // verifying that no pass changed the cache. |
| 9528 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 9529 | "New loops suddenly appeared!"); |
| 9530 | |
| 9531 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 9532 | OldE = BackedgeDumpsOld.end(), |
| 9533 | NewI = BackedgeDumpsNew.begin(); |
| 9534 | OldI != OldE; ++OldI, ++NewI) { |
| 9535 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 9536 | |
| 9537 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 9538 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9539 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9540 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 9541 | // usually not harmful. |
| 9542 | if (OldI->second != NewI->second && |
| 9543 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9544 | NewI->second.find("undef") == std::string::npos && |
| 9545 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9546 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9547 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9548 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9549 | << "' changed from '" << OldI->second |
| 9550 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9551 | std::abort(); |
| 9552 | } |
| 9553 | } |
| 9554 | |
| 9555 | // TODO: Verify more things. |
| 9556 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9557 | |
| 9558 | char ScalarEvolutionAnalysis::PassID; |
| 9559 | |
| 9560 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
| 9561 | AnalysisManager<Function> *AM) { |
| 9562 | return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F), |
| 9563 | AM->getResult<AssumptionAnalysis>(F), |
| 9564 | AM->getResult<DominatorTreeAnalysis>(F), |
| 9565 | AM->getResult<LoopAnalysis>(F)); |
| 9566 | } |
| 9567 | |
| 9568 | PreservedAnalyses |
| 9569 | ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) { |
| 9570 | AM->getResult<ScalarEvolutionAnalysis>(F).print(OS); |
| 9571 | return PreservedAnalyses::all(); |
| 9572 | } |
| 9573 | |
| 9574 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 9575 | "Scalar Evolution Analysis", false, true) |
| 9576 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 9577 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 9578 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 9579 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 9580 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 9581 | "Scalar Evolution Analysis", false, true) |
| 9582 | char ScalarEvolutionWrapperPass::ID = 0; |
| 9583 | |
| 9584 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 9585 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 9586 | } |
| 9587 | |
| 9588 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 9589 | SE.reset(new ScalarEvolution( |
| 9590 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 9591 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 9592 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 9593 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 9594 | return false; |
| 9595 | } |
| 9596 | |
| 9597 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 9598 | |
| 9599 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 9600 | SE->print(OS); |
| 9601 | } |
| 9602 | |
| 9603 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 9604 | if (!VerifySCEV) |
| 9605 | return; |
| 9606 | |
| 9607 | SE->verify(); |
| 9608 | } |
| 9609 | |
| 9610 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 9611 | AU.setPreservesAll(); |
| 9612 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
| 9613 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 9614 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 9615 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 9616 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9617 | |
| 9618 | const SCEVPredicate * |
| 9619 | ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, |
| 9620 | const SCEVConstant *RHS) { |
| 9621 | FoldingSetNodeID ID; |
| 9622 | // Unique this node based on the arguments |
| 9623 | ID.AddInteger(SCEVPredicate::P_Equal); |
| 9624 | ID.AddPointer(LHS); |
| 9625 | ID.AddPointer(RHS); |
| 9626 | void *IP = nullptr; |
| 9627 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 9628 | return S; |
| 9629 | SCEVEqualPredicate *Eq = new (SCEVAllocator) |
| 9630 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); |
| 9631 | UniquePreds.InsertNode(Eq, IP); |
| 9632 | return Eq; |
| 9633 | } |
| 9634 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9635 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( |
| 9636 | const SCEVAddRecExpr *AR, |
| 9637 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 9638 | FoldingSetNodeID ID; |
| 9639 | // Unique this node based on the arguments |
| 9640 | ID.AddInteger(SCEVPredicate::P_Wrap); |
| 9641 | ID.AddPointer(AR); |
| 9642 | ID.AddInteger(AddedFlags); |
| 9643 | void *IP = nullptr; |
| 9644 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 9645 | return S; |
| 9646 | auto *OF = new (SCEVAllocator) |
| 9647 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); |
| 9648 | UniquePreds.InsertNode(OF, IP); |
| 9649 | return OF; |
| 9650 | } |
| 9651 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 9652 | namespace { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9653 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9654 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { |
| 9655 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9656 | // 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] | 9657 | // If Assume is true, rewrite is free to add further predicates to A |
| 9658 | // such that the result will be an AddRecExpr. |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9659 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, |
| 9660 | SCEVUnionPredicate &A, bool Assume) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9661 | SCEVPredicateRewriter Rewriter(L, SE, A, Assume); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9662 | return Rewriter.visit(S); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9663 | } |
| 9664 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9665 | SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, |
| 9666 | SCEVUnionPredicate &P, bool Assume) |
| 9667 | : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {} |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9668 | |
| 9669 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 9670 | auto ExprPreds = P.getPredicatesForExpr(Expr); |
| 9671 | for (auto *Pred : ExprPreds) |
| 9672 | if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred)) |
| 9673 | if (IPred->getLHS() == Expr) |
| 9674 | return IPred->getRHS(); |
| 9675 | |
| 9676 | return Expr; |
| 9677 | } |
| 9678 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9679 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { |
| 9680 | const SCEV *Operand = visit(Expr->getOperand()); |
| 9681 | const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); |
| 9682 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 9683 | // This couldn't be folded because the operand didn't have the nuw |
| 9684 | // flag. Add the nusw flag as an assumption that we could make. |
| 9685 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 9686 | Type *Ty = Expr->getType(); |
| 9687 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) |
| 9688 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), |
| 9689 | SE.getSignExtendExpr(Step, Ty), L, |
| 9690 | AR->getNoWrapFlags()); |
| 9691 | } |
| 9692 | return SE.getZeroExtendExpr(Operand, Expr->getType()); |
| 9693 | } |
| 9694 | |
| 9695 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { |
| 9696 | const SCEV *Operand = visit(Expr->getOperand()); |
| 9697 | const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); |
| 9698 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 9699 | // This couldn't be folded because the operand didn't have the nsw |
| 9700 | // flag. Add the nssw flag as an assumption that we could make. |
| 9701 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 9702 | Type *Ty = Expr->getType(); |
| 9703 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) |
| 9704 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), |
| 9705 | SE.getSignExtendExpr(Step, Ty), L, |
| 9706 | AR->getNoWrapFlags()); |
| 9707 | } |
| 9708 | return SE.getSignExtendExpr(Operand, Expr->getType()); |
| 9709 | } |
| 9710 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9711 | private: |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9712 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, |
| 9713 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 9714 | auto *A = SE.getWrapPredicate(AR, AddedFlags); |
| 9715 | if (!Assume) { |
| 9716 | // Check if we've already made this assumption. |
| 9717 | if (P.implies(A)) |
| 9718 | return true; |
| 9719 | return false; |
| 9720 | } |
| 9721 | P.add(A); |
| 9722 | return true; |
| 9723 | } |
| 9724 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9725 | SCEVUnionPredicate &P; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9726 | const Loop *L; |
| 9727 | bool Assume; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9728 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 9729 | } // end anonymous namespace |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9730 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9731 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9732 | SCEVUnionPredicate &Preds) { |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9733 | return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9734 | } |
| 9735 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 9736 | const SCEV * |
| 9737 | ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, |
| 9738 | SCEVUnionPredicate &Preds) { |
| 9739 | return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, true); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9740 | } |
| 9741 | |
| 9742 | /// SCEV predicates |
| 9743 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, |
| 9744 | SCEVPredicateKind Kind) |
| 9745 | : FastID(ID), Kind(Kind) {} |
| 9746 | |
| 9747 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, |
| 9748 | const SCEVUnknown *LHS, |
| 9749 | const SCEVConstant *RHS) |
| 9750 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} |
| 9751 | |
| 9752 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { |
| 9753 | const auto *Op = dyn_cast<const SCEVEqualPredicate>(N); |
| 9754 | |
| 9755 | if (!Op) |
| 9756 | return false; |
| 9757 | |
| 9758 | return Op->LHS == LHS && Op->RHS == RHS; |
| 9759 | } |
| 9760 | |
| 9761 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } |
| 9762 | |
| 9763 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } |
| 9764 | |
| 9765 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 9766 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; |
| 9767 | } |
| 9768 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9769 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, |
| 9770 | const SCEVAddRecExpr *AR, |
| 9771 | IncrementWrapFlags Flags) |
| 9772 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} |
| 9773 | |
| 9774 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } |
| 9775 | |
| 9776 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { |
| 9777 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); |
| 9778 | |
| 9779 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; |
| 9780 | } |
| 9781 | |
| 9782 | bool SCEVWrapPredicate::isAlwaysTrue() const { |
| 9783 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); |
| 9784 | IncrementWrapFlags IFlags = Flags; |
| 9785 | |
| 9786 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) |
| 9787 | IFlags = clearFlags(IFlags, IncrementNSSW); |
| 9788 | |
| 9789 | return IFlags == IncrementAnyWrap; |
| 9790 | } |
| 9791 | |
| 9792 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 9793 | OS.indent(Depth) << *getExpr() << " Added Flags: "; |
| 9794 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) |
| 9795 | OS << "<nusw>"; |
| 9796 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) |
| 9797 | OS << "<nssw>"; |
| 9798 | OS << "\n"; |
| 9799 | } |
| 9800 | |
| 9801 | SCEVWrapPredicate::IncrementWrapFlags |
| 9802 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, |
| 9803 | ScalarEvolution &SE) { |
| 9804 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; |
| 9805 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); |
| 9806 | |
| 9807 | // We can safely transfer the NSW flag as NSSW. |
| 9808 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) |
| 9809 | ImpliedFlags = IncrementNSSW; |
| 9810 | |
| 9811 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { |
| 9812 | // If the increment is positive, the SCEV NUW flag will also imply the |
| 9813 | // WrapPredicate NUSW flag. |
| 9814 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 9815 | if (Step->getValue()->getValue().isNonNegative()) |
| 9816 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); |
| 9817 | } |
| 9818 | |
| 9819 | return ImpliedFlags; |
| 9820 | } |
| 9821 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9822 | /// Union predicates don't get cached so create a dummy set ID for it. |
| 9823 | SCEVUnionPredicate::SCEVUnionPredicate() |
| 9824 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} |
| 9825 | |
| 9826 | bool SCEVUnionPredicate::isAlwaysTrue() const { |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 9827 | return all_of(Preds, |
| 9828 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9829 | } |
| 9830 | |
| 9831 | ArrayRef<const SCEVPredicate *> |
| 9832 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { |
| 9833 | auto I = SCEVToPreds.find(Expr); |
| 9834 | if (I == SCEVToPreds.end()) |
| 9835 | return ArrayRef<const SCEVPredicate *>(); |
| 9836 | return I->second; |
| 9837 | } |
| 9838 | |
| 9839 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { |
| 9840 | if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 9841 | return all_of(Set->Preds, |
| 9842 | [this](const SCEVPredicate *I) { return this->implies(I); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9843 | |
| 9844 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); |
| 9845 | if (ScevPredsIt == SCEVToPreds.end()) |
| 9846 | return false; |
| 9847 | auto &SCEVPreds = ScevPredsIt->second; |
| 9848 | |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 9849 | return any_of(SCEVPreds, |
| 9850 | [N](const SCEVPredicate *I) { return I->implies(N); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9851 | } |
| 9852 | |
| 9853 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } |
| 9854 | |
| 9855 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 9856 | for (auto Pred : Preds) |
| 9857 | Pred->print(OS, Depth); |
| 9858 | } |
| 9859 | |
| 9860 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { |
| 9861 | if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) { |
| 9862 | for (auto Pred : Set->Preds) |
| 9863 | add(Pred); |
| 9864 | return; |
| 9865 | } |
| 9866 | |
| 9867 | if (implies(N)) |
| 9868 | return; |
| 9869 | |
| 9870 | const SCEV *Key = N->getExpr(); |
| 9871 | assert(Key && "Only SCEVUnionPredicate doesn't have an " |
| 9872 | " associated expression!"); |
| 9873 | |
| 9874 | SCEVToPreds[Key].push_back(N); |
| 9875 | Preds.push_back(N); |
| 9876 | } |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 9877 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9878 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, |
| 9879 | Loop &L) |
| 9880 | : SE(SE), L(L), Generation(0) {} |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 9881 | |
| 9882 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { |
| 9883 | const SCEV *Expr = SE.getSCEV(V); |
| 9884 | RewriteEntry &Entry = RewriteMap[Expr]; |
| 9885 | |
| 9886 | // If we already have an entry and the version matches, return it. |
| 9887 | if (Entry.second && Generation == Entry.first) |
| 9888 | return Entry.second; |
| 9889 | |
| 9890 | // We found an entry but it's stale. Rewrite the stale entry |
| 9891 | // acording to the current predicate. |
| 9892 | if (Entry.second) |
| 9893 | Expr = Entry.second; |
| 9894 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9895 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 9896 | Entry = {Generation, NewSCEV}; |
| 9897 | |
| 9898 | return NewSCEV; |
| 9899 | } |
| 9900 | |
| 9901 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { |
| 9902 | if (Preds.implies(&Pred)) |
| 9903 | return; |
| 9904 | Preds.add(&Pred); |
| 9905 | updateGeneration(); |
| 9906 | } |
| 9907 | |
| 9908 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { |
| 9909 | return Preds; |
| 9910 | } |
| 9911 | |
| 9912 | void PredicatedScalarEvolution::updateGeneration() { |
| 9913 | // If the generation number wrapped recompute everything. |
| 9914 | if (++Generation == 0) { |
| 9915 | for (auto &II : RewriteMap) { |
| 9916 | const SCEV *Rewritten = II.second.second; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9917 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 9918 | } |
| 9919 | } |
| 9920 | } |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 9921 | |
| 9922 | void PredicatedScalarEvolution::setNoOverflow( |
| 9923 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 9924 | const SCEV *Expr = getSCEV(V); |
| 9925 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 9926 | |
| 9927 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); |
| 9928 | |
| 9929 | // Clear the statically implied flags. |
| 9930 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); |
| 9931 | addPredicate(*SE.getWrapPredicate(AR, Flags)); |
| 9932 | |
| 9933 | auto II = FlagsMap.insert({V, Flags}); |
| 9934 | if (!II.second) |
| 9935 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); |
| 9936 | } |
| 9937 | |
| 9938 | bool PredicatedScalarEvolution::hasNoOverflow( |
| 9939 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 9940 | const SCEV *Expr = getSCEV(V); |
| 9941 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 9942 | |
| 9943 | Flags = SCEVWrapPredicate::clearFlags( |
| 9944 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); |
| 9945 | |
| 9946 | auto II = FlagsMap.find(V); |
| 9947 | |
| 9948 | if (II != FlagsMap.end()) |
| 9949 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); |
| 9950 | |
| 9951 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; |
| 9952 | } |
| 9953 | |
| 9954 | const SCEV *PredicatedScalarEvolution::getAsAddRec(Value *V) { |
| 9955 | const SCEV *Expr = this->getSCEV(V); |
| 9956 | const SCEV *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds); |
| 9957 | updateGeneration(); |
| 9958 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; |
| 9959 | return New; |
| 9960 | } |
| 9961 | |
| 9962 | PredicatedScalarEvolution:: |
| 9963 | PredicatedScalarEvolution(const PredicatedScalarEvolution &Init) : |
| 9964 | RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), |
| 9965 | Generation(Init.Generation) { |
| 9966 | for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I) |
| 9967 | FlagsMap.insert(*I); |
| 9968 | } |