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" |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 64 | #include "llvm/ADT/ScopeExit.h" |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 65 | #include "llvm/ADT/Sequence.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 66 | #include "llvm/ADT/SmallPtrSet.h" |
| 67 | #include "llvm/ADT/Statistic.h" |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/AssumptionCache.h" |
John Criswell | fe5f33b | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/ConstantFolding.h" |
Duncan Sands | d06f50e | 2010-11-17 04:18:45 +0000 | [diff] [blame] | 70 | #include "llvm/Analysis/InstructionSimplify.h" |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 71 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 72 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 73 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 74 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 75 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 76 | #include "llvm/IR/Constants.h" |
| 77 | #include "llvm/IR/DataLayout.h" |
| 78 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 79 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 80 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 81 | #include "llvm/IR/GlobalAlias.h" |
| 82 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 8394857 | 2014-03-04 10:30:26 +0000 | [diff] [blame] | 83 | #include "llvm/IR/InstIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 84 | #include "llvm/IR/Instructions.h" |
| 85 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 86 | #include "llvm/IR/Metadata.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 87 | #include "llvm/IR/Operator.h" |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 88 | #include "llvm/IR/PatternMatch.h" |
Chris Lattner | 996795b | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 89 | #include "llvm/Support/CommandLine.h" |
David Greene | 2330f78 | 2009-12-23 22:58:38 +0000 | [diff] [blame] | 90 | #include "llvm/Support/Debug.h" |
Torok Edwin | 56d0659 | 2009-07-11 20:10:48 +0000 | [diff] [blame] | 91 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | 0a1e993 | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 92 | #include "llvm/Support/MathExtras.h" |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 93 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 94 | #include "llvm/Support/SaveAndRestore.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 95 | #include <algorithm> |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 96 | using namespace llvm; |
| 97 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 98 | #define DEBUG_TYPE "scalar-evolution" |
| 99 | |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 100 | STATISTIC(NumArrayLenItCounts, |
| 101 | "Number of trip counts computed with array length"); |
| 102 | STATISTIC(NumTripCountsComputed, |
| 103 | "Number of loops with predictable loop counts"); |
| 104 | STATISTIC(NumTripCountsNotComputed, |
| 105 | "Number of loops without predictable loop counts"); |
| 106 | STATISTIC(NumBruteForceTripCountsComputed, |
| 107 | "Number of loops with trip counts computed by force"); |
| 108 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 109 | static cl::opt<unsigned> |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 110 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 111 | cl::desc("Maximum number of iterations SCEV will " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 112 | "symbolically execute a constant " |
| 113 | "derived loop"), |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 114 | cl::init(100)); |
| 115 | |
Filipe Cabecinhas | 0da9937 | 2016-04-29 15:22:48 +0000 | [diff] [blame] | 116 | // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 117 | static cl::opt<bool> |
| 118 | VerifySCEV("verify-scev", |
| 119 | cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 120 | static cl::opt<bool> |
| 121 | VerifySCEVMap("verify-scev-maps", |
Jeroen Ketema | e48e393 | 2016-04-12 23:21:46 +0000 | [diff] [blame] | 122 | cl::desc("Verify no dangling value in ScalarEvolution's " |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 123 | "ExprValueMap (slow)")); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 124 | |
Li Huang | fcfe8cd | 2016-10-20 21:38:39 +0000 | [diff] [blame] | 125 | static cl::opt<unsigned> MulOpsInlineThreshold( |
| 126 | "scev-mulops-inline-threshold", cl::Hidden, |
| 127 | cl::desc("Threshold for inlining multiplication operands into a SCEV"), |
| 128 | cl::init(1000)); |
| 129 | |
Daniil Fukalov | b09dac5 | 2017-01-26 13:33:17 +0000 | [diff] [blame^] | 130 | static cl::opt<unsigned> AddOpsInlineThreshold( |
| 131 | "scev-addops-inline-threshold", cl::Hidden, |
| 132 | cl::desc("Threshold for inlining multiplication operands into a SCEV"), |
| 133 | cl::init(500)); |
| 134 | |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 135 | static cl::opt<unsigned> |
| 136 | MaxCompareDepth("scalar-evolution-max-compare-depth", cl::Hidden, |
| 137 | cl::desc("Maximum depth of recursive compare complexity"), |
| 138 | cl::init(32)); |
| 139 | |
Michael Liao | 468fb74 | 2017-01-13 18:28:30 +0000 | [diff] [blame] | 140 | static cl::opt<unsigned> MaxConstantEvolvingDepth( |
| 141 | "scalar-evolution-max-constant-evolving-depth", cl::Hidden, |
| 142 | cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); |
| 143 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 144 | //===----------------------------------------------------------------------===// |
| 145 | // SCEV class definitions |
| 146 | //===----------------------------------------------------------------------===// |
| 147 | |
| 148 | //===----------------------------------------------------------------------===// |
| 149 | // Implementation of the SCEV class. |
| 150 | // |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 151 | |
Davide Italiano | 2071f4c | 2015-10-25 19:55:24 +0000 | [diff] [blame] | 152 | LLVM_DUMP_METHOD |
| 153 | void SCEV::dump() const { |
| 154 | print(dbgs()); |
| 155 | dbgs() << '\n'; |
| 156 | } |
| 157 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 158 | void SCEV::print(raw_ostream &OS) const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 159 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 160 | case scConstant: |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 161 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 162 | return; |
| 163 | case scTruncate: { |
| 164 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); |
| 165 | const SCEV *Op = Trunc->getOperand(); |
| 166 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " |
| 167 | << *Trunc->getType() << ")"; |
| 168 | return; |
| 169 | } |
| 170 | case scZeroExtend: { |
| 171 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); |
| 172 | const SCEV *Op = ZExt->getOperand(); |
| 173 | OS << "(zext " << *Op->getType() << " " << *Op << " to " |
| 174 | << *ZExt->getType() << ")"; |
| 175 | return; |
| 176 | } |
| 177 | case scSignExtend: { |
| 178 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); |
| 179 | const SCEV *Op = SExt->getOperand(); |
| 180 | OS << "(sext " << *Op->getType() << " " << *Op << " to " |
| 181 | << *SExt->getType() << ")"; |
| 182 | return; |
| 183 | } |
| 184 | case scAddRecExpr: { |
| 185 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); |
| 186 | OS << "{" << *AR->getOperand(0); |
| 187 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) |
| 188 | OS << ",+," << *AR->getOperand(i); |
| 189 | OS << "}<"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 190 | if (AR->hasNoUnsignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 191 | OS << "nuw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 192 | if (AR->hasNoSignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 193 | OS << "nsw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 194 | if (AR->hasNoSelfWrap() && |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 195 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) |
| 196 | OS << "nw><"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 197 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 198 | OS << ">"; |
| 199 | return; |
| 200 | } |
| 201 | case scAddExpr: |
| 202 | case scMulExpr: |
| 203 | case scUMaxExpr: |
| 204 | case scSMaxExpr: { |
| 205 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 206 | const char *OpStr = nullptr; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 207 | switch (NAry->getSCEVType()) { |
| 208 | case scAddExpr: OpStr = " + "; break; |
| 209 | case scMulExpr: OpStr = " * "; break; |
| 210 | case scUMaxExpr: OpStr = " umax "; break; |
| 211 | case scSMaxExpr: OpStr = " smax "; break; |
| 212 | } |
| 213 | OS << "("; |
| 214 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 215 | I != E; ++I) { |
| 216 | OS << **I; |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 217 | if (std::next(I) != E) |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 218 | OS << OpStr; |
| 219 | } |
| 220 | OS << ")"; |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 221 | switch (NAry->getSCEVType()) { |
| 222 | case scAddExpr: |
| 223 | case scMulExpr: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 224 | if (NAry->hasNoUnsignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 225 | OS << "<nuw>"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 226 | if (NAry->hasNoSignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 227 | OS << "<nsw>"; |
| 228 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 229 | return; |
| 230 | } |
| 231 | case scUDivExpr: { |
| 232 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); |
| 233 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; |
| 234 | return; |
| 235 | } |
| 236 | case scUnknown: { |
| 237 | const SCEVUnknown *U = cast<SCEVUnknown>(this); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 238 | Type *AllocTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 239 | if (U->isSizeOf(AllocTy)) { |
| 240 | OS << "sizeof(" << *AllocTy << ")"; |
| 241 | return; |
| 242 | } |
| 243 | if (U->isAlignOf(AllocTy)) { |
| 244 | OS << "alignof(" << *AllocTy << ")"; |
| 245 | return; |
| 246 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 247 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 248 | Type *CTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 249 | Constant *FieldNo; |
| 250 | if (U->isOffsetOf(CTy, FieldNo)) { |
| 251 | OS << "offsetof(" << *CTy << ", "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 252 | FieldNo->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 253 | OS << ")"; |
| 254 | return; |
| 255 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 256 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 257 | // Otherwise just print it normally. |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 258 | U->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 259 | return; |
| 260 | } |
| 261 | case scCouldNotCompute: |
| 262 | OS << "***COULDNOTCOMPUTE***"; |
| 263 | return; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 264 | } |
| 265 | llvm_unreachable("Unknown SCEV kind!"); |
| 266 | } |
| 267 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 268 | Type *SCEV::getType() const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 269 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 270 | case scConstant: |
| 271 | return cast<SCEVConstant>(this)->getType(); |
| 272 | case scTruncate: |
| 273 | case scZeroExtend: |
| 274 | case scSignExtend: |
| 275 | return cast<SCEVCastExpr>(this)->getType(); |
| 276 | case scAddRecExpr: |
| 277 | case scMulExpr: |
| 278 | case scUMaxExpr: |
| 279 | case scSMaxExpr: |
| 280 | return cast<SCEVNAryExpr>(this)->getType(); |
| 281 | case scAddExpr: |
| 282 | return cast<SCEVAddExpr>(this)->getType(); |
| 283 | case scUDivExpr: |
| 284 | return cast<SCEVUDivExpr>(this)->getType(); |
| 285 | case scUnknown: |
| 286 | return cast<SCEVUnknown>(this)->getType(); |
| 287 | case scCouldNotCompute: |
| 288 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 289 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 290 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 291 | } |
| 292 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 293 | bool SCEV::isZero() const { |
| 294 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 295 | return SC->getValue()->isZero(); |
| 296 | return false; |
| 297 | } |
| 298 | |
Dan Gohman | ba7f6d8 | 2009-05-18 15:22:39 +0000 | [diff] [blame] | 299 | bool SCEV::isOne() const { |
| 300 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 301 | return SC->getValue()->isOne(); |
| 302 | return false; |
| 303 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 304 | |
Dan Gohman | 18a96bb | 2009-06-24 00:30:26 +0000 | [diff] [blame] | 305 | bool SCEV::isAllOnesValue() const { |
| 306 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 307 | return SC->getValue()->isAllOnesValue(); |
| 308 | return false; |
| 309 | } |
| 310 | |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 311 | bool SCEV::isNonConstantNegative() const { |
| 312 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); |
| 313 | if (!Mul) return false; |
| 314 | |
| 315 | // If there is a constant factor, it will be first. |
| 316 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); |
| 317 | if (!SC) return false; |
| 318 | |
| 319 | // 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] | 320 | return SC->getAPInt().isNegative(); |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 321 | } |
| 322 | |
Owen Anderson | 04052ec | 2009-06-22 21:57:23 +0000 | [diff] [blame] | 323 | SCEVCouldNotCompute::SCEVCouldNotCompute() : |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 324 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 325 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 326 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 327 | return S->getSCEVType() == scCouldNotCompute; |
| 328 | } |
| 329 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 330 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 331 | FoldingSetNodeID ID; |
| 332 | ID.AddInteger(scConstant); |
| 333 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 334 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 335 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 336 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 337 | UniqueSCEVs.InsertNode(S, IP); |
| 338 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 339 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 340 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 341 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 342 | return getConstant(ConstantInt::get(getContext(), Val)); |
Dan Gohman | 0a76e7f | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 343 | } |
| 344 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 345 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 346 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { |
| 347 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); |
Dan Gohman | a029cbe | 2010-04-21 16:04:04 +0000 | [diff] [blame] | 348 | return getConstant(ConstantInt::get(ITy, V, isSigned)); |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 349 | } |
| 350 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 351 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 352 | unsigned SCEVTy, const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 353 | : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 354 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 355 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 356 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 357 | : SCEVCastExpr(ID, scTruncate, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 358 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 359 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 360 | "Cannot truncate non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 361 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 362 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 363 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 364 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 365 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 366 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 367 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 368 | "Cannot zero extend non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 369 | } |
| 370 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 371 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 372 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 373 | : SCEVCastExpr(ID, scSignExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 374 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 375 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 376 | "Cannot sign extend non-integer value!"); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 377 | } |
| 378 | |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 379 | void SCEVUnknown::deleted() { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 380 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 381 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 382 | |
| 383 | // Remove this SCEVUnknown from the uniquing map. |
| 384 | SE->UniqueSCEVs.RemoveNode(this); |
| 385 | |
| 386 | // Release the value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 387 | setValPtr(nullptr); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 388 | } |
| 389 | |
| 390 | void SCEVUnknown::allUsesReplacedWith(Value *New) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 391 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 392 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 393 | |
| 394 | // Remove this SCEVUnknown from the uniquing map. |
| 395 | SE->UniqueSCEVs.RemoveNode(this); |
| 396 | |
| 397 | // Update this SCEVUnknown to point to the new value. This is needed |
| 398 | // because there may still be outstanding SCEVs which still point to |
| 399 | // this SCEVUnknown. |
| 400 | setValPtr(New); |
| 401 | } |
| 402 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 403 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 404 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 405 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 406 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 407 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 408 | CE->getOperand(0)->isNullValue() && |
| 409 | CE->getNumOperands() == 2) |
| 410 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) |
| 411 | if (CI->isOne()) { |
| 412 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) |
| 413 | ->getElementType(); |
| 414 | return true; |
| 415 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 416 | |
| 417 | return false; |
| 418 | } |
| 419 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 420 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 421 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 422 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 423 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 424 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 425 | CE->getOperand(0)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 426 | Type *Ty = |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 427 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 428 | if (StructType *STy = dyn_cast<StructType>(Ty)) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 429 | if (!STy->isPacked() && |
| 430 | CE->getNumOperands() == 3 && |
| 431 | CE->getOperand(1)->isNullValue()) { |
| 432 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) |
| 433 | if (CI->isOne() && |
| 434 | STy->getNumElements() == 2 && |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 435 | STy->getElementType(0)->isIntegerTy(1)) { |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 436 | AllocTy = STy->getElementType(1); |
| 437 | return true; |
| 438 | } |
| 439 | } |
| 440 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 441 | |
| 442 | return false; |
| 443 | } |
| 444 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 445 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 446 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 447 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 448 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
| 449 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 450 | CE->getNumOperands() == 3 && |
| 451 | CE->getOperand(0)->isNullValue() && |
| 452 | CE->getOperand(1)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 453 | Type *Ty = |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 454 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
| 455 | // Ignore vector types here so that ScalarEvolutionExpander doesn't |
| 456 | // emit getelementptrs that index into vectors. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 457 | if (Ty->isStructTy() || Ty->isArrayTy()) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 458 | CTy = Ty; |
| 459 | FieldNo = CE->getOperand(2); |
| 460 | return true; |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | return false; |
| 465 | } |
| 466 | |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 467 | //===----------------------------------------------------------------------===// |
| 468 | // SCEV Utilities |
| 469 | //===----------------------------------------------------------------------===// |
| 470 | |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 471 | /// Compare the two values \p LV and \p RV in terms of their "complexity" where |
| 472 | /// "complexity" is a partial (and somewhat ad-hoc) relation used to order |
| 473 | /// operands in SCEV expressions. \p EqCache is a set of pairs of values that |
| 474 | /// have been previously deemed to be "equally complex" by this routine. It is |
| 475 | /// intended to avoid exponential time complexity in cases like: |
| 476 | /// |
| 477 | /// %a = f(%x, %y) |
| 478 | /// %b = f(%a, %a) |
| 479 | /// %c = f(%b, %b) |
| 480 | /// |
| 481 | /// %d = f(%x, %y) |
| 482 | /// %e = f(%d, %d) |
| 483 | /// %f = f(%e, %e) |
| 484 | /// |
| 485 | /// CompareValueComplexity(%f, %c) |
| 486 | /// |
| 487 | /// Since we do not continue running this routine on expression trees once we |
| 488 | /// have seen unequal values, there is no need to track them in the cache. |
| 489 | static int |
| 490 | CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, |
| 491 | const LoopInfo *const LI, Value *LV, Value *RV, |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 492 | unsigned Depth) { |
| 493 | if (Depth > MaxCompareDepth || EqCache.count({LV, RV})) |
Sanjoy Das | 507dd40 | 2016-10-18 17:45:16 +0000 | [diff] [blame] | 494 | return 0; |
| 495 | |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 496 | // Order pointer values after integer values. This helps SCEVExpander form |
| 497 | // GEPs. |
| 498 | bool LIsPointer = LV->getType()->isPointerTy(), |
| 499 | RIsPointer = RV->getType()->isPointerTy(); |
| 500 | if (LIsPointer != RIsPointer) |
| 501 | return (int)LIsPointer - (int)RIsPointer; |
| 502 | |
| 503 | // Compare getValueID values. |
| 504 | unsigned LID = LV->getValueID(), RID = RV->getValueID(); |
| 505 | if (LID != RID) |
| 506 | return (int)LID - (int)RID; |
| 507 | |
| 508 | // Sort arguments by their position. |
Sanjoy Das | b4830a8 | 2016-10-30 23:52:53 +0000 | [diff] [blame] | 509 | if (const auto *LA = dyn_cast<Argument>(LV)) { |
| 510 | const auto *RA = cast<Argument>(RV); |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 511 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); |
| 512 | return (int)LArgNo - (int)RArgNo; |
| 513 | } |
| 514 | |
Sanjoy Das | 299e672 | 2016-10-30 23:52:56 +0000 | [diff] [blame] | 515 | if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { |
| 516 | const auto *RGV = cast<GlobalValue>(RV); |
| 517 | |
| 518 | const auto IsGVNameSemantic = [&](const GlobalValue *GV) { |
| 519 | auto LT = GV->getLinkage(); |
| 520 | return !(GlobalValue::isPrivateLinkage(LT) || |
| 521 | GlobalValue::isInternalLinkage(LT)); |
| 522 | }; |
| 523 | |
| 524 | // Use the names to distinguish the two values, but only if the |
| 525 | // names are semantically important. |
| 526 | if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) |
| 527 | return LGV->getName().compare(RGV->getName()); |
| 528 | } |
| 529 | |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 530 | // For instructions, compare their loop depth, and their operand count. This |
| 531 | // is pretty loose. |
Sanjoy Das | b4830a8 | 2016-10-30 23:52:53 +0000 | [diff] [blame] | 532 | if (const auto *LInst = dyn_cast<Instruction>(LV)) { |
| 533 | const auto *RInst = cast<Instruction>(RV); |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 534 | |
| 535 | // Compare loop depths. |
| 536 | const BasicBlock *LParent = LInst->getParent(), |
| 537 | *RParent = RInst->getParent(); |
| 538 | if (LParent != RParent) { |
| 539 | unsigned LDepth = LI->getLoopDepth(LParent), |
| 540 | RDepth = LI->getLoopDepth(RParent); |
| 541 | if (LDepth != RDepth) |
| 542 | return (int)LDepth - (int)RDepth; |
| 543 | } |
| 544 | |
| 545 | // Compare the number of operands. |
| 546 | unsigned LNumOps = LInst->getNumOperands(), |
| 547 | RNumOps = RInst->getNumOperands(); |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 548 | if (LNumOps != RNumOps) |
Sanjoy Das | 507dd40 | 2016-10-18 17:45:16 +0000 | [diff] [blame] | 549 | return (int)LNumOps - (int)RNumOps; |
| 550 | |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 551 | for (unsigned Idx : seq(0u, LNumOps)) { |
| 552 | int Result = |
| 553 | CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 554 | RInst->getOperand(Idx), Depth + 1); |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 555 | if (Result != 0) |
Daniil Fukalov | e870398 | 2016-11-16 16:41:40 +0000 | [diff] [blame] | 556 | return Result; |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 557 | } |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 558 | } |
| 559 | |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 560 | EqCache.insert({LV, RV}); |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 561 | return 0; |
| 562 | } |
| 563 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 564 | // Return negative, zero, or positive, if LHS is less than, equal to, or greater |
| 565 | // than RHS, respectively. A three-way result allows recursive comparisons to be |
| 566 | // more efficient. |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 567 | static int CompareSCEVComplexity( |
| 568 | SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, |
| 569 | const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, |
| 570 | unsigned Depth = 0) { |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 571 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. |
| 572 | if (LHS == RHS) |
| 573 | return 0; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 574 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 575 | // Primarily, sort the SCEVs by their getSCEVType(). |
| 576 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); |
| 577 | if (LType != RType) |
| 578 | return (int)LType - (int)RType; |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 579 | |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 580 | if (Depth > MaxCompareDepth || EqCacheSCEV.count({LHS, RHS})) |
| 581 | return 0; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 582 | // Aside from the getSCEVType() ordering, the particular ordering |
| 583 | // isn't very important except that it's beneficial to be consistent, |
| 584 | // so that (a + b) and (b + a) don't end up as different expressions. |
| 585 | switch (static_cast<SCEVTypes>(LType)) { |
| 586 | case scUnknown: { |
| 587 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); |
| 588 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 589 | |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 590 | SmallSet<std::pair<Value *, Value *>, 8> EqCache; |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 591 | int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(), |
| 592 | Depth + 1); |
| 593 | if (X == 0) |
| 594 | EqCacheSCEV.insert({LHS, RHS}); |
| 595 | return X; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 596 | } |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 597 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 598 | case scConstant: { |
| 599 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); |
| 600 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); |
| 601 | |
| 602 | // Compare constant values. |
| 603 | const APInt &LA = LC->getAPInt(); |
| 604 | const APInt &RA = RC->getAPInt(); |
| 605 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); |
| 606 | if (LBitWidth != RBitWidth) |
| 607 | return (int)LBitWidth - (int)RBitWidth; |
| 608 | return LA.ult(RA) ? -1 : 1; |
| 609 | } |
| 610 | |
| 611 | case scAddRecExpr: { |
| 612 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); |
| 613 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); |
| 614 | |
| 615 | // Compare addrec loop depths. |
| 616 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); |
| 617 | if (LLoop != RLoop) { |
| 618 | unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); |
| 619 | if (LDepth != RDepth) |
| 620 | return (int)LDepth - (int)RDepth; |
| 621 | } |
| 622 | |
| 623 | // Addrec complexity grows with operand count. |
| 624 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); |
| 625 | if (LNumOps != RNumOps) |
| 626 | return (int)LNumOps - (int)RNumOps; |
| 627 | |
| 628 | // Lexicographically compare. |
| 629 | for (unsigned i = 0; i != LNumOps; ++i) { |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 630 | int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), |
| 631 | RA->getOperand(i), Depth + 1); |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 632 | if (X != 0) |
| 633 | return X; |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 634 | } |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 635 | EqCacheSCEV.insert({LHS, RHS}); |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 636 | return 0; |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 637 | } |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 638 | |
| 639 | case scAddExpr: |
| 640 | case scMulExpr: |
| 641 | case scSMaxExpr: |
| 642 | case scUMaxExpr: { |
| 643 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); |
| 644 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); |
| 645 | |
| 646 | // Lexicographically compare n-ary expressions. |
| 647 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); |
| 648 | if (LNumOps != RNumOps) |
| 649 | return (int)LNumOps - (int)RNumOps; |
| 650 | |
| 651 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 652 | if (i >= RNumOps) |
| 653 | return 1; |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 654 | int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), |
| 655 | RC->getOperand(i), Depth + 1); |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 656 | if (X != 0) |
| 657 | return X; |
| 658 | } |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 659 | EqCacheSCEV.insert({LHS, RHS}); |
| 660 | return 0; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 661 | } |
| 662 | |
| 663 | case scUDivExpr: { |
| 664 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); |
| 665 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); |
| 666 | |
| 667 | // Lexicographically compare udiv expressions. |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 668 | int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), |
| 669 | Depth + 1); |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 670 | if (X != 0) |
| 671 | return X; |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 672 | X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), |
| 673 | Depth + 1); |
| 674 | if (X == 0) |
| 675 | EqCacheSCEV.insert({LHS, RHS}); |
| 676 | return X; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 677 | } |
| 678 | |
| 679 | case scTruncate: |
| 680 | case scZeroExtend: |
| 681 | case scSignExtend: { |
| 682 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); |
| 683 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); |
| 684 | |
| 685 | // Compare cast expressions by operand. |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 686 | int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), |
| 687 | RC->getOperand(), Depth + 1); |
| 688 | if (X == 0) |
| 689 | EqCacheSCEV.insert({LHS, RHS}); |
| 690 | return X; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 691 | } |
| 692 | |
| 693 | case scCouldNotCompute: |
| 694 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
| 695 | } |
| 696 | llvm_unreachable("Unknown SCEV kind!"); |
| 697 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 698 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 699 | /// Given a list of SCEV objects, order them by their complexity, and group |
| 700 | /// objects of the same complexity together by value. When this routine is |
| 701 | /// finished, we know that any duplicates in the vector are consecutive and that |
| 702 | /// complexity is monotonically increasing. |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 703 | /// |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 704 | /// 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] | 705 | /// results from this routine. In other words, we don't want the results of |
| 706 | /// this to depend on where the addresses of various SCEV objects happened to |
| 707 | /// land in memory. |
| 708 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 709 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 710 | LoopInfo *LI) { |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 711 | if (Ops.size() < 2) return; // Noop |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 712 | |
| 713 | SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 714 | if (Ops.size() == 2) { |
| 715 | // This is the common case, which also happens to be trivially simple. |
| 716 | // Special case it. |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 717 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 718 | if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0) |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 719 | std::swap(LHS, RHS); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 720 | return; |
| 721 | } |
| 722 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 723 | // Do the rough sort by complexity. |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 724 | std::stable_sort(Ops.begin(), Ops.end(), |
Daniil Fukalov | 4c3322c | 2016-11-17 16:07:52 +0000 | [diff] [blame] | 725 | [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) { |
| 726 | return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 727 | }); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 728 | |
| 729 | // Now that we are sorted by complexity, group elements of the same |
| 730 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 731 | // be extremely short in practice. Note that we take this approach because we |
| 732 | // do not want to depend on the addresses of the objects we are grouping. |
| 733 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
| 734 | const SCEV *S = Ops[i]; |
| 735 | unsigned Complexity = S->getSCEVType(); |
| 736 | |
| 737 | // If there are any objects of the same complexity and same value as this |
| 738 | // one, group them. |
| 739 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 740 | if (Ops[j] == S) { // Found a duplicate. |
| 741 | // Move it to immediately after i'th element. |
| 742 | std::swap(Ops[i+1], Ops[j]); |
| 743 | ++i; // no need to rescan it. |
| 744 | if (i == e-2) return; // Done! |
| 745 | } |
| 746 | } |
| 747 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 748 | } |
| 749 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 750 | // Returns the size of the SCEV S. |
| 751 | static inline int sizeOfSCEV(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 752 | struct FindSCEVSize { |
| 753 | int Size; |
| 754 | FindSCEVSize() : Size(0) {} |
| 755 | |
| 756 | bool follow(const SCEV *S) { |
| 757 | ++Size; |
| 758 | // Keep looking at all operands of S. |
| 759 | return true; |
| 760 | } |
| 761 | bool isDone() const { |
| 762 | return false; |
| 763 | } |
| 764 | }; |
| 765 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 766 | FindSCEVSize F; |
| 767 | SCEVTraversal<FindSCEVSize> ST(F); |
| 768 | ST.visitAll(S); |
| 769 | return F.Size; |
| 770 | } |
| 771 | |
| 772 | namespace { |
| 773 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 774 | struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 775 | public: |
| 776 | // Computes the Quotient and Remainder of the division of Numerator by |
| 777 | // Denominator. |
| 778 | static void divide(ScalarEvolution &SE, const SCEV *Numerator, |
| 779 | const SCEV *Denominator, const SCEV **Quotient, |
| 780 | const SCEV **Remainder) { |
| 781 | assert(Numerator && Denominator && "Uninitialized SCEV"); |
| 782 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 783 | SCEVDivision D(SE, Numerator, Denominator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 784 | |
| 785 | // Check for the trivial case here to avoid having to check for it in the |
| 786 | // rest of the code. |
| 787 | if (Numerator == Denominator) { |
| 788 | *Quotient = D.One; |
| 789 | *Remainder = D.Zero; |
| 790 | return; |
| 791 | } |
| 792 | |
| 793 | if (Numerator->isZero()) { |
| 794 | *Quotient = D.Zero; |
| 795 | *Remainder = D.Zero; |
| 796 | return; |
| 797 | } |
| 798 | |
Brendon Cahoon | a57cc8b | 2015-04-20 16:03:28 +0000 | [diff] [blame] | 799 | // A simple case when N/1. The quotient is N. |
| 800 | if (Denominator->isOne()) { |
| 801 | *Quotient = Numerator; |
| 802 | *Remainder = D.Zero; |
| 803 | return; |
| 804 | } |
| 805 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 806 | // Split the Denominator when it is a product. |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 807 | if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 808 | const SCEV *Q, *R; |
| 809 | *Quotient = Numerator; |
| 810 | for (const SCEV *Op : T->operands()) { |
| 811 | divide(SE, *Quotient, Op, &Q, &R); |
| 812 | *Quotient = Q; |
| 813 | |
| 814 | // Bail out when the Numerator is not divisible by one of the terms of |
| 815 | // the Denominator. |
| 816 | if (!R->isZero()) { |
| 817 | *Quotient = D.Zero; |
| 818 | *Remainder = Numerator; |
| 819 | return; |
| 820 | } |
| 821 | } |
| 822 | *Remainder = D.Zero; |
| 823 | return; |
| 824 | } |
| 825 | |
| 826 | D.visit(Numerator); |
| 827 | *Quotient = D.Quotient; |
| 828 | *Remainder = D.Remainder; |
| 829 | } |
| 830 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 831 | // Except in the trivial case described above, we do not know how to divide |
| 832 | // Expr by Denominator for the following functions with empty implementation. |
| 833 | void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} |
| 834 | void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} |
| 835 | void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} |
| 836 | void visitUDivExpr(const SCEVUDivExpr *Numerator) {} |
| 837 | void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} |
| 838 | void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} |
| 839 | void visitUnknown(const SCEVUnknown *Numerator) {} |
| 840 | void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} |
| 841 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 842 | void visitConstant(const SCEVConstant *Numerator) { |
| 843 | if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 844 | APInt NumeratorVal = Numerator->getAPInt(); |
| 845 | APInt DenominatorVal = D->getAPInt(); |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 846 | uint32_t NumeratorBW = NumeratorVal.getBitWidth(); |
| 847 | uint32_t DenominatorBW = DenominatorVal.getBitWidth(); |
| 848 | |
| 849 | if (NumeratorBW > DenominatorBW) |
| 850 | DenominatorVal = DenominatorVal.sext(NumeratorBW); |
| 851 | else if (NumeratorBW < DenominatorBW) |
| 852 | NumeratorVal = NumeratorVal.sext(DenominatorBW); |
| 853 | |
| 854 | APInt QuotientVal(NumeratorVal.getBitWidth(), 0); |
| 855 | APInt RemainderVal(NumeratorVal.getBitWidth(), 0); |
| 856 | APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); |
| 857 | Quotient = SE.getConstant(QuotientVal); |
| 858 | Remainder = SE.getConstant(RemainderVal); |
| 859 | return; |
| 860 | } |
| 861 | } |
| 862 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 863 | void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { |
| 864 | const SCEV *StartQ, *StartR, *StepQ, *StepR; |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 865 | if (!Numerator->isAffine()) |
| 866 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 867 | divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); |
| 868 | divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); |
Brendon Cahoon | f9751ad | 2015-04-22 15:06:40 +0000 | [diff] [blame] | 869 | // Bail out if the types do not match. |
| 870 | Type *Ty = Denominator->getType(); |
| 871 | if (Ty != StartQ->getType() || Ty != StartR->getType() || |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 872 | Ty != StepQ->getType() || Ty != StepR->getType()) |
| 873 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 874 | Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), |
| 875 | Numerator->getNoWrapFlags()); |
| 876 | Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), |
| 877 | Numerator->getNoWrapFlags()); |
| 878 | } |
| 879 | |
| 880 | void visitAddExpr(const SCEVAddExpr *Numerator) { |
| 881 | SmallVector<const SCEV *, 2> Qs, Rs; |
| 882 | Type *Ty = Denominator->getType(); |
| 883 | |
| 884 | for (const SCEV *Op : Numerator->operands()) { |
| 885 | const SCEV *Q, *R; |
| 886 | divide(SE, Op, Denominator, &Q, &R); |
| 887 | |
| 888 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 889 | if (Ty != Q->getType() || Ty != R->getType()) |
| 890 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 891 | |
| 892 | Qs.push_back(Q); |
| 893 | Rs.push_back(R); |
| 894 | } |
| 895 | |
| 896 | if (Qs.size() == 1) { |
| 897 | Quotient = Qs[0]; |
| 898 | Remainder = Rs[0]; |
| 899 | return; |
| 900 | } |
| 901 | |
| 902 | Quotient = SE.getAddExpr(Qs); |
| 903 | Remainder = SE.getAddExpr(Rs); |
| 904 | } |
| 905 | |
| 906 | void visitMulExpr(const SCEVMulExpr *Numerator) { |
| 907 | SmallVector<const SCEV *, 2> Qs; |
| 908 | Type *Ty = Denominator->getType(); |
| 909 | |
| 910 | bool FoundDenominatorTerm = false; |
| 911 | for (const SCEV *Op : Numerator->operands()) { |
| 912 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 913 | if (Ty != Op->getType()) |
| 914 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 915 | |
| 916 | if (FoundDenominatorTerm) { |
| 917 | Qs.push_back(Op); |
| 918 | continue; |
| 919 | } |
| 920 | |
| 921 | // Check whether Denominator divides one of the product operands. |
| 922 | const SCEV *Q, *R; |
| 923 | divide(SE, Op, Denominator, &Q, &R); |
| 924 | if (!R->isZero()) { |
| 925 | Qs.push_back(Op); |
| 926 | continue; |
| 927 | } |
| 928 | |
| 929 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 930 | if (Ty != Q->getType()) |
| 931 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 932 | |
| 933 | FoundDenominatorTerm = true; |
| 934 | Qs.push_back(Q); |
| 935 | } |
| 936 | |
| 937 | if (FoundDenominatorTerm) { |
| 938 | Remainder = Zero; |
| 939 | if (Qs.size() == 1) |
| 940 | Quotient = Qs[0]; |
| 941 | else |
| 942 | Quotient = SE.getMulExpr(Qs); |
| 943 | return; |
| 944 | } |
| 945 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 946 | if (!isa<SCEVUnknown>(Denominator)) |
| 947 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 948 | |
| 949 | // The Remainder is obtained by replacing Denominator by 0 in Numerator. |
| 950 | ValueToValueMap RewriteMap; |
| 951 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 952 | cast<SCEVConstant>(Zero)->getValue(); |
| 953 | Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 954 | |
| 955 | if (Remainder->isZero()) { |
| 956 | // The Quotient is obtained by replacing Denominator by 1 in Numerator. |
| 957 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 958 | cast<SCEVConstant>(One)->getValue(); |
| 959 | Quotient = |
| 960 | SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 961 | return; |
| 962 | } |
| 963 | |
| 964 | // Quotient is (Numerator - Remainder) divided by Denominator. |
| 965 | const SCEV *Q, *R; |
| 966 | const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 967 | // This SCEV does not seem to simplify: fail the division here. |
| 968 | if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) |
| 969 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 970 | divide(SE, Diff, Denominator, &Q, &R); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 971 | if (R != Zero) |
| 972 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 973 | Quotient = Q; |
| 974 | } |
| 975 | |
| 976 | private: |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 977 | SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, |
| 978 | const SCEV *Denominator) |
| 979 | : SE(S), Denominator(Denominator) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 980 | Zero = SE.getZero(Denominator->getType()); |
| 981 | One = SE.getOne(Denominator->getType()); |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 982 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 983 | // We generally do not know how to divide Expr by Denominator. We |
| 984 | // initialize the division to a "cannot divide" state to simplify the rest |
| 985 | // of the code. |
| 986 | cannotDivide(Numerator); |
| 987 | } |
| 988 | |
| 989 | // Convenience function for giving up on the division. We set the quotient to |
| 990 | // be equal to zero and the remainder to be equal to the numerator. |
| 991 | void cannotDivide(const SCEV *Numerator) { |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 992 | Quotient = Zero; |
| 993 | Remainder = Numerator; |
| 994 | } |
| 995 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 996 | ScalarEvolution &SE; |
| 997 | const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; |
David Majnemer | 32b8ccf | 2014-11-16 20:35:19 +0000 | [diff] [blame] | 998 | }; |
| 999 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1000 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 1001 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1002 | //===----------------------------------------------------------------------===// |
| 1003 | // Simple SCEV method implementations |
| 1004 | //===----------------------------------------------------------------------===// |
| 1005 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1006 | /// Compute BC(It, K). The result has width W. Assume, K > 0. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1007 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1008 | ScalarEvolution &SE, |
Nick Lewycky | 702cf1e | 2011-09-06 06:39:54 +0000 | [diff] [blame] | 1009 | Type *ResultTy) { |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1010 | // Handle the simplest case efficiently. |
| 1011 | if (K == 1) |
| 1012 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 1013 | |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1014 | // We are using the following formula for BC(It, K): |
| 1015 | // |
| 1016 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 1017 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1018 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 1019 | // overflow. Hence, we must assure that the result of our computation is |
| 1020 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 1021 | // safe in modular arithmetic. |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1022 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1023 | // 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] | 1024 | // 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] | 1025 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 1026 | // exponentiation: |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1027 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1028 | // 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] | 1029 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1030 | // This formula is trivially equivalent to the previous formula. However, |
| 1031 | // this formula can be implemented much more efficiently. The trick is that |
| 1032 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 1033 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 1034 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 1035 | // width W. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 1036 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1037 | // The next issue is how to safely do the division by 2^T. The way this |
| 1038 | // is done is by doing the multiplication step at a width of at least W + T |
| 1039 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 1040 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 1041 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 1042 | // truncated out after the division by 2^T. |
| 1043 | // |
| 1044 | // In comparison to just directly using the first formula, this technique |
| 1045 | // is much more efficient; using the first formula requires W * K bits, |
| 1046 | // but this formula less than W + K bits. Also, the first formula requires |
| 1047 | // a division step, whereas this formula only requires multiplies and shifts. |
| 1048 | // |
| 1049 | // It doesn't matter whether the subtraction step is done in the calculation |
| 1050 | // width or the input iteration count's width; if the subtraction overflows, |
| 1051 | // the result must be zero anyway. We prefer here to do it in the width of |
| 1052 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 1053 | // isn't smart enough to ignore the overflow, which leads to much less |
| 1054 | // efficient code if the width of the subtraction is wider than the native |
| 1055 | // register width. |
| 1056 | // |
| 1057 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 1058 | // the multiplication; for example, K=2 can be calculated as |
| 1059 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 1060 | // extra arithmetic, so it's not an obvious win, and it gets |
| 1061 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1062 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1063 | // Protection from insane SCEVs; this bound is conservative, |
| 1064 | // but it probably doesn't matter. |
| 1065 | if (K > 1000) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 1066 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1067 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1068 | unsigned W = SE.getTypeSizeInBits(ResultTy); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1069 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1070 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 1071 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 1072 | // Other overflow doesn't matter because we only care about the bottom |
| 1073 | // W bits of the result. |
| 1074 | APInt OddFactorial(W, 1); |
| 1075 | unsigned T = 1; |
| 1076 | for (unsigned i = 3; i <= K; ++i) { |
| 1077 | APInt Mult(W, i); |
| 1078 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 1079 | T += TwoFactors; |
| 1080 | Mult = Mult.lshr(TwoFactors); |
| 1081 | OddFactorial *= Mult; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1082 | } |
Nick Lewycky | ed169d5 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 1083 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1084 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 21add8f | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 1085 | unsigned CalculationBits = W + T; |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1086 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1087 | // Calculate 2^T, at width T+W. |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 1088 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1089 | |
| 1090 | // Calculate the multiplicative inverse of K! / 2^T; |
| 1091 | // this multiplication factor will perform the exact division by |
| 1092 | // K! / 2^T. |
| 1093 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 1094 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 1095 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 1096 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 1097 | |
| 1098 | // Calculate the product, at width T+W |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1099 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1100 | CalculationBits); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1101 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1102 | for (unsigned i = 1; i != K; ++i) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1103 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1104 | Dividend = SE.getMulExpr(Dividend, |
| 1105 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 1106 | } |
| 1107 | |
| 1108 | // Divide by 2^T |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1109 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1110 | |
| 1111 | // Truncate the result, and divide by K! / 2^T. |
| 1112 | |
| 1113 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 1114 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1115 | } |
| 1116 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1117 | /// Return the value of this chain of recurrences at the specified iteration |
| 1118 | /// number. We can evaluate this recurrence by multiplying each element in the |
| 1119 | /// chain by the binomial coefficient corresponding to it. In other words, we |
| 1120 | /// can evaluate {A,+,B,+,C,+,D} as: |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1121 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1122 | /// 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] | 1123 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1124 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1125 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1126 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1127 | ScalarEvolution &SE) const { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1128 | const SCEV *Result = getStart(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1129 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1130 | // The computation is correct in the face of overflow provided that the |
| 1131 | // multiplication is performed _after_ the evaluation of the binomial |
| 1132 | // coefficient. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1133 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); |
Nick Lewycky | 707663e | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 1134 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 1135 | return Coeff; |
| 1136 | |
| 1137 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1138 | } |
| 1139 | return Result; |
| 1140 | } |
| 1141 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1142 | //===----------------------------------------------------------------------===// |
| 1143 | // SCEV Expression folder implementations |
| 1144 | //===----------------------------------------------------------------------===// |
| 1145 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1146 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1147 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1148 | assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1149 | "This is not a truncating conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1150 | assert(isSCEVable(Ty) && |
| 1151 | "This is not a conversion to a SCEVable type!"); |
| 1152 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1153 | |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1154 | FoldingSetNodeID ID; |
| 1155 | ID.AddInteger(scTruncate); |
| 1156 | ID.AddPointer(Op); |
| 1157 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1158 | void *IP = nullptr; |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1159 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1160 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1161 | // Fold if the operand is constant. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1162 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 8d7576e | 2009-06-24 00:38:39 +0000 | [diff] [blame] | 1163 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1164 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1165 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1166 | // trunc(trunc(x)) --> trunc(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1167 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1168 | return getTruncateExpr(ST->getOperand(), Ty); |
| 1169 | |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1170 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1171 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1172 | return getTruncateOrSignExtend(SS->getOperand(), Ty); |
| 1173 | |
| 1174 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1175 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1176 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty); |
| 1177 | |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1178 | // 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] | 1179 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1180 | if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1181 | SmallVector<const SCEV *, 4> Operands; |
| 1182 | bool hasTrunc = false; |
| 1183 | for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1184 | const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1185 | if (!isa<SCEVCastExpr>(SA->getOperand(i))) |
| 1186 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1187 | Operands.push_back(S); |
| 1188 | } |
| 1189 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1190 | return getAddExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1191 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1192 | } |
| 1193 | |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1194 | // 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] | 1195 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1196 | if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { |
| 1197 | SmallVector<const SCEV *, 4> Operands; |
| 1198 | bool hasTrunc = false; |
| 1199 | for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1200 | const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1201 | if (!isa<SCEVCastExpr>(SM->getOperand(i))) |
| 1202 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1203 | Operands.push_back(S); |
| 1204 | } |
| 1205 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1206 | return getMulExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1207 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1208 | } |
| 1209 | |
Dan Gohman | 5a728c9 | 2009-06-18 16:24:47 +0000 | [diff] [blame] | 1210 | // 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] | 1211 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1212 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 1213 | for (const SCEV *Op : AddRec->operands()) |
| 1214 | Operands.push_back(getTruncateExpr(Op, Ty)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1215 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1216 | } |
| 1217 | |
Dan Gohman | 89dd42a | 2010-06-25 18:47:08 +0000 | [diff] [blame] | 1218 | // The cast wasn't folded; create an explicit cast node. We can reuse |
| 1219 | // the existing insert position since if we get here, we won't have |
| 1220 | // made any changes which would invalidate it. |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1221 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), |
| 1222 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1223 | UniqueSCEVs.InsertNode(S, IP); |
| 1224 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1225 | } |
| 1226 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1227 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1228 | // signed overflow as long as the value of the recurrence within the |
| 1229 | // loop does not exceed this limit before incrementing. |
| 1230 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, |
| 1231 | ICmpInst::Predicate *Pred, |
| 1232 | ScalarEvolution *SE) { |
| 1233 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1234 | if (SE->isKnownPositive(Step)) { |
| 1235 | *Pred = ICmpInst::ICMP_SLT; |
| 1236 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - |
| 1237 | SE->getSignedRange(Step).getSignedMax()); |
| 1238 | } |
| 1239 | if (SE->isKnownNegative(Step)) { |
| 1240 | *Pred = ICmpInst::ICMP_SGT; |
| 1241 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - |
| 1242 | SE->getSignedRange(Step).getSignedMin()); |
| 1243 | } |
| 1244 | return nullptr; |
| 1245 | } |
| 1246 | |
| 1247 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1248 | // unsigned overflow as long as the value of the recurrence within the loop does |
| 1249 | // not exceed this limit before incrementing. |
| 1250 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, |
| 1251 | ICmpInst::Predicate *Pred, |
| 1252 | ScalarEvolution *SE) { |
| 1253 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1254 | *Pred = ICmpInst::ICMP_ULT; |
| 1255 | |
| 1256 | return SE->getConstant(APInt::getMinValue(BitWidth) - |
| 1257 | SE->getUnsignedRange(Step).getUnsignedMax()); |
| 1258 | } |
| 1259 | |
| 1260 | namespace { |
| 1261 | |
| 1262 | struct ExtendOpTraitsBase { |
| 1263 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); |
| 1264 | }; |
| 1265 | |
| 1266 | // Used to make code generic over signed and unsigned overflow. |
| 1267 | template <typename ExtendOp> struct ExtendOpTraits { |
| 1268 | // Members present: |
| 1269 | // |
| 1270 | // static const SCEV::NoWrapFlags WrapType; |
| 1271 | // |
| 1272 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; |
| 1273 | // |
| 1274 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1275 | // ICmpInst::Predicate *Pred, |
| 1276 | // ScalarEvolution *SE); |
| 1277 | }; |
| 1278 | |
| 1279 | template <> |
| 1280 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { |
| 1281 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; |
| 1282 | |
| 1283 | static const GetExtendExprTy GetExtendExpr; |
| 1284 | |
| 1285 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1286 | ICmpInst::Predicate *Pred, |
| 1287 | ScalarEvolution *SE) { |
| 1288 | return getSignedOverflowLimitForStep(Step, Pred, SE); |
| 1289 | } |
| 1290 | }; |
| 1291 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1292 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1293 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; |
| 1294 | |
| 1295 | template <> |
| 1296 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { |
| 1297 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; |
| 1298 | |
| 1299 | static const GetExtendExprTy GetExtendExpr; |
| 1300 | |
| 1301 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1302 | ICmpInst::Predicate *Pred, |
| 1303 | ScalarEvolution *SE) { |
| 1304 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); |
| 1305 | } |
| 1306 | }; |
| 1307 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1308 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1309 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1310 | } |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1311 | |
| 1312 | // The recurrence AR has been shown to have no signed/unsigned wrap or something |
| 1313 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as |
| 1314 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This |
| 1315 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + |
| 1316 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the |
| 1317 | // expression "Step + sext/zext(PreIncAR)" is congruent with |
| 1318 | // "sext/zext(PostIncAR)" |
| 1319 | template <typename ExtendOpTy> |
| 1320 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, |
| 1321 | ScalarEvolution *SE) { |
| 1322 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1323 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1324 | |
| 1325 | const Loop *L = AR->getLoop(); |
| 1326 | const SCEV *Start = AR->getStart(); |
| 1327 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 1328 | |
| 1329 | // Check for a simple looking step prior to loop entry. |
| 1330 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); |
| 1331 | if (!SA) |
| 1332 | return nullptr; |
| 1333 | |
| 1334 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV |
| 1335 | // subtraction is expensive. For this purpose, perform a quick and dirty |
| 1336 | // difference, by checking for Step in the operand list. |
| 1337 | SmallVector<const SCEV *, 4> DiffOps; |
| 1338 | for (const SCEV *Op : SA->operands()) |
| 1339 | if (Op != Step) |
| 1340 | DiffOps.push_back(Op); |
| 1341 | |
| 1342 | if (DiffOps.size() == SA->getNumOperands()) |
| 1343 | return nullptr; |
| 1344 | |
| 1345 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + |
| 1346 | // `Step`: |
| 1347 | |
| 1348 | // 1. NSW/NUW flags on the step increment. |
Sanjoy Das | 0714e3e | 2015-10-23 06:33:47 +0000 | [diff] [blame] | 1349 | auto PreStartFlags = |
| 1350 | ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); |
| 1351 | const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1352 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( |
| 1353 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); |
| 1354 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1355 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies |
| 1356 | // "S+X does not sign/unsign-overflow". |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1357 | // |
| 1358 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1359 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 1360 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && |
| 1361 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1362 | return PreStart; |
| 1363 | |
| 1364 | // 2. Direct overflow check on the step operation's expression. |
| 1365 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1366 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); |
| 1367 | const SCEV *OperandExtendedStart = |
| 1368 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), |
| 1369 | (SE->*GetExtendExpr)(Step, WideTy)); |
| 1370 | if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { |
| 1371 | if (PreAR && AR->getNoWrapFlags(WrapType)) { |
| 1372 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW |
| 1373 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then |
| 1374 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. |
| 1375 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); |
| 1376 | } |
| 1377 | return PreStart; |
| 1378 | } |
| 1379 | |
| 1380 | // 3. Loop precondition. |
| 1381 | ICmpInst::Predicate Pred; |
| 1382 | const SCEV *OverflowLimit = |
| 1383 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); |
| 1384 | |
| 1385 | if (OverflowLimit && |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1386 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1387 | return PreStart; |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1388 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1389 | return nullptr; |
| 1390 | } |
| 1391 | |
| 1392 | // Get the normalized zero or sign extended expression for this AddRec's Start. |
| 1393 | template <typename ExtendOpTy> |
| 1394 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, |
| 1395 | ScalarEvolution *SE) { |
| 1396 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1397 | |
| 1398 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); |
| 1399 | if (!PreStart) |
| 1400 | return (SE->*GetExtendExpr)(AR->getStart(), Ty); |
| 1401 | |
| 1402 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), |
| 1403 | (SE->*GetExtendExpr)(PreStart, Ty)); |
| 1404 | } |
| 1405 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1406 | // Try to prove away overflow by looking at "nearby" add recurrences. A |
| 1407 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it |
| 1408 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. |
| 1409 | // |
| 1410 | // Formally: |
| 1411 | // |
| 1412 | // {S,+,X} == {S-T,+,X} + T |
| 1413 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) |
| 1414 | // |
| 1415 | // If ({S-T,+,X} + T) does not overflow ... (1) |
| 1416 | // |
| 1417 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) |
| 1418 | // |
| 1419 | // If {S-T,+,X} does not overflow ... (2) |
| 1420 | // |
| 1421 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) |
| 1422 | // == {Ext(S-T)+Ext(T),+,Ext(X)} |
| 1423 | // |
| 1424 | // If (S-T)+T does not overflow ... (3) |
| 1425 | // |
| 1426 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} |
| 1427 | // == {Ext(S),+,Ext(X)} == LHS |
| 1428 | // |
| 1429 | // Thus, if (1), (2) and (3) are true for some T, then |
| 1430 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} |
| 1431 | // |
| 1432 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) |
| 1433 | // does not overflow" restricted to the 0th iteration. Therefore we only need |
| 1434 | // to check for (1) and (2). |
| 1435 | // |
| 1436 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T |
| 1437 | // is `Delta` (defined below). |
| 1438 | // |
| 1439 | template <typename ExtendOpTy> |
| 1440 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, |
| 1441 | const SCEV *Step, |
| 1442 | const Loop *L) { |
| 1443 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1444 | |
| 1445 | // We restrict `Start` to a constant to prevent SCEV from spending too much |
| 1446 | // time here. It is correct (but more expensive) to continue with a |
| 1447 | // non-constant `Start` and do a general SCEV subtraction to compute |
| 1448 | // `PreStart` below. |
| 1449 | // |
| 1450 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); |
| 1451 | if (!StartC) |
| 1452 | return false; |
| 1453 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1454 | APInt StartAI = StartC->getAPInt(); |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1455 | |
| 1456 | for (unsigned Delta : {-2, -1, 1, 2}) { |
| 1457 | const SCEV *PreStart = getConstant(StartAI - Delta); |
| 1458 | |
Sanjoy Das | 4280110 | 2015-10-23 06:57:21 +0000 | [diff] [blame] | 1459 | FoldingSetNodeID ID; |
| 1460 | ID.AddInteger(scAddRecExpr); |
| 1461 | ID.AddPointer(PreStart); |
| 1462 | ID.AddPointer(Step); |
| 1463 | ID.AddPointer(L); |
| 1464 | void *IP = nullptr; |
| 1465 | const auto *PreAR = |
| 1466 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 1467 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1468 | // Give up if we don't already have the add recurrence we need because |
| 1469 | // actually constructing an add recurrence is relatively expensive. |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1470 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) |
| 1471 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); |
| 1472 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 1473 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( |
| 1474 | DeltaS, &Pred, this); |
| 1475 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) |
| 1476 | return true; |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | return false; |
| 1481 | } |
| 1482 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1483 | const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1484 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1485 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1486 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1487 | assert(isSCEVable(Ty) && |
| 1488 | "This is not a conversion to a SCEVable type!"); |
| 1489 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1490 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1491 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1492 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1493 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1494 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1495 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1496 | // zext(zext(x)) --> zext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1497 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1498 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1499 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1500 | // Before doing any expensive analysis, check to see if we've already |
| 1501 | // computed a SCEV for this Op and Ty. |
| 1502 | FoldingSetNodeID ID; |
| 1503 | ID.AddInteger(scZeroExtend); |
| 1504 | ID.AddPointer(Op); |
| 1505 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1506 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1507 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1508 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1509 | // zext(trunc(x)) --> zext(x) or x or trunc(x) |
| 1510 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1511 | // It's possible the bits taken off by the truncate were all zero bits. If |
| 1512 | // so, we should be able to simplify this further. |
| 1513 | const SCEV *X = ST->getOperand(); |
| 1514 | ConstantRange CR = getUnsignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1515 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1516 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1517 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1518 | CR.zextOrTrunc(NewBits))) |
| 1519 | return getTruncateOrZeroExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1520 | } |
| 1521 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1522 | // 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] | 1523 | // 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] | 1524 | // operands (often constants). This allows analysis of something like |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1525 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1526 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1527 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1528 | const SCEV *Start = AR->getStart(); |
| 1529 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1530 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1531 | const Loop *L = AR->getLoop(); |
| 1532 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1533 | if (!AR->hasNoUnsignedWrap()) { |
| 1534 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1535 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1536 | } |
| 1537 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1538 | // If we have special knowledge that this addrec won't overflow, |
| 1539 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1540 | if (AR->hasNoUnsignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1541 | return getAddRecExpr( |
| 1542 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1543 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1544 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1545 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1546 | // Note that this serves two purposes: It filters out loops that are |
| 1547 | // simply not analyzable, and it covers the case where this code is |
| 1548 | // being called from within backedge-taken count analysis, such that |
| 1549 | // attempting to ask for the backedge-taken count would likely result |
| 1550 | // in infinite recursion. In the later case, the analysis code will |
| 1551 | // cope with a conservative value, and it will take care to purge |
| 1552 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1553 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1554 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1555 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1556 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1557 | |
| 1558 | // Check whether the backedge-taken count can be losslessly casted to |
| 1559 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1560 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1561 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1562 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1563 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1564 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1565 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1566 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1567 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1568 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1569 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1570 | const SCEV *WideMaxBECount = |
| 1571 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1572 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1573 | getAddExpr(WideStart, |
| 1574 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1575 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1576 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1577 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1578 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1579 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1580 | return getAddRecExpr( |
| 1581 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1582 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1583 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1584 | // Similar to above, only this time treat the step value as signed. |
| 1585 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1586 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1587 | getAddExpr(WideStart, |
| 1588 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1589 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1590 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1591 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1592 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1593 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1594 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1595 | return getAddRecExpr( |
| 1596 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1597 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1598 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1599 | } |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1600 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1601 | |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1602 | // Normally, in the cases we can prove no-overflow via a |
| 1603 | // backedge guarding condition, we can also compute a backedge |
| 1604 | // taken count for the loop. The exceptions are assumptions and |
| 1605 | // guards present in the loop -- SCEV is not great at exploiting |
| 1606 | // these to compute max backedge taken counts, but can still use |
| 1607 | // these to prove lack of overflow. Use this fact to avoid |
| 1608 | // doing extra work that may not pay off. |
| 1609 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1610 | !AC.assumptions().empty()) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1611 | // If the backedge is guarded by a comparison with the pre-inc |
| 1612 | // value the addrec is safe. Also, if the entry is guarded by |
| 1613 | // a comparison with the start value and the backedge is |
| 1614 | // guarded by a comparison with the post-inc value, the addrec |
| 1615 | // is safe. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1616 | if (isKnownPositive(Step)) { |
| 1617 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1618 | getUnsignedRange(Step).getUnsignedMax()); |
| 1619 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1620 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1621 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1622 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1623 | // Cache knowledge of AR NUW, which is propagated to this |
| 1624 | // AddRec. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1625 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1626 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1627 | return getAddRecExpr( |
| 1628 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1629 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1630 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1631 | } else if (isKnownNegative(Step)) { |
| 1632 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1633 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1634 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1635 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1636 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1637 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1638 | // Cache knowledge of AR NW, which is propagated to this |
| 1639 | // AddRec. Negative step causes unsigned wrap, but it |
| 1640 | // still can't self-wrap. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1641 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1642 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1643 | return getAddRecExpr( |
| 1644 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1645 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1646 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1647 | } |
| 1648 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1649 | |
| 1650 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1651 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1652 | return getAddRecExpr( |
| 1653 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1654 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1655 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1656 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1657 | |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1658 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1659 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1660 | if (SA->hasNoUnsignedWrap()) { |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1661 | // If the addition does not unsign overflow then we can, by definition, |
| 1662 | // commute the zero extension with the addition operation. |
| 1663 | SmallVector<const SCEV *, 4> Ops; |
| 1664 | for (const auto *Op : SA->operands()) |
| 1665 | Ops.push_back(getZeroExtendExpr(Op, Ty)); |
| 1666 | return getAddExpr(Ops, SCEV::FlagNUW); |
| 1667 | } |
| 1668 | } |
| 1669 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1670 | // The cast wasn't folded; create an explicit cast node. |
| 1671 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1672 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1673 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1674 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1675 | UniqueSCEVs.InsertNode(S, IP); |
| 1676 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1677 | } |
| 1678 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1679 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1680 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1681 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1682 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1683 | assert(isSCEVable(Ty) && |
| 1684 | "This is not a conversion to a SCEVable type!"); |
| 1685 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1686 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1687 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1688 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1689 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1690 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1691 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1692 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1693 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1694 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1695 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1696 | // sext(zext(x)) --> zext(x) |
| 1697 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1698 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1699 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1700 | // Before doing any expensive analysis, check to see if we've already |
| 1701 | // computed a SCEV for this Op and Ty. |
| 1702 | FoldingSetNodeID ID; |
| 1703 | ID.AddInteger(scSignExtend); |
| 1704 | ID.AddPointer(Op); |
| 1705 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1706 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1707 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1708 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1709 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1710 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1711 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1712 | // so, we should be able to simplify this further. |
| 1713 | const SCEV *X = ST->getOperand(); |
| 1714 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1715 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1716 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1717 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1718 | CR.sextOrTrunc(NewBits))) |
| 1719 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1720 | } |
| 1721 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1722 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1723 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1724 | if (SA->getNumOperands() == 2) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1725 | auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1726 | auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1727 | if (SMul && SC1) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1728 | if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1729 | const APInt &C1 = SC1->getAPInt(); |
| 1730 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1731 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1732 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1733 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1734 | getSignExtendExpr(SMul, Ty)); |
| 1735 | } |
| 1736 | } |
| 1737 | } |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1738 | |
| 1739 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1740 | if (SA->hasNoSignedWrap()) { |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1741 | // If the addition does not sign overflow then we can, by definition, |
| 1742 | // commute the sign extension with the addition operation. |
| 1743 | SmallVector<const SCEV *, 4> Ops; |
| 1744 | for (const auto *Op : SA->operands()) |
| 1745 | Ops.push_back(getSignExtendExpr(Op, Ty)); |
| 1746 | return getAddExpr(Ops, SCEV::FlagNSW); |
| 1747 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1748 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1749 | // 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] | 1750 | // 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] | 1751 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1752 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1753 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1754 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1755 | const SCEV *Start = AR->getStart(); |
| 1756 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1757 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1758 | const Loop *L = AR->getLoop(); |
| 1759 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1760 | if (!AR->hasNoSignedWrap()) { |
| 1761 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1762 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1763 | } |
| 1764 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1765 | // If we have special knowledge that this addrec won't overflow, |
| 1766 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1767 | if (AR->hasNoSignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1768 | return getAddRecExpr( |
| 1769 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1770 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1771 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1772 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1773 | // Note that this serves two purposes: It filters out loops that are |
| 1774 | // simply not analyzable, and it covers the case where this code is |
| 1775 | // being called from within backedge-taken count analysis, such that |
| 1776 | // attempting to ask for the backedge-taken count would likely result |
| 1777 | // in infinite recursion. In the later case, the analysis code will |
| 1778 | // cope with a conservative value, and it will take care to purge |
| 1779 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1780 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1781 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1782 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1783 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1784 | |
| 1785 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1786 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1787 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1788 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1789 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1790 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1791 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1792 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1793 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1794 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1795 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1796 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1797 | const SCEV *WideMaxBECount = |
| 1798 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1799 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1800 | getAddExpr(WideStart, |
| 1801 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1802 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1803 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1804 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1805 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1806 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1807 | return getAddRecExpr( |
| 1808 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1809 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1810 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1811 | // Similar to above, only this time treat the step value as unsigned. |
| 1812 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1813 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1814 | getAddExpr(WideStart, |
| 1815 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1816 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1817 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1818 | // If AR wraps around then |
| 1819 | // |
| 1820 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1821 | // => SAdd != OperandExtendedAdd |
| 1822 | // |
| 1823 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1824 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1825 | |
| 1826 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1827 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1828 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1829 | return getAddRecExpr( |
| 1830 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1831 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1832 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1833 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1834 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1835 | |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1836 | // Normally, in the cases we can prove no-overflow via a |
| 1837 | // backedge guarding condition, we can also compute a backedge |
| 1838 | // taken count for the loop. The exceptions are assumptions and |
| 1839 | // guards present in the loop -- SCEV is not great at exploiting |
| 1840 | // these to compute max backedge taken counts, but can still use |
| 1841 | // these to prove lack of overflow. Use this fact to avoid |
| 1842 | // doing extra work that may not pay off. |
| 1843 | |
| 1844 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1845 | !AC.assumptions().empty()) { |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1846 | // If the backedge is guarded by a comparison with the pre-inc |
| 1847 | // value the addrec is safe. Also, if the entry is guarded by |
| 1848 | // a comparison with the start value and the backedge is |
| 1849 | // guarded by a comparison with the post-inc value, the addrec |
| 1850 | // is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1851 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1852 | const SCEV *OverflowLimit = |
| 1853 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1854 | if (OverflowLimit && |
| 1855 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1856 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1857 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1858 | OverflowLimit)))) { |
| 1859 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1860 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1861 | return getAddRecExpr( |
| 1862 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1863 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1864 | } |
| 1865 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1866 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1867 | // If Start and Step are constants, check if we can apply this |
| 1868 | // transformation: |
| 1869 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1870 | auto *SC1 = dyn_cast<SCEVConstant>(Start); |
| 1871 | auto *SC2 = dyn_cast<SCEVConstant>(Step); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1872 | if (SC1 && SC2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1873 | const APInt &C1 = SC1->getAPInt(); |
| 1874 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1875 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1876 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1877 | Start = getSignExtendExpr(Start, Ty); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1878 | const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, |
| 1879 | AR->getNoWrapFlags()); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1880 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1881 | } |
| 1882 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1883 | |
| 1884 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1885 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1886 | return getAddRecExpr( |
| 1887 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1888 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1889 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1890 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1891 | |
Sanjoy Das | 11ef606 | 2016-03-03 18:31:23 +0000 | [diff] [blame] | 1892 | // If the input value is provably positive and we could not simplify |
| 1893 | // away the sext build a zext instead. |
| 1894 | if (isKnownNonNegative(Op)) |
| 1895 | return getZeroExtendExpr(Op, Ty); |
| 1896 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1897 | // The cast wasn't folded; create an explicit cast node. |
| 1898 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1899 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1900 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1901 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1902 | UniqueSCEVs.InsertNode(S, IP); |
| 1903 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1904 | } |
| 1905 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1906 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1907 | /// unspecified bits out to the given type. |
| 1908 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1909 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1910 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1911 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1912 | "This is not an extending conversion!"); |
| 1913 | assert(isSCEVable(Ty) && |
| 1914 | "This is not a conversion to a SCEVable type!"); |
| 1915 | Ty = getEffectiveSCEVType(Ty); |
| 1916 | |
| 1917 | // Sign-extend negative constants. |
| 1918 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1919 | if (SC->getAPInt().isNegative()) |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1920 | return getSignExtendExpr(Op, Ty); |
| 1921 | |
| 1922 | // Peel off a truncate cast. |
| 1923 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1924 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1925 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1926 | return getAnyExtendExpr(NewOp, Ty); |
| 1927 | return getTruncateOrNoop(NewOp, Ty); |
| 1928 | } |
| 1929 | |
| 1930 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1931 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1932 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1933 | return ZExt; |
| 1934 | |
| 1935 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1936 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1937 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1938 | return SExt; |
| 1939 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1940 | // Force the cast to be folded into the operands of an addrec. |
| 1941 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1942 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1943 | for (const SCEV *Op : AR->operands()) |
| 1944 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1945 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1946 | } |
| 1947 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1948 | // If the expression is obviously signed, use the sext cast value. |
| 1949 | if (isa<SCEVSMaxExpr>(Op)) |
| 1950 | return SExt; |
| 1951 | |
| 1952 | // Absent any other information, use the zext cast value. |
| 1953 | return ZExt; |
| 1954 | } |
| 1955 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1956 | /// Process the given Ops list, which is a list of operands to be added under |
| 1957 | /// the given scale, update the given map. This is a helper function for |
| 1958 | /// getAddRecExpr. As an example of what it does, given a sequence of operands |
| 1959 | /// that would form an add expression like this: |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1960 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1961 | /// 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] | 1962 | /// |
| 1963 | /// where A and B are constants, update the map with these values: |
| 1964 | /// |
| 1965 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1966 | /// |
| 1967 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1968 | /// This will allow getAddRecExpr to produce this: |
| 1969 | /// |
| 1970 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1971 | /// |
| 1972 | /// This form often exposes folding opportunities that are hidden in |
| 1973 | /// the original operand list. |
| 1974 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1975 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1976 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1977 | /// the common case where no interesting opportunities are present, and |
| 1978 | /// is also used as a check to avoid infinite recursion. |
| 1979 | /// |
| 1980 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1981 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1982 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1983 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1984 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1985 | const APInt &Scale, |
| 1986 | ScalarEvolution &SE) { |
| 1987 | bool Interesting = false; |
| 1988 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1989 | // Iterate over the add operands. They are sorted, with constants first. |
| 1990 | unsigned i = 0; |
| 1991 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1992 | ++i; |
| 1993 | // Pull a buried constant out to the outside. |
| 1994 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1995 | Interesting = true; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1996 | AccumulatedConstant += Scale * C->getAPInt(); |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1997 | } |
| 1998 | |
| 1999 | // Next comes everything else. We're especially interested in multiplies |
| 2000 | // here, but they're in the middle, so just visit the rest with one loop. |
| 2001 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2002 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 2003 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 2004 | APInt NewScale = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2005 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2006 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 2007 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2008 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2009 | Interesting |= |
| 2010 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2011 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2012 | NewScale, SE); |
| 2013 | } else { |
| 2014 | // A multiplication of a constant with some other value. Update |
| 2015 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2016 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 2017 | const SCEV *Key = SE.getMulExpr(MulOps); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 2018 | auto Pair = M.insert({Key, NewScale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2019 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2020 | NewOps.push_back(Pair.first->first); |
| 2021 | } else { |
| 2022 | Pair.first->second += NewScale; |
| 2023 | // The map already had an entry for this value, which may indicate |
| 2024 | // a folding opportunity. |
| 2025 | Interesting = true; |
| 2026 | } |
| 2027 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2028 | } else { |
| 2029 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2030 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 2031 | M.insert({Ops[i], Scale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2032 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2033 | NewOps.push_back(Pair.first->first); |
| 2034 | } else { |
| 2035 | Pair.first->second += Scale; |
| 2036 | // The map already had an entry for this value, which may indicate |
| 2037 | // a folding opportunity. |
| 2038 | Interesting = true; |
| 2039 | } |
| 2040 | } |
| 2041 | } |
| 2042 | |
| 2043 | return Interesting; |
| 2044 | } |
| 2045 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2046 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 2047 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 2048 | // can't-overflow flags for the operation if possible. |
| 2049 | static SCEV::NoWrapFlags |
| 2050 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 2051 | const SmallVectorImpl<const SCEV *> &Ops, |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2052 | SCEV::NoWrapFlags Flags) { |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2053 | using namespace std::placeholders; |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2054 | typedef OverflowingBinaryOperator OBO; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2055 | |
| 2056 | bool CanAnalyze = |
| 2057 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 2058 | (void)CanAnalyze; |
| 2059 | assert(CanAnalyze && "don't call from other places!"); |
| 2060 | |
| 2061 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 2062 | SCEV::NoWrapFlags SignOrUnsignWrap = |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2063 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2064 | |
| 2065 | // 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] | 2066 | auto IsKnownNonNegative = [&](const SCEV *S) { |
| 2067 | return SE->isKnownNonNegative(S); |
| 2068 | }; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2069 | |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2070 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2071 | Flags = |
| 2072 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2073 | |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2074 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
| 2075 | |
| 2076 | if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && |
| 2077 | Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { |
| 2078 | |
| 2079 | // (A + C) --> (A + C)<nsw> if the addition does not sign overflow |
| 2080 | // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow |
| 2081 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2082 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2083 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2084 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2085 | Instruction::Add, C, OBO::NoSignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2086 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) |
| 2087 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 2088 | } |
| 2089 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2090 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2091 | Instruction::Add, C, OBO::NoUnsignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2092 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) |
| 2093 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 2094 | } |
| 2095 | } |
| 2096 | |
| 2097 | return Flags; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2098 | } |
| 2099 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2100 | /// Get a canonical add expression, or something simpler if possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2101 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2102 | SCEV::NoWrapFlags Flags) { |
| 2103 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 2104 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2105 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2106 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2107 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2108 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2109 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 2110 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2111 | "SCEVAddExpr operand types don't match!"); |
| 2112 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2113 | |
| 2114 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2115 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2116 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2117 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
| 2118 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2119 | // If there are any constants, fold them together. |
| 2120 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2121 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2122 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2123 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2124 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2125 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2126 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 2127 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2128 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2129 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2130 | } |
| 2131 | |
| 2132 | // 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] | 2133 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2134 | Ops.erase(Ops.begin()); |
| 2135 | --Idx; |
| 2136 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2137 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2138 | if (Ops.size() == 1) return Ops[0]; |
| 2139 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2140 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2141 | // Okay, check to see if the same value occurs in the operand list more than |
Reid Kleckner | 30422ee | 2016-12-12 18:52:32 +0000 | [diff] [blame] | 2142 | // once. If so, merge them together into an multiply expression. Since we |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2143 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2144 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2145 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2146 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2147 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2148 | // Scan ahead to count how many equal operands there are. |
| 2149 | unsigned Count = 2; |
| 2150 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2151 | ++Count; |
| 2152 | // Merge the values into a multiply. |
| 2153 | const SCEV *Scale = getConstant(Ty, Count); |
| 2154 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2155 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2156 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2157 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2158 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2159 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2160 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2161 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2162 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2163 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2164 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2165 | // Check for truncates. If all the operands are truncated from the same |
| 2166 | // type, see if factoring out the truncate would permit the result to be |
| 2167 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2168 | // if the contents of the resulting outer trunc fold to something simple. |
| 2169 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2170 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2171 | Type *DstType = Trunc->getType(); |
| 2172 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2173 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2174 | bool Ok = true; |
| 2175 | // Check all the operands to see if they can be represented in the |
| 2176 | // source type of the truncate. |
| 2177 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2178 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2179 | if (T->getOperand()->getType() != SrcType) { |
| 2180 | Ok = false; |
| 2181 | break; |
| 2182 | } |
| 2183 | LargeOps.push_back(T->getOperand()); |
| 2184 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2185 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2186 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2187 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2188 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2189 | if (const SCEVTruncateExpr *T = |
| 2190 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2191 | if (T->getOperand()->getType() != SrcType) { |
| 2192 | Ok = false; |
| 2193 | break; |
| 2194 | } |
| 2195 | LargeMulOps.push_back(T->getOperand()); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2196 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2197 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2198 | } else { |
| 2199 | Ok = false; |
| 2200 | break; |
| 2201 | } |
| 2202 | } |
| 2203 | if (Ok) |
| 2204 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2205 | } else { |
| 2206 | Ok = false; |
| 2207 | break; |
| 2208 | } |
| 2209 | } |
| 2210 | if (Ok) { |
| 2211 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2212 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2213 | // If it folds to something simple, use it. Otherwise, don't. |
| 2214 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2215 | return getTruncateExpr(Fold, DstType); |
| 2216 | } |
| 2217 | } |
| 2218 | |
| 2219 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2220 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2221 | ++Idx; |
| 2222 | |
| 2223 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2224 | if (Idx < Ops.size()) { |
| 2225 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2226 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Daniil Fukalov | b09dac5 | 2017-01-26 13:33:17 +0000 | [diff] [blame^] | 2227 | if (Ops.size() > AddOpsInlineThreshold || |
| 2228 | Add->getNumOperands() > AddOpsInlineThreshold) |
| 2229 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2230 | // If we have an add, expand the add operands onto the end of the operands |
| 2231 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2232 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2233 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2234 | DeletedAdd = true; |
| 2235 | } |
| 2236 | |
| 2237 | // If we deleted at least one add, we added operands to the end of the list, |
| 2238 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2239 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2240 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2241 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2242 | } |
| 2243 | |
| 2244 | // Skip over the add expression until we get to a multiply. |
| 2245 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2246 | ++Idx; |
| 2247 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2248 | // Check to see if there are any folding opportunities present with |
| 2249 | // operands multiplied by constant values. |
| 2250 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2251 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2252 | DenseMap<const SCEV *, APInt> M; |
| 2253 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2254 | APInt AccumulatedConstant(BitWidth, 0); |
| 2255 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2256 | Ops.data(), Ops.size(), |
| 2257 | APInt(BitWidth, 1), *this)) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 2258 | struct APIntCompare { |
| 2259 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 2260 | return LHS.ult(RHS); |
| 2261 | } |
| 2262 | }; |
| 2263 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2264 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2265 | // re-generate the operands list. Group the operands by constant scale, |
| 2266 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2267 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2268 | for (const SCEV *NewOp : NewOps) |
| 2269 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2270 | // Re-generate the operands list. |
| 2271 | Ops.clear(); |
| 2272 | if (AccumulatedConstant != 0) |
| 2273 | Ops.push_back(getConstant(AccumulatedConstant)); |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2274 | for (auto &MulOp : MulOpLists) |
| 2275 | if (MulOp.first != 0) |
| 2276 | Ops.push_back(getMulExpr(getConstant(MulOp.first), |
| 2277 | getAddExpr(MulOp.second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2278 | if (Ops.empty()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2279 | return getZero(Ty); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2280 | if (Ops.size() == 1) |
| 2281 | return Ops[0]; |
| 2282 | return getAddExpr(Ops); |
| 2283 | } |
| 2284 | } |
| 2285 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2286 | // If we are adding something to a multiply expression, make sure the |
| 2287 | // something is not already an operand of the multiply. If so, merge it into |
| 2288 | // the multiply. |
| 2289 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2290 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2291 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2292 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2293 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2294 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2295 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2296 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2297 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2298 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2299 | if (Mul->getNumOperands() != 2) { |
| 2300 | // If the multiply has more than two operands, we must get the |
| 2301 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2302 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2303 | Mul->op_begin()+MulOp); |
| 2304 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2305 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2306 | } |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2307 | const SCEV *One = getOne(Ty); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2308 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2309 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2310 | if (Ops.size() == 2) return OuterMul; |
| 2311 | if (AddOp < Idx) { |
| 2312 | Ops.erase(Ops.begin()+AddOp); |
| 2313 | Ops.erase(Ops.begin()+Idx-1); |
| 2314 | } else { |
| 2315 | Ops.erase(Ops.begin()+Idx); |
| 2316 | Ops.erase(Ops.begin()+AddOp-1); |
| 2317 | } |
| 2318 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2319 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2320 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2321 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2322 | // Check this multiply against other multiplies being added together. |
| 2323 | for (unsigned OtherMulIdx = Idx+1; |
| 2324 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2325 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2326 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2327 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2328 | // together. |
| 2329 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2330 | OMulOp != e; ++OMulOp) |
| 2331 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2332 | // 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] | 2333 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2334 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2335 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2336 | Mul->op_begin()+MulOp); |
| 2337 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2338 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2339 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2340 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2341 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2342 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2343 | OtherMul->op_begin()+OMulOp); |
| 2344 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2345 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2346 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2347 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2348 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2349 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2350 | Ops.erase(Ops.begin()+Idx); |
| 2351 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2352 | Ops.push_back(OuterMul); |
| 2353 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2354 | } |
| 2355 | } |
| 2356 | } |
| 2357 | } |
| 2358 | |
| 2359 | // If there are any add recurrences in the operands list, see if any other |
| 2360 | // added values are loop invariant. If so, we can fold them into the |
| 2361 | // recurrence. |
| 2362 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2363 | ++Idx; |
| 2364 | |
| 2365 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2366 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2367 | // Scan all of the other operands to this add and add them to the vector if |
| 2368 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2369 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2370 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2371 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2372 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2373 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2374 | LIOps.push_back(Ops[i]); |
| 2375 | Ops.erase(Ops.begin()+i); |
| 2376 | --i; --e; |
| 2377 | } |
| 2378 | |
| 2379 | // If we found some loop invariants, fold them into the recurrence. |
| 2380 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2381 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2382 | LIOps.push_back(AddRec->getStart()); |
| 2383 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2384 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2385 | AddRec->op_end()); |
Oleg Ranevskyy | eb4ecca | 2016-05-25 13:01:33 +0000 | [diff] [blame] | 2386 | // This follows from the fact that the no-wrap flags on the outer add |
| 2387 | // expression are applicable on the 0th iteration, when the add recurrence |
| 2388 | // will be equal to its start value. |
| 2389 | AddRecOps[0] = getAddExpr(LIOps, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2390 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2391 | // 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] | 2392 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2393 | // Always propagate NW. |
| 2394 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2395 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2396 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2397 | // If all of the other operands were loop invariant, we are done. |
| 2398 | if (Ops.size() == 1) return NewRec; |
| 2399 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2400 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2401 | for (unsigned i = 0;; ++i) |
| 2402 | if (Ops[i] == AddRec) { |
| 2403 | Ops[i] = NewRec; |
| 2404 | break; |
| 2405 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2406 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2407 | } |
| 2408 | |
| 2409 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2410 | // there are multiple AddRec's with the same loop induction variable being |
| 2411 | // added together. If so, we can fold them. |
| 2412 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2413 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2414 | ++OtherIdx) |
| 2415 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2416 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2417 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2418 | AddRec->op_end()); |
| 2419 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2420 | ++OtherIdx) |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2421 | if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2422 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2423 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2424 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2425 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2426 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2427 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2428 | break; |
| 2429 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2430 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2431 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2432 | } |
| 2433 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2434 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2435 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2436 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2437 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2438 | } |
| 2439 | |
| 2440 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2441 | // next one. |
| 2442 | } |
| 2443 | |
| 2444 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2445 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2446 | FoldingSetNodeID ID; |
| 2447 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2448 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2449 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2450 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2451 | SCEVAddExpr *S = |
| 2452 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2453 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2454 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2455 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2456 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2457 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2458 | UniqueSCEVs.InsertNode(S, IP); |
| 2459 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2460 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2461 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2462 | } |
| 2463 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2464 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2465 | uint64_t k = i*j; |
| 2466 | if (j > 1 && k / j != i) Overflow = true; |
| 2467 | return k; |
| 2468 | } |
| 2469 | |
| 2470 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2471 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2472 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2473 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2474 | // We use the multiplicative formula: |
| 2475 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2476 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2477 | // (k-n)th term of the denominator. This division will always produce an |
| 2478 | // integral result, and helps reduce the chance of overflow in the |
| 2479 | // intermediate computations. However, we can still overflow even when the |
| 2480 | // final result would fit. |
| 2481 | |
| 2482 | if (n == 0 || n == k) return 1; |
| 2483 | if (k > n) return 0; |
| 2484 | |
| 2485 | if (k > n/2) |
| 2486 | k = n-k; |
| 2487 | |
| 2488 | uint64_t r = 1; |
| 2489 | for (uint64_t i = 1; i <= k; ++i) { |
| 2490 | r = umul_ov(r, n-(i-1), Overflow); |
| 2491 | r /= i; |
| 2492 | } |
| 2493 | return r; |
| 2494 | } |
| 2495 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2496 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2497 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2498 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2499 | SmallVector<const SCEV *, 4> Ops; |
| 2500 | Ops.push_back(StartExpr); |
| 2501 | while (!Ops.empty()) { |
| 2502 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2503 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2504 | return true; |
| 2505 | |
| 2506 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2507 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2508 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2509 | } |
| 2510 | } |
| 2511 | return false; |
| 2512 | } |
| 2513 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2514 | /// Get a canonical multiply expression, or something simpler if possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2515 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2516 | SCEV::NoWrapFlags Flags) { |
| 2517 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2518 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2519 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2520 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2521 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2522 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2523 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2524 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2525 | "SCEVMulExpr operand types don't match!"); |
| 2526 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2527 | |
| 2528 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2529 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2530 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2531 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
| 2532 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2533 | // If there are any constants, fold them together. |
| 2534 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2535 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2536 | |
| 2537 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2538 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2539 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2540 | // If any of Add's ops are Adds or Muls with a constant, |
| 2541 | // apply this transformation as well. |
| 2542 | if (Add->getNumOperands() == 2) |
| 2543 | if (containsConstantSomewhere(Add)) |
| 2544 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2545 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2546 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2547 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2548 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2549 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2550 | ConstantInt *Fold = |
| 2551 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2552 | Ops[0] = getConstant(Fold); |
| 2553 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2554 | if (Ops.size() == 1) return Ops[0]; |
| 2555 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2556 | } |
| 2557 | |
| 2558 | // If we are left with a constant one being multiplied, strip it off. |
| 2559 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2560 | Ops.erase(Ops.begin()); |
| 2561 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2562 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2563 | // If we have a multiply of zero, it will always be zero. |
| 2564 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2565 | } else if (Ops[0]->isAllOnesValue()) { |
| 2566 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2567 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2568 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2569 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2570 | SmallVector<const SCEV *, 4> NewOps; |
| 2571 | bool AnyFolded = false; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2572 | for (const SCEV *AddOp : Add->operands()) { |
| 2573 | const SCEV *Mul = getMulExpr(Ops[0], AddOp); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2574 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2575 | NewOps.push_back(Mul); |
| 2576 | } |
| 2577 | if (AnyFolded) |
| 2578 | return getAddExpr(NewOps); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2579 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2580 | // Negation preserves a recurrence's no self-wrap property. |
| 2581 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2582 | for (const SCEV *AddRecOp : AddRec->operands()) |
| 2583 | Operands.push_back(getMulExpr(Ops[0], AddRecOp)); |
| 2584 | |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2585 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2586 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2587 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2588 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2589 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2590 | |
| 2591 | if (Ops.size() == 1) |
| 2592 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2593 | } |
| 2594 | |
| 2595 | // Skip over the add expression until we get to a multiply. |
| 2596 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2597 | ++Idx; |
| 2598 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2599 | // If there are mul operands inline them all into this expression. |
| 2600 | if (Idx < Ops.size()) { |
| 2601 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2602 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Li Huang | fcfe8cd | 2016-10-20 21:38:39 +0000 | [diff] [blame] | 2603 | if (Ops.size() > MulOpsInlineThreshold) |
| 2604 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2605 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2606 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2607 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2608 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2609 | DeletedMul = true; |
| 2610 | } |
| 2611 | |
| 2612 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2613 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2614 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2615 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2616 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2617 | } |
| 2618 | |
| 2619 | // If there are any add recurrences in the operands list, see if any other |
| 2620 | // added values are loop invariant. If so, we can fold them into the |
| 2621 | // recurrence. |
| 2622 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2623 | ++Idx; |
| 2624 | |
| 2625 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2626 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2627 | // Scan all of the other operands to this mul and add them to the vector if |
| 2628 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2629 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2630 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2631 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2632 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2633 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2634 | LIOps.push_back(Ops[i]); |
| 2635 | Ops.erase(Ops.begin()+i); |
| 2636 | --i; --e; |
| 2637 | } |
| 2638 | |
| 2639 | // If we found some loop invariants, fold them into the recurrence. |
| 2640 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2641 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2642 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2643 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2644 | const SCEV *Scale = getMulExpr(LIOps); |
| 2645 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2646 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2647 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2648 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2649 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2650 | // |
| 2651 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2652 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2653 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2654 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2655 | |
| 2656 | // If all of the other operands were loop invariant, we are done. |
| 2657 | if (Ops.size() == 1) return NewRec; |
| 2658 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2659 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2660 | for (unsigned i = 0;; ++i) |
| 2661 | if (Ops[i] == AddRec) { |
| 2662 | Ops[i] = NewRec; |
| 2663 | break; |
| 2664 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2665 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2666 | } |
| 2667 | |
| 2668 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2669 | // there are multiple AddRec's with the same loop induction variable being |
| 2670 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2671 | |
| 2672 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2673 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2674 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2675 | // ]]],+,...up to x=2n}. |
| 2676 | // Note that the arguments to choose() are always integers with values |
| 2677 | // known at compile time, never SCEV objects. |
| 2678 | // |
| 2679 | // The implementation avoids pointless extra computations when the two |
| 2680 | // addrec's are of different length (mathematically, it's equivalent to |
| 2681 | // an infinite stream of zeros on the right). |
| 2682 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2683 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2684 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2685 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2686 | const SCEVAddRecExpr *OtherAddRec = |
| 2687 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2688 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2689 | continue; |
| 2690 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2691 | bool Overflow = false; |
| 2692 | Type *Ty = AddRec->getType(); |
| 2693 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2694 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2695 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2696 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2697 | const SCEV *Term = getZero(Ty); |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2698 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2699 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2700 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2701 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2702 | z < ze && !Overflow; ++z) { |
| 2703 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2704 | uint64_t Coeff; |
| 2705 | if (LargerThan64Bits) |
| 2706 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2707 | else |
| 2708 | Coeff = Coeff1*Coeff2; |
| 2709 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2710 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2711 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2712 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2713 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2714 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2715 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2716 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2717 | if (!Overflow) { |
| 2718 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2719 | SCEV::FlagAnyWrap); |
| 2720 | if (Ops.size() == 2) return NewAddRec; |
| 2721 | Ops[Idx] = NewAddRec; |
| 2722 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2723 | OpsModified = true; |
| 2724 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2725 | if (!AddRec) |
| 2726 | break; |
| 2727 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2728 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2729 | if (OpsModified) |
| 2730 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2731 | |
| 2732 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2733 | // next one. |
| 2734 | } |
| 2735 | |
| 2736 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2737 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2738 | FoldingSetNodeID ID; |
| 2739 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2740 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2741 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2742 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2743 | SCEVMulExpr *S = |
| 2744 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2745 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2746 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2747 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2748 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2749 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2750 | UniqueSCEVs.InsertNode(S, IP); |
| 2751 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2752 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2753 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2754 | } |
| 2755 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2756 | /// Get a canonical unsigned division expression, or something simpler if |
| 2757 | /// possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2758 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2759 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2760 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2761 | getEffectiveSCEVType(RHS->getType()) && |
| 2762 | "SCEVUDivExpr operand types don't match!"); |
| 2763 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2764 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2765 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2766 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2767 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2768 | // try to analyze it, because the resolution chosen here may differ from |
| 2769 | // the resolution chosen in other parts of the compiler. |
| 2770 | if (!RHSC->getValue()->isZero()) { |
| 2771 | // Determine if the division can be folded into the operands of |
| 2772 | // its operands. |
| 2773 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2774 | Type *Ty = LHS->getType(); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2775 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2776 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2777 | // For non-power-of-two values, effectively round the value up to the |
| 2778 | // nearest power of two. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2779 | if (!RHSC->getAPInt().isPowerOf2()) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2780 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2781 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2782 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2783 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2784 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2785 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2786 | // {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] | 2787 | const APInt &StepInt = Step->getAPInt(); |
| 2788 | const APInt &DivInt = RHSC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2789 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2790 | getZeroExtendExpr(AR, ExtTy) == |
| 2791 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2792 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2793 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2794 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2795 | for (const SCEV *Op : AR->operands()) |
| 2796 | Operands.push_back(getUDivExpr(Op, RHS)); |
| 2797 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2798 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2799 | /// Get a canonical UDivExpr for a recurrence. |
| 2800 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2801 | // We can currently only fold X%N if X is constant. |
| 2802 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2803 | if (StartC && !DivInt.urem(StepInt) && |
| 2804 | getZeroExtendExpr(AR, ExtTy) == |
| 2805 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2806 | getZeroExtendExpr(Step, ExtTy), |
| 2807 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2808 | const APInt &StartInt = StartC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2809 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2810 | if (StartRem != 0) |
| 2811 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2812 | AR->getLoop(), SCEV::FlagNW); |
| 2813 | } |
| 2814 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2815 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2816 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2817 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2818 | for (const SCEV *Op : M->operands()) |
| 2819 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2820 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2821 | // Find an operand that's safely divisible. |
| 2822 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2823 | const SCEV *Op = M->getOperand(i); |
| 2824 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2825 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2826 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2827 | M->op_end()); |
| 2828 | Operands[i] = Div; |
| 2829 | return getMulExpr(Operands); |
| 2830 | } |
| 2831 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2832 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2833 | // (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] | 2834 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2835 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2836 | for (const SCEV *Op : A->operands()) |
| 2837 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2838 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2839 | Operands.clear(); |
| 2840 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2841 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2842 | if (isa<SCEVUDivExpr>(Op) || |
| 2843 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2844 | break; |
| 2845 | Operands.push_back(Op); |
| 2846 | } |
| 2847 | if (Operands.size() == A->getNumOperands()) |
| 2848 | return getAddExpr(Operands); |
| 2849 | } |
| 2850 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2851 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2852 | // Fold if both operands are constant. |
| 2853 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2854 | Constant *LHSCV = LHSC->getValue(); |
| 2855 | Constant *RHSCV = RHSC->getValue(); |
| 2856 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2857 | RHSCV))); |
| 2858 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2859 | } |
| 2860 | } |
| 2861 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2862 | FoldingSetNodeID ID; |
| 2863 | ID.AddInteger(scUDivExpr); |
| 2864 | ID.AddPointer(LHS); |
| 2865 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2866 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2867 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2868 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2869 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2870 | UniqueSCEVs.InsertNode(S, IP); |
| 2871 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2872 | } |
| 2873 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2874 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2875 | APInt A = C1->getAPInt().abs(); |
| 2876 | APInt B = C2->getAPInt().abs(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2877 | uint32_t ABW = A.getBitWidth(); |
| 2878 | uint32_t BBW = B.getBitWidth(); |
| 2879 | |
| 2880 | if (ABW > BBW) |
| 2881 | B = B.zext(ABW); |
| 2882 | else if (ABW < BBW) |
| 2883 | A = A.zext(BBW); |
| 2884 | |
| 2885 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2886 | } |
| 2887 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2888 | /// Get a canonical unsigned division expression, or something simpler if |
| 2889 | /// possible. There is no representation for an exact udiv in SCEV IR, but we |
| 2890 | /// can attempt to remove factors from the LHS and RHS. We can't do this when |
| 2891 | /// it's not exact because the udiv may be clearing bits. |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2892 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2893 | const SCEV *RHS) { |
| 2894 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2895 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2896 | // end of this file for inspiration. |
| 2897 | |
| 2898 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
Eli Friedman | f1f49c8 | 2017-01-18 23:56:42 +0000 | [diff] [blame] | 2899 | if (!Mul || !Mul->hasNoUnsignedWrap()) |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2900 | return getUDivExpr(LHS, RHS); |
| 2901 | |
| 2902 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2903 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2904 | // first element of the mulexpr. |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2905 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2906 | if (LHSCst == RHSCst) { |
| 2907 | SmallVector<const SCEV *, 2> Operands; |
| 2908 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2909 | return getMulExpr(Operands); |
| 2910 | } |
| 2911 | |
| 2912 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2913 | // that there's a factor provided by one of the other terms. We need to |
| 2914 | // check. |
| 2915 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2916 | if (!Factor.isIntN(1)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2917 | LHSCst = |
| 2918 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); |
| 2919 | RHSCst = |
| 2920 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2921 | SmallVector<const SCEV *, 2> Operands; |
| 2922 | Operands.push_back(LHSCst); |
| 2923 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2924 | LHS = getMulExpr(Operands); |
| 2925 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2926 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2927 | if (!Mul) |
| 2928 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2929 | } |
| 2930 | } |
| 2931 | } |
| 2932 | |
| 2933 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2934 | if (Mul->getOperand(i) == RHS) { |
| 2935 | SmallVector<const SCEV *, 2> Operands; |
| 2936 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2937 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2938 | return getMulExpr(Operands); |
| 2939 | } |
| 2940 | } |
| 2941 | |
| 2942 | return getUDivExpr(LHS, RHS); |
| 2943 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2944 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2945 | /// Get an add recurrence expression for the specified loop. Simplify the |
| 2946 | /// expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2947 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2948 | const Loop *L, |
| 2949 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2950 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2951 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2952 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2953 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2954 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2955 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2956 | } |
| 2957 | |
| 2958 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2959 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2960 | } |
| 2961 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2962 | /// Get an add recurrence expression for the specified loop. Simplify the |
| 2963 | /// expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2964 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2965 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2966 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2967 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2968 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2969 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2970 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2971 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2972 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2973 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2974 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2975 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2976 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2977 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2978 | if (Operands.back()->isZero()) { |
| 2979 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2980 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2981 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2982 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2983 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2984 | // use that information to infer NUW and NSW flags. However, computing a |
| 2985 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2986 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2987 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2988 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2989 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2990 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2991 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2992 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2993 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2994 | if (L->contains(NestedLoop) |
| 2995 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2996 | : (!NestedLoop->contains(L) && |
| 2997 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2998 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2999 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 3000 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 3001 | // AddRecs require their operands be loop-invariant with respect to their |
| 3002 | // loops. Don't perform this transformation if it would break this |
| 3003 | // requirement. |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 3004 | bool AllInvariant = all_of( |
| 3005 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 3006 | |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 3007 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3008 | // Create a recurrence for the outer loop with the same step size. |
| 3009 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3010 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 3011 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 3012 | SCEV::NoWrapFlags OuterFlags = |
| 3013 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3014 | |
| 3015 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 3016 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { |
| 3017 | return isLoopInvariant(Op, NestedLoop); |
| 3018 | }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 3019 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3020 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 3021 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3022 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3023 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 3024 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 3025 | SCEV::NoWrapFlags InnerFlags = |
| 3026 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3027 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 3028 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 3029 | } |
| 3030 | // Reset Operands to its original state. |
| 3031 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 3032 | } |
| 3033 | } |
| 3034 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 3035 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 3036 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3037 | FoldingSetNodeID ID; |
| 3038 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3039 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 3040 | ID.AddPointer(Operands[i]); |
| 3041 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3042 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3043 | SCEVAddRecExpr *S = |
| 3044 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 3045 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3046 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 3047 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3048 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 3049 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3050 | UniqueSCEVs.InsertNode(S, IP); |
| 3051 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3052 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3053 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3054 | } |
| 3055 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3056 | const SCEV * |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame] | 3057 | ScalarEvolution::getGEPExpr(GEPOperator *GEP, |
| 3058 | const SmallVectorImpl<const SCEV *> &IndexExprs) { |
| 3059 | const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3060 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 3061 | // because SCEV::getType() preserves the address space. |
| 3062 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 3063 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 3064 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 3065 | // 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] | 3066 | // context. This can be fixed similarly to how these flags are handled for |
| 3067 | // adds. |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame] | 3068 | SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW |
| 3069 | : SCEV::FlagAnyWrap; |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3070 | |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3071 | const SCEV *TotalOffset = getZero(IntPtrTy); |
Peter Collingbourne | 4568158 | 2016-12-02 03:05:41 +0000 | [diff] [blame] | 3072 | // The array size is unimportant. The first thing we do on CurTy is getting |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3073 | // its element type. |
Peter Collingbourne | 4568158 | 2016-12-02 03:05:41 +0000 | [diff] [blame] | 3074 | Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3075 | for (const SCEV *IndexExpr : IndexExprs) { |
| 3076 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 3077 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 3078 | // For a struct, add the member offset. |
| 3079 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 3080 | unsigned FieldNo = Index->getZExtValue(); |
| 3081 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 3082 | |
| 3083 | // Add the field offset to the running total offset. |
| 3084 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 3085 | |
| 3086 | // Update CurTy to the type of the field at Index. |
| 3087 | CurTy = STy->getTypeAtIndex(Index); |
| 3088 | } else { |
| 3089 | // Update CurTy to its element type. |
| 3090 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 3091 | // For an array, add the element offset, explicitly scaled. |
| 3092 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 3093 | // Getelementptr indices are signed. |
| 3094 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 3095 | |
| 3096 | // Multiply the index by the element size to compute the element offset. |
| 3097 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 3098 | |
| 3099 | // Add the element offset to the running total offset. |
| 3100 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 3101 | } |
| 3102 | } |
| 3103 | |
| 3104 | // Add the total offset from all the GEP indices to the base. |
| 3105 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 3106 | } |
| 3107 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3108 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 3109 | const SCEV *RHS) { |
Benjamin Kramer | 3bc1edf | 2016-07-02 11:41:39 +0000 | [diff] [blame] | 3110 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3111 | return getSMaxExpr(Ops); |
| 3112 | } |
| 3113 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3114 | const SCEV * |
| 3115 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3116 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 3117 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3118 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3119 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3120 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3121 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3122 | "SCEVSMaxExpr operand types don't match!"); |
| 3123 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3124 | |
| 3125 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3126 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3127 | |
| 3128 | // If there are any constants, fold them together. |
| 3129 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3130 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3131 | ++Idx; |
| 3132 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3133 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3134 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3135 | ConstantInt *Fold = ConstantInt::get( |
| 3136 | getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3137 | Ops[0] = getConstant(Fold); |
| 3138 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3139 | if (Ops.size() == 1) return Ops[0]; |
| 3140 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3141 | } |
| 3142 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3143 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3144 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3145 | Ops.erase(Ops.begin()); |
| 3146 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3147 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3148 | // If we have an smax with a constant maximum-int, it will always be |
| 3149 | // maximum-int. |
| 3150 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3151 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3152 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3153 | if (Ops.size() == 1) return Ops[0]; |
| 3154 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3155 | |
| 3156 | // Find the first SMax |
| 3157 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3158 | ++Idx; |
| 3159 | |
| 3160 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3161 | // onto our operand list, and recurse to simplify. |
| 3162 | if (Idx < Ops.size()) { |
| 3163 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3164 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3165 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3166 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3167 | DeletedSMax = true; |
| 3168 | } |
| 3169 | |
| 3170 | if (DeletedSMax) |
| 3171 | return getSMaxExpr(Ops); |
| 3172 | } |
| 3173 | |
| 3174 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3175 | // so, delete one. Since we sorted the list, these values are required to |
| 3176 | // be adjacent. |
| 3177 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3178 | // X smax Y smax Y --> X smax Y |
| 3179 | // X smax Y --> X, if X is always greater than Y |
| 3180 | if (Ops[i] == Ops[i+1] || |
| 3181 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3182 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3183 | --i; --e; |
| 3184 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3185 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3186 | --i; --e; |
| 3187 | } |
| 3188 | |
| 3189 | if (Ops.size() == 1) return Ops[0]; |
| 3190 | |
| 3191 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3192 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3193 | // 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] | 3194 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3195 | FoldingSetNodeID ID; |
| 3196 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3197 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3198 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3199 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3200 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3201 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3202 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3203 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3204 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3205 | UniqueSCEVs.InsertNode(S, IP); |
| 3206 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3207 | } |
| 3208 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3209 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3210 | const SCEV *RHS) { |
Benjamin Kramer | 3bc1edf | 2016-07-02 11:41:39 +0000 | [diff] [blame] | 3211 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3212 | return getUMaxExpr(Ops); |
| 3213 | } |
| 3214 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3215 | const SCEV * |
| 3216 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3217 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3218 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3219 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3220 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3221 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3222 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3223 | "SCEVUMaxExpr operand types don't match!"); |
| 3224 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3225 | |
| 3226 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3227 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3228 | |
| 3229 | // If there are any constants, fold them together. |
| 3230 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3231 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3232 | ++Idx; |
| 3233 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3234 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3235 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3236 | ConstantInt *Fold = ConstantInt::get( |
| 3237 | getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3238 | Ops[0] = getConstant(Fold); |
| 3239 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3240 | if (Ops.size() == 1) return Ops[0]; |
| 3241 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3242 | } |
| 3243 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3244 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3245 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3246 | Ops.erase(Ops.begin()); |
| 3247 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3248 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3249 | // If we have an umax with a constant maximum-int, it will always be |
| 3250 | // maximum-int. |
| 3251 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3252 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3253 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3254 | if (Ops.size() == 1) return Ops[0]; |
| 3255 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3256 | |
| 3257 | // Find the first UMax |
| 3258 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3259 | ++Idx; |
| 3260 | |
| 3261 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3262 | // onto our operand list, and recurse to simplify. |
| 3263 | if (Idx < Ops.size()) { |
| 3264 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3265 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3266 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3267 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3268 | DeletedUMax = true; |
| 3269 | } |
| 3270 | |
| 3271 | if (DeletedUMax) |
| 3272 | return getUMaxExpr(Ops); |
| 3273 | } |
| 3274 | |
| 3275 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3276 | // so, delete one. Since we sorted the list, these values are required to |
| 3277 | // be adjacent. |
| 3278 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3279 | // X umax Y umax Y --> X umax Y |
| 3280 | // X umax Y --> X, if X is always greater than Y |
| 3281 | if (Ops[i] == Ops[i+1] || |
| 3282 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3283 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3284 | --i; --e; |
| 3285 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3286 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3287 | --i; --e; |
| 3288 | } |
| 3289 | |
| 3290 | if (Ops.size() == 1) return Ops[0]; |
| 3291 | |
| 3292 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3293 | |
| 3294 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3295 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3296 | FoldingSetNodeID ID; |
| 3297 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3298 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3299 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3300 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3301 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3302 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3303 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3304 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3305 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3306 | UniqueSCEVs.InsertNode(S, IP); |
| 3307 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3308 | } |
| 3309 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3310 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3311 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3312 | // ~smax(~x, ~y) == smin(x, y). |
| 3313 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3314 | } |
| 3315 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3316 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3317 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3318 | // ~umax(~x, ~y) == umin(x, y) |
| 3319 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3320 | } |
| 3321 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3322 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3323 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3324 | // constant expression and then folding it back into a ConstantInt. |
| 3325 | // This is just a compile-time optimization. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3326 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3327 | } |
| 3328 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3329 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3330 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3331 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3332 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3333 | // constant expression and then folding it back into a ConstantInt. |
| 3334 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3335 | return getConstant( |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3336 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3337 | } |
| 3338 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3339 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3340 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3341 | // here. createSCEV only calls getUnknown after checking for all other |
| 3342 | // interesting possibilities, and any other code that calls getUnknown |
| 3343 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3344 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3345 | FoldingSetNodeID ID; |
| 3346 | ID.AddInteger(scUnknown); |
| 3347 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3348 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3349 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3350 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3351 | "Stale SCEVUnknown in uniquing map!"); |
| 3352 | return S; |
| 3353 | } |
| 3354 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3355 | FirstUnknown); |
| 3356 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3357 | UniqueSCEVs.InsertNode(S, IP); |
| 3358 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3359 | } |
| 3360 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3361 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3362 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3363 | // |
| 3364 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3365 | /// Test if values of the given type are analyzable within the SCEV |
| 3366 | /// framework. This primarily includes integer types, and it can optionally |
| 3367 | /// include pointer types if the ScalarEvolution class has access to |
| 3368 | /// target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3369 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3370 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3371 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3372 | } |
| 3373 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3374 | /// Return the size in bits of the specified type, for which isSCEVable must |
| 3375 | /// return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3376 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3377 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3378 | return getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3379 | } |
| 3380 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3381 | /// Return a type with the same bitwidth as the given type and which represents |
| 3382 | /// how SCEV will treat the given type, for which isSCEVable must return |
| 3383 | /// true. For pointer types, this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3384 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3385 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3386 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3387 | if (Ty->isIntegerTy()) |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3388 | return Ty; |
| 3389 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3390 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3391 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3392 | return getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3393 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3394 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3395 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3396 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3397 | } |
| 3398 | |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 3399 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 3400 | bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { |
| 3401 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 3402 | return SU && SU->getValue() == nullptr; |
| 3403 | }); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3404 | |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 3405 | return !ContainsNulls; |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3406 | } |
| 3407 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3408 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { |
Sanjoy Das | a260214 | 2016-09-27 18:01:46 +0000 | [diff] [blame] | 3409 | HasRecMapType::iterator I = HasRecMap.find(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3410 | if (I != HasRecMap.end()) |
| 3411 | return I->second; |
| 3412 | |
Sanjoy Das | 0ae390a | 2016-11-10 06:33:54 +0000 | [diff] [blame] | 3413 | bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 3414 | HasRecMap.insert({S, FoundAddRec}); |
| 3415 | return FoundAddRec; |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3416 | } |
| 3417 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3418 | /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. |
| 3419 | /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an |
| 3420 | /// offset I, then return {S', I}, else return {\p S, nullptr}. |
| 3421 | static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { |
| 3422 | const auto *Add = dyn_cast<SCEVAddExpr>(S); |
| 3423 | if (!Add) |
| 3424 | return {S, nullptr}; |
| 3425 | |
| 3426 | if (Add->getNumOperands() != 2) |
| 3427 | return {S, nullptr}; |
| 3428 | |
| 3429 | auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); |
| 3430 | if (!ConstOp) |
| 3431 | return {S, nullptr}; |
| 3432 | |
| 3433 | return {Add->getOperand(1), ConstOp->getValue()}; |
| 3434 | } |
| 3435 | |
| 3436 | /// Return the ValueOffsetPair set for \p S. \p S can be represented |
| 3437 | /// by the value and offset from any ValueOffsetPair in the set. |
| 3438 | SetVector<ScalarEvolution::ValueOffsetPair> * |
| 3439 | ScalarEvolution::getSCEVValues(const SCEV *S) { |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3440 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); |
| 3441 | if (SI == ExprValueMap.end()) |
| 3442 | return nullptr; |
| 3443 | #ifndef NDEBUG |
| 3444 | if (VerifySCEVMap) { |
| 3445 | // Check there is no dangling Value in the set returned. |
| 3446 | for (const auto &VE : SI->second) |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3447 | assert(ValueExprMap.count(VE.first)); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3448 | } |
| 3449 | #endif |
| 3450 | return &SI->second; |
| 3451 | } |
| 3452 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3453 | /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) |
| 3454 | /// cannot be used separately. eraseValueFromMap should be used to remove |
| 3455 | /// V from ValueExprMap and ExprValueMap at the same time. |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3456 | void ScalarEvolution::eraseValueFromMap(Value *V) { |
| 3457 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3458 | if (I != ValueExprMap.end()) { |
| 3459 | const SCEV *S = I->second; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3460 | // Remove {V, 0} from the set of ExprValueMap[S] |
| 3461 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) |
| 3462 | SV->remove({V, nullptr}); |
| 3463 | |
| 3464 | // Remove {V, Offset} from the set of ExprValueMap[Stripped] |
| 3465 | const SCEV *Stripped; |
| 3466 | ConstantInt *Offset; |
| 3467 | std::tie(Stripped, Offset) = splitAddExpr(S); |
| 3468 | if (Offset != nullptr) { |
| 3469 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) |
| 3470 | SV->remove({V, Offset}); |
| 3471 | } |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3472 | ValueExprMap.erase(V); |
| 3473 | } |
| 3474 | } |
| 3475 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3476 | /// Return an existing SCEV if it exists, otherwise analyze the expression and |
| 3477 | /// create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3478 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3479 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3480 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3481 | const SCEV *S = getExistingSCEV(V); |
| 3482 | if (S == nullptr) { |
| 3483 | S = createSCEV(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3484 | // During PHI resolution, it is possible to create two SCEVs for the same |
| 3485 | // V, so it is needed to double check whether V->S is inserted into |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3486 | // ValueExprMap before insert S->{V, 0} into ExprValueMap. |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3487 | std::pair<ValueExprMapType::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3488 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3489 | if (Pair.second) { |
| 3490 | ExprValueMap[S].insert({V, nullptr}); |
| 3491 | |
| 3492 | // If S == Stripped + Offset, add Stripped -> {V, Offset} into |
| 3493 | // ExprValueMap. |
| 3494 | const SCEV *Stripped = S; |
| 3495 | ConstantInt *Offset = nullptr; |
| 3496 | std::tie(Stripped, Offset) = splitAddExpr(S); |
| 3497 | // If stripped is SCEVUnknown, don't bother to save |
| 3498 | // Stripped -> {V, offset}. It doesn't simplify and sometimes even |
| 3499 | // increase the complexity of the expansion code. |
| 3500 | // If V is GetElementPtrInst, don't save Stripped -> {V, offset} |
| 3501 | // because it may generate add/sub instead of GEP in SCEV expansion. |
| 3502 | if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && |
| 3503 | !isa<GetElementPtrInst>(V)) |
| 3504 | ExprValueMap[Stripped].insert({V, Offset}); |
| 3505 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3506 | } |
| 3507 | return S; |
| 3508 | } |
| 3509 | |
| 3510 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3511 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3512 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3513 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3514 | if (I != ValueExprMap.end()) { |
| 3515 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3516 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3517 | return S; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3518 | eraseValueFromMap(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3519 | forgetMemoizedResults(S); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3520 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3521 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3522 | } |
| 3523 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3524 | /// Return a SCEV corresponding to -V = -1*V |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3525 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3526 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3527 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3528 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3529 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3530 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3531 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3532 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3533 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3534 | return getMulExpr( |
| 3535 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3536 | } |
| 3537 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3538 | /// Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3539 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3540 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3541 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3542 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3543 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3544 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3545 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3546 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3547 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3548 | return getMinusSCEV(AllOnes, V); |
| 3549 | } |
| 3550 | |
Chris Lattner | fc87752 | 2011-01-09 22:26:35 +0000 | [diff] [blame] | 3551 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3552 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3553 | // Fast path: X - X --> 0. |
| 3554 | if (LHS == RHS) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3555 | return getZero(LHS->getType()); |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3556 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3557 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3558 | // makes it so that we cannot make much use of NUW. |
| 3559 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3560 | const bool RHSIsNotMinSigned = |
| 3561 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3562 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3563 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3564 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3565 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3566 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3567 | // (-1)*RHS, we need to prove that RHS != M. |
| 3568 | // |
| 3569 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3570 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3571 | // either by proving that RHS > M or that LHS >= 0. |
| 3572 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3573 | AddFlags = SCEV::FlagNSW; |
| 3574 | } |
| 3575 | } |
| 3576 | |
| 3577 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3578 | // RHS is NSW and LHS >= 0. |
| 3579 | // |
| 3580 | // The difficulty here is that the NSW flag may have been proven |
| 3581 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3582 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3583 | // larger scope than intended. |
| 3584 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3585 | |
| 3586 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3587 | } |
| 3588 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3589 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3590 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3591 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3592 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3593 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3594 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3595 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3596 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3597 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3598 | return getTruncateExpr(V, Ty); |
| 3599 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3600 | } |
| 3601 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3602 | const SCEV * |
| 3603 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3604 | Type *Ty) { |
| 3605 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3606 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3607 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3608 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3609 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3610 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3611 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3612 | return getTruncateExpr(V, Ty); |
| 3613 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3614 | } |
| 3615 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3616 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3617 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3618 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3619 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3620 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3621 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3622 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3623 | "getNoopOrZeroExtend cannot truncate!"); |
| 3624 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3625 | return V; // No conversion |
| 3626 | return getZeroExtendExpr(V, Ty); |
| 3627 | } |
| 3628 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3629 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3630 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3631 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3632 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3633 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3634 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3635 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3636 | "getNoopOrSignExtend cannot truncate!"); |
| 3637 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3638 | return V; // No conversion |
| 3639 | return getSignExtendExpr(V, Ty); |
| 3640 | } |
| 3641 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3642 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3643 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3644 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3645 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3646 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3647 | "Cannot noop or any extend with non-integer arguments!"); |
| 3648 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3649 | "getNoopOrAnyExtend cannot truncate!"); |
| 3650 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3651 | return V; // No conversion |
| 3652 | return getAnyExtendExpr(V, Ty); |
| 3653 | } |
| 3654 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3655 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3656 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3657 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3658 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3659 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3660 | "Cannot truncate or noop with non-integer arguments!"); |
| 3661 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3662 | "getTruncateOrNoop cannot extend!"); |
| 3663 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3664 | return V; // No conversion |
| 3665 | return getTruncateExpr(V, Ty); |
| 3666 | } |
| 3667 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3668 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3669 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3670 | const SCEV *PromotedLHS = LHS; |
| 3671 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3672 | |
| 3673 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3674 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3675 | else |
| 3676 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3677 | |
| 3678 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3679 | } |
| 3680 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3681 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3682 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3683 | const SCEV *PromotedLHS = LHS; |
| 3684 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3685 | |
| 3686 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3687 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3688 | else |
| 3689 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3690 | |
| 3691 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3692 | } |
| 3693 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3694 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { |
| 3695 | // A pointer operand may evaluate to a nonpointer expression, such as null. |
| 3696 | if (!V->getType()->isPointerTy()) |
| 3697 | return V; |
| 3698 | |
| 3699 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { |
| 3700 | return getPointerBase(Cast->getOperand()); |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3701 | } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3702 | const SCEV *PtrOp = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3703 | for (const SCEV *NAryOp : NAry->operands()) { |
| 3704 | if (NAryOp->getType()->isPointerTy()) { |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3705 | // Cannot find the base of an expression with multiple pointer operands. |
| 3706 | if (PtrOp) |
| 3707 | return V; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3708 | PtrOp = NAryOp; |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3709 | } |
| 3710 | } |
| 3711 | if (!PtrOp) |
| 3712 | return V; |
| 3713 | return getPointerBase(PtrOp); |
| 3714 | } |
| 3715 | return V; |
| 3716 | } |
| 3717 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3718 | /// Push users of the given Instruction onto the given Worklist. |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3719 | static void |
| 3720 | PushDefUseChildren(Instruction *I, |
| 3721 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3722 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3723 | for (User *U : I->users()) |
| 3724 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3725 | } |
| 3726 | |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3727 | void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3728 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3729 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3730 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3731 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3732 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3733 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3734 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3735 | if (!Visited.insert(I).second) |
| 3736 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3737 | |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 3738 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3739 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3740 | const SCEV *Old = It->second; |
| 3741 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3742 | // Short-circuit the def-use traversal if the symbolic name |
| 3743 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3744 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3745 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3746 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3747 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3748 | // structure, it's a PHI that's in the progress of being computed |
| 3749 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3750 | // additional loop trip count information isn't going to change anything. |
| 3751 | // In the second case, createNodeForPHI will perform the necessary |
| 3752 | // updates on its own when it gets to that point. In the third, we do |
| 3753 | // want to forget the SCEVUnknown. |
| 3754 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3755 | !isa<SCEVUnknown>(Old) || |
| 3756 | (I != PN && Old == SymName)) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3757 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3758 | forgetMemoizedResults(Old); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3759 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3760 | } |
| 3761 | |
| 3762 | PushDefUseChildren(I, Worklist); |
| 3763 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3764 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3765 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3766 | namespace { |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3767 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { |
| 3768 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3769 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3770 | ScalarEvolution &SE) { |
| 3771 | SCEVInitRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3772 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3773 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3774 | } |
| 3775 | |
| 3776 | SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) |
| 3777 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3778 | |
| 3779 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3780 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3781 | Valid = false; |
| 3782 | return Expr; |
| 3783 | } |
| 3784 | |
| 3785 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3786 | // Only allow AddRecExprs for this loop. |
| 3787 | if (Expr->getLoop() == L) |
| 3788 | return Expr->getStart(); |
| 3789 | Valid = false; |
| 3790 | return Expr; |
| 3791 | } |
| 3792 | |
| 3793 | bool isValid() { return Valid; } |
| 3794 | |
| 3795 | private: |
| 3796 | const Loop *L; |
| 3797 | bool Valid; |
| 3798 | }; |
| 3799 | |
| 3800 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { |
| 3801 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3802 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3803 | ScalarEvolution &SE) { |
| 3804 | SCEVShiftRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3805 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3806 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3807 | } |
| 3808 | |
| 3809 | SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) |
| 3810 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3811 | |
| 3812 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3813 | // Only allow AddRecExprs for this loop. |
| 3814 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3815 | Valid = false; |
| 3816 | return Expr; |
| 3817 | } |
| 3818 | |
| 3819 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3820 | if (Expr->getLoop() == L && Expr->isAffine()) |
| 3821 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); |
| 3822 | Valid = false; |
| 3823 | return Expr; |
| 3824 | } |
| 3825 | bool isValid() { return Valid; } |
| 3826 | |
| 3827 | private: |
| 3828 | const Loop *L; |
| 3829 | bool Valid; |
| 3830 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3831 | } // end anonymous namespace |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3832 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 3833 | SCEV::NoWrapFlags |
| 3834 | ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { |
| 3835 | if (!AR->isAffine()) |
| 3836 | return SCEV::FlagAnyWrap; |
| 3837 | |
| 3838 | typedef OverflowingBinaryOperator OBO; |
| 3839 | SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; |
| 3840 | |
| 3841 | if (!AR->hasNoSignedWrap()) { |
| 3842 | ConstantRange AddRecRange = getSignedRange(AR); |
| 3843 | ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); |
| 3844 | |
| 3845 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3846 | Instruction::Add, IncRange, OBO::NoSignedWrap); |
| 3847 | if (NSWRegion.contains(AddRecRange)) |
| 3848 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); |
| 3849 | } |
| 3850 | |
| 3851 | if (!AR->hasNoUnsignedWrap()) { |
| 3852 | ConstantRange AddRecRange = getUnsignedRange(AR); |
| 3853 | ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); |
| 3854 | |
| 3855 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3856 | Instruction::Add, IncRange, OBO::NoUnsignedWrap); |
| 3857 | if (NUWRegion.contains(AddRecRange)) |
| 3858 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); |
| 3859 | } |
| 3860 | |
| 3861 | return Result; |
| 3862 | } |
| 3863 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3864 | namespace { |
| 3865 | /// Represents an abstract binary operation. This may exist as a |
| 3866 | /// normal instruction or constant expression, or may have been |
| 3867 | /// derived from an expression tree. |
| 3868 | struct BinaryOp { |
| 3869 | unsigned Opcode; |
| 3870 | Value *LHS; |
| 3871 | Value *RHS; |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3872 | bool IsNSW; |
| 3873 | bool IsNUW; |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3874 | |
| 3875 | /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or |
| 3876 | /// constant expression. |
| 3877 | Operator *Op; |
| 3878 | |
| 3879 | explicit BinaryOp(Operator *Op) |
| 3880 | : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3881 | IsNSW(false), IsNUW(false), Op(Op) { |
| 3882 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { |
| 3883 | IsNSW = OBO->hasNoSignedWrap(); |
| 3884 | IsNUW = OBO->hasNoUnsignedWrap(); |
| 3885 | } |
| 3886 | } |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3887 | |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3888 | explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, |
| 3889 | bool IsNUW = false) |
| 3890 | : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), |
| 3891 | Op(nullptr) {} |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3892 | }; |
| 3893 | } |
| 3894 | |
| 3895 | |
| 3896 | /// Try to map \p V into a BinaryOp, and return \c None on failure. |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 3897 | static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3898 | auto *Op = dyn_cast<Operator>(V); |
| 3899 | if (!Op) |
| 3900 | return None; |
| 3901 | |
| 3902 | // Implementation detail: all the cleverness here should happen without |
| 3903 | // creating new SCEV expressions -- our caller knowns tricks to avoid creating |
| 3904 | // SCEV expressions when possible, and we should not break that. |
| 3905 | |
| 3906 | switch (Op->getOpcode()) { |
| 3907 | case Instruction::Add: |
| 3908 | case Instruction::Sub: |
| 3909 | case Instruction::Mul: |
| 3910 | case Instruction::UDiv: |
| 3911 | case Instruction::And: |
| 3912 | case Instruction::Or: |
| 3913 | case Instruction::AShr: |
| 3914 | case Instruction::Shl: |
| 3915 | return BinaryOp(Op); |
| 3916 | |
| 3917 | case Instruction::Xor: |
| 3918 | if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) |
| 3919 | // If the RHS of the xor is a signbit, then this is just an add. |
| 3920 | // Instcombine turns add of signbit into xor as a strength reduction step. |
| 3921 | if (RHSC->getValue().isSignBit()) |
| 3922 | return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); |
| 3923 | return BinaryOp(Op); |
| 3924 | |
| 3925 | case Instruction::LShr: |
| 3926 | // Turn logical shift right of a constant into a unsigned divide. |
| 3927 | if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { |
| 3928 | uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); |
| 3929 | |
| 3930 | // If the shift count is not less than the bitwidth, the result of |
| 3931 | // the shift is undefined. Don't try to analyze it, because the |
| 3932 | // resolution chosen here may differ from the resolution chosen in |
| 3933 | // other parts of the compiler. |
| 3934 | if (SA->getValue().ult(BitWidth)) { |
| 3935 | Constant *X = |
| 3936 | ConstantInt::get(SA->getContext(), |
| 3937 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
| 3938 | return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); |
| 3939 | } |
| 3940 | } |
| 3941 | return BinaryOp(Op); |
| 3942 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 3943 | case Instruction::ExtractValue: { |
| 3944 | auto *EVI = cast<ExtractValueInst>(Op); |
| 3945 | if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) |
| 3946 | break; |
| 3947 | |
| 3948 | auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); |
| 3949 | if (!CI) |
| 3950 | break; |
| 3951 | |
| 3952 | if (auto *F = CI->getCalledFunction()) |
| 3953 | switch (F->getIntrinsicID()) { |
| 3954 | case Intrinsic::sadd_with_overflow: |
| 3955 | case Intrinsic::uadd_with_overflow: { |
| 3956 | if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) |
| 3957 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3958 | CI->getArgOperand(1)); |
| 3959 | |
| 3960 | // Now that we know that all uses of the arithmetic-result component of |
| 3961 | // CI are guarded by the overflow check, we can go ahead and pretend |
| 3962 | // that the arithmetic is non-overflowing. |
| 3963 | if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) |
| 3964 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3965 | CI->getArgOperand(1), /* IsNSW = */ true, |
| 3966 | /* IsNUW = */ false); |
| 3967 | else |
| 3968 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3969 | CI->getArgOperand(1), /* IsNSW = */ false, |
| 3970 | /* IsNUW*/ true); |
| 3971 | } |
| 3972 | |
| 3973 | case Intrinsic::ssub_with_overflow: |
| 3974 | case Intrinsic::usub_with_overflow: |
| 3975 | return BinaryOp(Instruction::Sub, CI->getArgOperand(0), |
| 3976 | CI->getArgOperand(1)); |
| 3977 | |
| 3978 | case Intrinsic::smul_with_overflow: |
| 3979 | case Intrinsic::umul_with_overflow: |
| 3980 | return BinaryOp(Instruction::Mul, CI->getArgOperand(0), |
| 3981 | CI->getArgOperand(1)); |
| 3982 | default: |
| 3983 | break; |
| 3984 | } |
| 3985 | } |
| 3986 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3987 | default: |
| 3988 | break; |
| 3989 | } |
| 3990 | |
| 3991 | return None; |
| 3992 | } |
| 3993 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3994 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { |
| 3995 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 3996 | if (!L || L->getHeader() != PN->getParent()) |
| 3997 | return nullptr; |
| 3998 | |
| 3999 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 4000 | // this phi as an addrec if it has a unique entry value and a unique |
| 4001 | // backedge value. |
| 4002 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
| 4003 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 4004 | Value *V = PN->getIncomingValue(i); |
| 4005 | if (L->contains(PN->getIncomingBlock(i))) { |
| 4006 | if (!BEValueV) { |
| 4007 | BEValueV = V; |
| 4008 | } else if (BEValueV != V) { |
| 4009 | BEValueV = nullptr; |
| 4010 | break; |
| 4011 | } |
| 4012 | } else if (!StartValueV) { |
| 4013 | StartValueV = V; |
| 4014 | } else if (StartValueV != V) { |
| 4015 | StartValueV = nullptr; |
| 4016 | break; |
| 4017 | } |
| 4018 | } |
| 4019 | if (BEValueV && StartValueV) { |
| 4020 | // While we are analyzing this PHI node, handle its value symbolically. |
| 4021 | const SCEV *SymbolicName = getUnknown(PN); |
| 4022 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
| 4023 | "PHI node already processed?"); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 4024 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4025 | |
| 4026 | // Using this symbolic name for the PHI, analyze the value coming around |
| 4027 | // the back-edge. |
| 4028 | const SCEV *BEValue = getSCEV(BEValueV); |
| 4029 | |
| 4030 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 4031 | // has a special value for the first iteration of the loop. |
| 4032 | |
| 4033 | // If the value coming around the backedge is an add with the symbolic |
| 4034 | // value we just inserted, then we found a simple induction variable! |
| 4035 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 4036 | // If there is a single occurrence of the symbolic value, replace it |
| 4037 | // with a recurrence. |
| 4038 | unsigned FoundIndex = Add->getNumOperands(); |
| 4039 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 4040 | if (Add->getOperand(i) == SymbolicName) |
| 4041 | if (FoundIndex == e) { |
| 4042 | FoundIndex = i; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4043 | break; |
| 4044 | } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4045 | |
| 4046 | if (FoundIndex != Add->getNumOperands()) { |
| 4047 | // Create an add with everything but the specified operand. |
| 4048 | SmallVector<const SCEV *, 8> Ops; |
| 4049 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 4050 | if (i != FoundIndex) |
| 4051 | Ops.push_back(Add->getOperand(i)); |
| 4052 | const SCEV *Accum = getAddExpr(Ops); |
| 4053 | |
| 4054 | // This is not a valid addrec if the step amount is varying each |
| 4055 | // loop iteration, but is not itself an addrec in this loop. |
| 4056 | if (isLoopInvariant(Accum, L) || |
| 4057 | (isa<SCEVAddRecExpr>(Accum) && |
| 4058 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 4059 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4060 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 4061 | if (auto BO = MatchBinaryOp(BEValueV, DT)) { |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 4062 | if (BO->Opcode == Instruction::Add && BO->LHS == PN) { |
| 4063 | if (BO->IsNUW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4064 | Flags = setFlags(Flags, SCEV::FlagNUW); |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 4065 | if (BO->IsNSW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4066 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 4067 | } |
| 4068 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
| 4069 | // If the increment is an inbounds GEP, then we know the address |
| 4070 | // space cannot be wrapped around. We cannot make any guarantee |
| 4071 | // about signed or unsigned overflow because pointers are |
| 4072 | // unsigned but we may have a negative index from the base |
| 4073 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 4074 | // indices form a positive value. |
| 4075 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
| 4076 | Flags = setFlags(Flags, SCEV::FlagNW); |
| 4077 | |
| 4078 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 4079 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 4080 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 4081 | } |
| 4082 | |
| 4083 | // We cannot transfer nuw and nsw flags from subtraction |
| 4084 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 4085 | // for instance. |
| 4086 | } |
| 4087 | |
| 4088 | const SCEV *StartVal = getSCEV(StartValueV); |
| 4089 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
| 4090 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4091 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4092 | // to be symbolic. We now need to go back and purge all of the |
| 4093 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4094 | forgetSymbolicName(PN, SymbolicName); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4095 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4096 | |
| 4097 | // We can add Flags to the post-inc expression only if we |
| 4098 | // know that it us *undefined behavior* for BEValueV to |
| 4099 | // overflow. |
| 4100 | if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) |
| 4101 | if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) |
| 4102 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); |
| 4103 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4104 | return PHISCEV; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4105 | } |
| 4106 | } |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4107 | } else { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4108 | // Otherwise, this could be a loop like this: |
| 4109 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 4110 | // In this case, j = {1,+,1} and BEValue is j. |
| 4111 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 4112 | // i really is an addrec evolution. |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4113 | // |
| 4114 | // We can generalize this saying that i is the shifted value of BEValue |
| 4115 | // by one iteration: |
| 4116 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) |
| 4117 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); |
| 4118 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); |
| 4119 | if (Shifted != getCouldNotCompute() && |
| 4120 | Start != getCouldNotCompute()) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4121 | const SCEV *StartVal = getSCEV(StartValueV); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4122 | if (Start == StartVal) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4123 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4124 | // to be symbolic. We now need to go back and purge all of the |
| 4125 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4126 | forgetSymbolicName(PN, SymbolicName); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4127 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; |
| 4128 | return Shifted; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4129 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4130 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4131 | } |
Tobias Grosser | 934fcf4 | 2016-02-21 18:50:09 +0000 | [diff] [blame] | 4132 | |
| 4133 | // Remove the temporary PHI node SCEV that has been inserted while intending |
| 4134 | // to create an AddRecExpr for this PHI node. We can not keep this temporary |
| 4135 | // as it will prevent later (possibly simpler) SCEV expressions to be added |
| 4136 | // to the ValueExprMap. |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 4137 | eraseValueFromMap(PN); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4138 | } |
| 4139 | |
| 4140 | return nullptr; |
| 4141 | } |
| 4142 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4143 | // Checks if the SCEV S is available at BB. S is considered available at BB |
| 4144 | // if S can be materialized at BB without introducing a fault. |
| 4145 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, |
| 4146 | BasicBlock *BB) { |
| 4147 | struct CheckAvailable { |
| 4148 | bool TraversalDone = false; |
| 4149 | bool Available = true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4150 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4151 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) |
| 4152 | BasicBlock *BB = nullptr; |
| 4153 | DominatorTree &DT; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4154 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4155 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) |
| 4156 | : L(L), BB(BB), DT(DT) {} |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4157 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4158 | bool setUnavailable() { |
| 4159 | TraversalDone = true; |
| 4160 | Available = false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4161 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4162 | } |
| 4163 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4164 | bool follow(const SCEV *S) { |
| 4165 | switch (S->getSCEVType()) { |
| 4166 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: |
| 4167 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: |
Sanjoy Das | bb5ffc5 | 2015-10-24 05:37:28 +0000 | [diff] [blame] | 4168 | // These expressions are available if their operand(s) is/are. |
| 4169 | return true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4170 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4171 | case scAddRecExpr: { |
| 4172 | // We allow add recurrences that are on the loop BB is in, or some |
| 4173 | // outer loop. This guarantees availability because the value of the |
| 4174 | // add recurrence at BB is simply the "current" value of the induction |
| 4175 | // variable. We can relax this in the future; for instance an add |
| 4176 | // recurrence on a sibling dominating loop is also available at BB. |
| 4177 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); |
| 4178 | if (L && (ARLoop == L || ARLoop->contains(L))) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4179 | return true; |
| 4180 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4181 | return setUnavailable(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4182 | } |
| 4183 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4184 | case scUnknown: { |
| 4185 | // For SCEVUnknown, we check for simple dominance. |
| 4186 | const auto *SU = cast<SCEVUnknown>(S); |
| 4187 | Value *V = SU->getValue(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4188 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4189 | if (isa<Argument>(V)) |
| 4190 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4191 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4192 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) |
| 4193 | return false; |
| 4194 | |
| 4195 | return setUnavailable(); |
| 4196 | } |
| 4197 | |
| 4198 | case scUDivExpr: |
| 4199 | case scCouldNotCompute: |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 4200 | // We do not try to smart about these at all. |
| 4201 | return setUnavailable(); |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4202 | } |
| 4203 | llvm_unreachable("switch should be fully covered!"); |
| 4204 | } |
| 4205 | |
| 4206 | bool isDone() { return TraversalDone; } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4207 | }; |
| 4208 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4209 | CheckAvailable CA(L, BB, DT); |
| 4210 | SCEVTraversal<CheckAvailable> ST(CA); |
| 4211 | |
| 4212 | ST.visitAll(S); |
| 4213 | return CA.Available; |
| 4214 | } |
| 4215 | |
| 4216 | // Try to match a control flow sequence that branches out at BI and merges back |
| 4217 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful |
| 4218 | // match. |
| 4219 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, |
| 4220 | Value *&C, Value *&LHS, Value *&RHS) { |
| 4221 | C = BI->getCondition(); |
| 4222 | |
| 4223 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); |
| 4224 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); |
| 4225 | |
| 4226 | if (!LeftEdge.isSingleEdge()) |
| 4227 | return false; |
| 4228 | |
| 4229 | assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); |
| 4230 | |
| 4231 | Use &LeftUse = Merge->getOperandUse(0); |
| 4232 | Use &RightUse = Merge->getOperandUse(1); |
| 4233 | |
| 4234 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { |
| 4235 | LHS = LeftUse; |
| 4236 | RHS = RightUse; |
| 4237 | return true; |
| 4238 | } |
| 4239 | |
| 4240 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { |
| 4241 | LHS = RightUse; |
| 4242 | RHS = LeftUse; |
| 4243 | return true; |
| 4244 | } |
| 4245 | |
| 4246 | return false; |
| 4247 | } |
| 4248 | |
| 4249 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { |
Sanjoy Das | b0b4e86 | 2016-08-05 18:34:14 +0000 | [diff] [blame] | 4250 | auto IsReachable = |
| 4251 | [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; |
| 4252 | if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4253 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 4254 | |
Sanjoy Das | 337d478 | 2015-10-31 23:21:40 +0000 | [diff] [blame] | 4255 | // We don't want to break LCSSA, even in a SCEV expression tree. |
| 4256 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 4257 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) |
| 4258 | return nullptr; |
| 4259 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4260 | // Try to match |
| 4261 | // |
| 4262 | // br %cond, label %left, label %right |
| 4263 | // left: |
| 4264 | // br label %merge |
| 4265 | // right: |
| 4266 | // br label %merge |
| 4267 | // merge: |
| 4268 | // V = phi [ %x, %left ], [ %y, %right ] |
| 4269 | // |
| 4270 | // as "select %cond, %x, %y" |
| 4271 | |
| 4272 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); |
| 4273 | assert(IDom && "At least the entry block should dominate PN"); |
| 4274 | |
| 4275 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); |
| 4276 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; |
| 4277 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4278 | if (BI && BI->isConditional() && |
| 4279 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && |
| 4280 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && |
| 4281 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4282 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); |
| 4283 | } |
| 4284 | |
| 4285 | return nullptr; |
| 4286 | } |
| 4287 | |
| 4288 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
| 4289 | if (const SCEV *S = createAddRecFromPHI(PN)) |
| 4290 | return S; |
| 4291 | |
| 4292 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) |
| 4293 | return S; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 4294 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4295 | // If the PHI has a single incoming value, follow that value, unless the |
| 4296 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 4297 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 4298 | // it doesn't have DominatorTree information, so it may miss cases. |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4299 | if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4300 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4301 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 4302 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4303 | // 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] | 4304 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4305 | } |
| 4306 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4307 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, |
| 4308 | Value *Cond, |
| 4309 | Value *TrueVal, |
| 4310 | Value *FalseVal) { |
Mehdi Amini | 044cb34 | 2015-10-07 18:14:25 +0000 | [diff] [blame] | 4311 | // Handle "constant" branch or select. This can occur for instance when a |
| 4312 | // loop pass transforms an inner loop and moves on to process the outer loop. |
| 4313 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) |
| 4314 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); |
| 4315 | |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4316 | // Try to match some simple smax or umax patterns. |
| 4317 | auto *ICI = dyn_cast<ICmpInst>(Cond); |
| 4318 | if (!ICI) |
| 4319 | return getUnknown(I); |
| 4320 | |
| 4321 | Value *LHS = ICI->getOperand(0); |
| 4322 | Value *RHS = ICI->getOperand(1); |
| 4323 | |
| 4324 | switch (ICI->getPredicate()) { |
| 4325 | case ICmpInst::ICMP_SLT: |
| 4326 | case ICmpInst::ICMP_SLE: |
| 4327 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4328 | LLVM_FALLTHROUGH; |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4329 | case ICmpInst::ICMP_SGT: |
| 4330 | case ICmpInst::ICMP_SGE: |
| 4331 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4332 | // a >s b ? b+x : a+x -> smin(a, b)+x |
| 4333 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4334 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); |
| 4335 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); |
| 4336 | const SCEV *LA = getSCEV(TrueVal); |
| 4337 | const SCEV *RA = getSCEV(FalseVal); |
| 4338 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4339 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4340 | if (LDiff == RDiff) |
| 4341 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4342 | LDiff = getMinusSCEV(LA, RS); |
| 4343 | RDiff = getMinusSCEV(RA, LS); |
| 4344 | if (LDiff == RDiff) |
| 4345 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4346 | } |
| 4347 | break; |
| 4348 | case ICmpInst::ICMP_ULT: |
| 4349 | case ICmpInst::ICMP_ULE: |
| 4350 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4351 | LLVM_FALLTHROUGH; |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4352 | case ICmpInst::ICMP_UGT: |
| 4353 | case ICmpInst::ICMP_UGE: |
| 4354 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4355 | // a >u b ? b+x : a+x -> umin(a, b)+x |
| 4356 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4357 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4358 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); |
| 4359 | const SCEV *LA = getSCEV(TrueVal); |
| 4360 | const SCEV *RA = getSCEV(FalseVal); |
| 4361 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4362 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4363 | if (LDiff == RDiff) |
| 4364 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4365 | LDiff = getMinusSCEV(LA, RS); |
| 4366 | RDiff = getMinusSCEV(RA, LS); |
| 4367 | if (LDiff == RDiff) |
| 4368 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4369 | } |
| 4370 | break; |
| 4371 | case ICmpInst::ICMP_NE: |
| 4372 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
| 4373 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4374 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4375 | const SCEV *One = getOne(I->getType()); |
| 4376 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4377 | const SCEV *LA = getSCEV(TrueVal); |
| 4378 | const SCEV *RA = getSCEV(FalseVal); |
| 4379 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4380 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4381 | if (LDiff == RDiff) |
| 4382 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4383 | } |
| 4384 | break; |
| 4385 | case ICmpInst::ICMP_EQ: |
| 4386 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
| 4387 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4388 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4389 | const SCEV *One = getOne(I->getType()); |
| 4390 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4391 | const SCEV *LA = getSCEV(TrueVal); |
| 4392 | const SCEV *RA = getSCEV(FalseVal); |
| 4393 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4394 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4395 | if (LDiff == RDiff) |
| 4396 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4397 | } |
| 4398 | break; |
| 4399 | default: |
| 4400 | break; |
| 4401 | } |
| 4402 | |
| 4403 | return getUnknown(I); |
| 4404 | } |
| 4405 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4406 | /// Expand GEP instructions into add and multiply operations. This allows them |
| 4407 | /// to be analyzed by regular SCEV code. |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4408 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4409 | // Don't attempt to analyze GEPs over unsized objects. |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4410 | if (!GEP->getSourceElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4411 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 4412 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 4413 | SmallVector<const SCEV *, 4> IndexExprs; |
| 4414 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 4415 | IndexExprs.push_back(getSCEV(*Index)); |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame] | 4416 | return getGEPExpr(GEP, IndexExprs); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4417 | } |
| 4418 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4419 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4420 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4421 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4422 | return C->getAPInt().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4423 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4424 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4425 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 4426 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4427 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4428 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4429 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4430 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4431 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4432 | } |
| 4433 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4434 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4435 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4436 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4437 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4438 | } |
| 4439 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4440 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4441 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4442 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4443 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4444 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4445 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4446 | } |
| 4447 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4448 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4449 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4450 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 4451 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4452 | for (unsigned i = 1, e = M->getNumOperands(); |
| 4453 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4454 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4455 | BitWidth); |
| 4456 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4457 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4458 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4459 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4460 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4461 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4462 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4463 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4464 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4465 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4466 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4467 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4468 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4469 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4470 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4471 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4472 | return MinOpRes; |
| 4473 | } |
| 4474 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4475 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4476 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4477 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4478 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4479 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4480 | return MinOpRes; |
| 4481 | } |
| 4482 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4483 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 4484 | // For a SCEVUnknown, ask ValueTracking. |
| 4485 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4486 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4487 | computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4488 | nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4489 | return Zeros.countTrailingOnes(); |
| 4490 | } |
| 4491 | |
| 4492 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4493 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4494 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4495 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4496 | /// Helper method to assign a range to V from metadata present in the IR. |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4497 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
Sanjoy Das | a7e1378 | 2015-10-24 05:37:35 +0000 | [diff] [blame] | 4498 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4499 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) |
| 4500 | return getConstantRangeFromMetadata(*MD); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4501 | |
| 4502 | return None; |
| 4503 | } |
| 4504 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4505 | /// Determine the range for a particular SCEV. If SignHint is |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4506 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 4507 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4508 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4509 | ScalarEvolution::getRange(const SCEV *S, |
| 4510 | ScalarEvolution::RangeSignHint SignHint) { |
| 4511 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 4512 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 4513 | : SignedRanges; |
| 4514 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4515 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4516 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 4517 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4518 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4519 | |
| 4520 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4521 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4522 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4523 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 4524 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 4525 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4526 | // If the value has known zeros, the maximum value will have those known zeros |
| 4527 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4528 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4529 | if (TZ != 0) { |
| 4530 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 4531 | ConservativeResult = |
| 4532 | ConstantRange(APInt::getMinValue(BitWidth), |
| 4533 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 4534 | else |
| 4535 | ConservativeResult = ConstantRange( |
| 4536 | APInt::getSignedMinValue(BitWidth), |
| 4537 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 4538 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4539 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4540 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4541 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4542 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4543 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 4544 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4545 | } |
| 4546 | |
| 4547 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4548 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4549 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4550 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 4551 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4552 | } |
| 4553 | |
| 4554 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4555 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4556 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4557 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 4558 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4559 | } |
| 4560 | |
| 4561 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4562 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4563 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4564 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 4565 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4566 | } |
| 4567 | |
| 4568 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4569 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 4570 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 4571 | return setRange(UDiv, SignHint, |
| 4572 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4573 | } |
| 4574 | |
| 4575 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4576 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 4577 | return setRange(ZExt, SignHint, |
| 4578 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4579 | } |
| 4580 | |
| 4581 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4582 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 4583 | return setRange(SExt, SignHint, |
| 4584 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4585 | } |
| 4586 | |
| 4587 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4588 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 4589 | return setRange(Trunc, SignHint, |
| 4590 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4591 | } |
| 4592 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4593 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4594 | // If there's no unsigned wrap, the value will never be less than its |
| 4595 | // initial value. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4596 | if (AddRec->hasNoUnsignedWrap()) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4597 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 4598 | if (!C->getValue()->isZero()) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4599 | ConservativeResult = ConservativeResult.intersectWith( |
| 4600 | ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4601 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4602 | // If there's no signed wrap, and all the operands have the same sign or |
| 4603 | // zero, the value won't ever change sign. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4604 | if (AddRec->hasNoSignedWrap()) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4605 | bool AllNonNeg = true; |
| 4606 | bool AllNonPos = true; |
| 4607 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 4608 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 4609 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4610 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4611 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4612 | ConservativeResult = ConservativeResult.intersectWith( |
| 4613 | ConstantRange(APInt(BitWidth, 0), |
| 4614 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4615 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4616 | ConservativeResult = ConservativeResult.intersectWith( |
| 4617 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4618 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4619 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4620 | |
| 4621 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4622 | if (AddRec->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4623 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4624 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4625 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4626 | auto RangeFromAffine = getRangeForAffineAR( |
| 4627 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4628 | BitWidth); |
| 4629 | if (!RangeFromAffine.isFullSet()) |
| 4630 | ConservativeResult = |
| 4631 | ConservativeResult.intersectWith(RangeFromAffine); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4632 | |
| 4633 | auto RangeFromFactoring = getRangeViaFactoring( |
| 4634 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4635 | BitWidth); |
| 4636 | if (!RangeFromFactoring.isFullSet()) |
| 4637 | ConservativeResult = |
| 4638 | ConservativeResult.intersectWith(RangeFromFactoring); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4639 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4640 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4641 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4642 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4643 | } |
| 4644 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4645 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4646 | // Check if the IR explicitly contains !range metadata. |
| 4647 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4648 | if (MDRange.hasValue()) |
| 4649 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4650 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4651 | // Split here to avoid paying the compile-time cost of calling both |
| 4652 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4653 | // if needed. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4654 | const DataLayout &DL = getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4655 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4656 | // For a SCEVUnknown, ask ValueTracking. |
| 4657 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4658 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4659 | if (Ones != ~Zeros + 1) |
| 4660 | ConservativeResult = |
| 4661 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4662 | } else { |
| 4663 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4664 | "generalize as needed!"); |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4665 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4666 | if (NS > 1) |
| 4667 | ConservativeResult = ConservativeResult.intersectWith( |
| 4668 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4669 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4670 | } |
| 4671 | |
| 4672 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4673 | } |
| 4674 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4675 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4676 | } |
| 4677 | |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4678 | ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, |
| 4679 | const SCEV *Step, |
| 4680 | const SCEV *MaxBECount, |
| 4681 | unsigned BitWidth) { |
| 4682 | assert(!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4683 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && |
| 4684 | "Precondition!"); |
| 4685 | |
| 4686 | ConstantRange Result(BitWidth, /* isFullSet = */ true); |
| 4687 | |
| 4688 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4689 | // because we could be called from within the ScalarEvolution overflow |
| 4690 | // checking code. |
| 4691 | |
| 4692 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); |
| 4693 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
Michael Zolotukhin | e909a6e | 2016-12-20 23:03:42 +0000 | [diff] [blame] | 4694 | ConstantRange ZExtMaxBECountRange = MaxBECountRange.zextOrTrunc(BitWidth * 2); |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4695 | |
| 4696 | ConstantRange StepSRange = getSignedRange(Step); |
Michael Zolotukhin | e909a6e | 2016-12-20 23:03:42 +0000 | [diff] [blame] | 4697 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2); |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4698 | |
| 4699 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4700 | ConstantRange EndURange = |
| 4701 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
| 4702 | |
| 4703 | // Check for unsigned overflow. |
Michael Zolotukhin | e909a6e | 2016-12-20 23:03:42 +0000 | [diff] [blame] | 4704 | ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2); |
| 4705 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2); |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4706 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4707 | ZExtEndURange) { |
| 4708 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4709 | EndURange.getUnsignedMin()); |
| 4710 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4711 | EndURange.getUnsignedMax()); |
| 4712 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4713 | if (!IsFullRange) |
| 4714 | Result = |
| 4715 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4716 | } |
| 4717 | |
| 4718 | ConstantRange StartSRange = getSignedRange(Start); |
| 4719 | ConstantRange EndSRange = |
| 4720 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4721 | |
| 4722 | // Check for signed overflow. This must be done with ConstantRange |
| 4723 | // arithmetic because we could be called from within the ScalarEvolution |
| 4724 | // overflow checking code. |
Michael Zolotukhin | e909a6e | 2016-12-20 23:03:42 +0000 | [diff] [blame] | 4725 | ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2); |
| 4726 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2); |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4727 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4728 | SExtEndSRange) { |
| 4729 | APInt Min = |
| 4730 | APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); |
| 4731 | APInt Max = |
| 4732 | APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); |
| 4733 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4734 | if (!IsFullRange) |
| 4735 | Result = |
| 4736 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4737 | } |
| 4738 | |
| 4739 | return Result; |
| 4740 | } |
| 4741 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4742 | ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, |
| 4743 | const SCEV *Step, |
| 4744 | const SCEV *MaxBECount, |
| 4745 | unsigned BitWidth) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4746 | // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) |
| 4747 | // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) |
| 4748 | |
| 4749 | struct SelectPattern { |
| 4750 | Value *Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4751 | APInt TrueValue; |
| 4752 | APInt FalseValue; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4753 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4754 | explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, |
| 4755 | const SCEV *S) { |
| 4756 | Optional<unsigned> CastOp; |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4757 | APInt Offset(BitWidth, 0); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4758 | |
| 4759 | assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && |
| 4760 | "Should be!"); |
| 4761 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4762 | // Peel off a constant offset: |
| 4763 | if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { |
| 4764 | // In the future we could consider being smarter here and handle |
| 4765 | // {Start+Step,+,Step} too. |
| 4766 | if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) |
| 4767 | return; |
| 4768 | |
| 4769 | Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); |
| 4770 | S = SA->getOperand(1); |
| 4771 | } |
| 4772 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4773 | // Peel off a cast operation |
| 4774 | if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { |
| 4775 | CastOp = SCast->getSCEVType(); |
| 4776 | S = SCast->getOperand(); |
| 4777 | } |
| 4778 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4779 | using namespace llvm::PatternMatch; |
| 4780 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4781 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 4782 | const APInt *TrueVal, *FalseVal; |
| 4783 | if (!SU || |
| 4784 | !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), |
| 4785 | m_APInt(FalseVal)))) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4786 | Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4787 | return; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4788 | } |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4789 | |
| 4790 | TrueValue = *TrueVal; |
| 4791 | FalseValue = *FalseVal; |
| 4792 | |
| 4793 | // Re-apply the cast we peeled off earlier |
| 4794 | if (CastOp.hasValue()) |
| 4795 | switch (*CastOp) { |
| 4796 | default: |
| 4797 | llvm_unreachable("Unknown SCEV cast type!"); |
| 4798 | |
| 4799 | case scTruncate: |
| 4800 | TrueValue = TrueValue.trunc(BitWidth); |
| 4801 | FalseValue = FalseValue.trunc(BitWidth); |
| 4802 | break; |
| 4803 | case scZeroExtend: |
| 4804 | TrueValue = TrueValue.zext(BitWidth); |
| 4805 | FalseValue = FalseValue.zext(BitWidth); |
| 4806 | break; |
| 4807 | case scSignExtend: |
| 4808 | TrueValue = TrueValue.sext(BitWidth); |
| 4809 | FalseValue = FalseValue.sext(BitWidth); |
| 4810 | break; |
| 4811 | } |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4812 | |
| 4813 | // Re-apply the constant offset we peeled off earlier |
| 4814 | TrueValue += Offset; |
| 4815 | FalseValue += Offset; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4816 | } |
| 4817 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4818 | bool isRecognized() { return Condition != nullptr; } |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4819 | }; |
| 4820 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4821 | SelectPattern StartPattern(*this, BitWidth, Start); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4822 | if (!StartPattern.isRecognized()) |
| 4823 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4824 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4825 | SelectPattern StepPattern(*this, BitWidth, Step); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4826 | if (!StepPattern.isRecognized()) |
| 4827 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4828 | |
| 4829 | if (StartPattern.Condition != StepPattern.Condition) { |
| 4830 | // We don't handle this case today; but we could, by considering four |
| 4831 | // possibilities below instead of two. I'm not sure if there are cases where |
| 4832 | // that will help over what getRange already does, though. |
| 4833 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4834 | } |
| 4835 | |
| 4836 | // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to |
| 4837 | // construct arbitrary general SCEV expressions here. This function is called |
| 4838 | // from deep in the call stack, and calling getSCEV (on a sext instruction, |
| 4839 | // say) can end up caching a suboptimal value. |
| 4840 | |
Sanjoy Das | 6b017a1 | 2016-03-02 02:56:29 +0000 | [diff] [blame] | 4841 | // FIXME: without the explicit `this` receiver below, MSVC errors out with |
| 4842 | // C2352 and C2512 (otherwise it isn't needed). |
| 4843 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4844 | const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4845 | const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4846 | const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4847 | const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); |
Sanjoy Das | 62a1c33 | 2016-03-02 02:15:42 +0000 | [diff] [blame] | 4848 | |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4849 | ConstantRange TrueRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4850 | this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4851 | ConstantRange FalseRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4852 | this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4853 | |
| 4854 | return TrueRange.unionWith(FalseRange); |
| 4855 | } |
| 4856 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4857 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4858 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4859 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4860 | |
| 4861 | // Return early if there are no flags to propagate to the SCEV. |
| 4862 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4863 | if (BinOp->hasNoUnsignedWrap()) |
| 4864 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4865 | if (BinOp->hasNoSignedWrap()) |
| 4866 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4867 | if (Flags == SCEV::FlagAnyWrap) |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4868 | return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4869 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4870 | return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; |
| 4871 | } |
| 4872 | |
| 4873 | bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { |
| 4874 | // Here we check that I is in the header of the innermost loop containing I, |
| 4875 | // since we only deal with instructions in the loop header. The actual loop we |
| 4876 | // need to check later will come from an add recurrence, but getting that |
| 4877 | // requires computing the SCEV of the operands, which can be expensive. This |
| 4878 | // check we can do cheaply to rule out some cases early. |
| 4879 | Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4880 | if (InnermostContainingLoop == nullptr || |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4881 | InnermostContainingLoop->getHeader() != I->getParent()) |
| 4882 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4883 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4884 | // Only proceed if we can prove that I does not yield poison. |
| 4885 | if (!isKnownNotFullPoison(I)) return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4886 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4887 | // At this point we know that if I is executed, then it does not wrap |
| 4888 | // according to at least one of NSW or NUW. If I is not executed, then we do |
| 4889 | // not know if the calculation that I represents would wrap. Multiple |
| 4890 | // instructions can map to the same SCEV. If we apply NSW or NUW from I to |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4891 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4892 | // derived from other instructions that map to the same SCEV. We cannot make |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4893 | // that guarantee for cases where I is not executed. So we need to find the |
| 4894 | // loop that I is considered in relation to and prove that I is executed for |
| 4895 | // every iteration of that loop. That implies that the value that I |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4896 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4897 | // flags to the SCEV. |
| 4898 | // |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4899 | // We check isLoopInvariant to disambiguate in case we are adding recurrences |
| 4900 | // from different loops, so that we know which loop to prove that I is |
| 4901 | // executed in. |
| 4902 | for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { |
Hans Wennborg | 3879035 | 2016-08-17 22:50:18 +0000 | [diff] [blame] | 4903 | // I could be an extractvalue from a call to an overflow intrinsic. |
| 4904 | // TODO: We can do better here in some cases. |
| 4905 | if (!isSCEVable(I->getOperand(OpIndex)->getType())) |
| 4906 | return false; |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4907 | const SCEV *Op = getSCEV(I->getOperand(OpIndex)); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4908 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4909 | bool AllOtherOpsLoopInvariant = true; |
| 4910 | for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); |
| 4911 | ++OtherOpIndex) { |
| 4912 | if (OtherOpIndex != OpIndex) { |
| 4913 | const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); |
| 4914 | if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { |
| 4915 | AllOtherOpsLoopInvariant = false; |
| 4916 | break; |
| 4917 | } |
| 4918 | } |
| 4919 | } |
| 4920 | if (AllOtherOpsLoopInvariant && |
| 4921 | isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) |
| 4922 | return true; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4923 | } |
| 4924 | } |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4925 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4926 | } |
| 4927 | |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4928 | bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { |
| 4929 | // If we know that \c I can never be poison period, then that's enough. |
| 4930 | if (isSCEVExprNeverPoison(I)) |
| 4931 | return true; |
| 4932 | |
| 4933 | // For an add recurrence specifically, we assume that infinite loops without |
| 4934 | // side effects are undefined behavior, and then reason as follows: |
| 4935 | // |
| 4936 | // If the add recurrence is poison in any iteration, it is poison on all |
| 4937 | // future iterations (since incrementing poison yields poison). If the result |
| 4938 | // of the add recurrence is fed into the loop latch condition and the loop |
| 4939 | // does not contain any throws or exiting blocks other than the latch, we now |
| 4940 | // have the ability to "choose" whether the backedge is taken or not (by |
| 4941 | // choosing a sufficiently evil value for the poison feeding into the branch) |
| 4942 | // for every iteration including and after the one in which \p I first became |
| 4943 | // poison. There are two possibilities (let's call the iteration in which \p |
| 4944 | // I first became poison as K): |
| 4945 | // |
| 4946 | // 1. In the set of iterations including and after K, the loop body executes |
| 4947 | // no side effects. In this case executing the backege an infinte number |
| 4948 | // of times will yield undefined behavior. |
| 4949 | // |
| 4950 | // 2. In the set of iterations including and after K, the loop body executes |
| 4951 | // at least one side effect. In this case, that specific instance of side |
| 4952 | // effect is control dependent on poison, which also yields undefined |
| 4953 | // behavior. |
| 4954 | |
| 4955 | auto *ExitingBB = L->getExitingBlock(); |
| 4956 | auto *LatchBB = L->getLoopLatch(); |
| 4957 | if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) |
| 4958 | return false; |
| 4959 | |
| 4960 | SmallPtrSet<const Instruction *, 16> Pushed; |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4961 | SmallVector<const Instruction *, 8> PoisonStack; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4962 | |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4963 | // We start by assuming \c I, the post-inc add recurrence, is poison. Only |
| 4964 | // things that are known to be fully poison under that assumption go on the |
| 4965 | // PoisonStack. |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4966 | Pushed.insert(I); |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4967 | PoisonStack.push_back(I); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4968 | |
| 4969 | bool LatchControlDependentOnPoison = false; |
Sanjoy Das | 2401c98 | 2016-06-08 17:48:46 +0000 | [diff] [blame] | 4970 | while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4971 | const Instruction *Poison = PoisonStack.pop_back_val(); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4972 | |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4973 | for (auto *PoisonUser : Poison->users()) { |
| 4974 | if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { |
| 4975 | if (Pushed.insert(cast<Instruction>(PoisonUser)).second) |
| 4976 | PoisonStack.push_back(cast<Instruction>(PoisonUser)); |
| 4977 | } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4978 | assert(BI->isConditional() && "Only possibility!"); |
| 4979 | if (BI->getParent() == LatchBB) { |
| 4980 | LatchControlDependentOnPoison = true; |
| 4981 | break; |
| 4982 | } |
| 4983 | } |
| 4984 | } |
| 4985 | } |
| 4986 | |
Sanjoy Das | 97cd7d5 | 2016-06-09 01:13:54 +0000 | [diff] [blame] | 4987 | return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); |
| 4988 | } |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4989 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4990 | ScalarEvolution::LoopProperties |
| 4991 | ScalarEvolution::getLoopProperties(const Loop *L) { |
| 4992 | typedef ScalarEvolution::LoopProperties LoopProperties; |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4993 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4994 | auto Itr = LoopPropertiesCache.find(L); |
| 4995 | if (Itr == LoopPropertiesCache.end()) { |
| 4996 | auto HasSideEffects = [](Instruction *I) { |
| 4997 | if (auto *SI = dyn_cast<StoreInst>(I)) |
| 4998 | return !SI->isSimple(); |
| 4999 | |
| 5000 | return I->mayHaveSideEffects(); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 5001 | }; |
| 5002 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 5003 | LoopProperties LP = {/* HasNoAbnormalExits */ true, |
| 5004 | /*HasNoSideEffects*/ true}; |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 5005 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 5006 | for (auto *BB : L->getBlocks()) |
| 5007 | for (auto &I : *BB) { |
| 5008 | if (!isGuaranteedToTransferExecutionToSuccessor(&I)) |
| 5009 | LP.HasNoAbnormalExits = false; |
| 5010 | if (HasSideEffects(&I)) |
| 5011 | LP.HasNoSideEffects = false; |
| 5012 | if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) |
| 5013 | break; // We're already as pessimistic as we can get. |
| 5014 | } |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 5015 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 5016 | auto InsertPair = LoopPropertiesCache.insert({L, LP}); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 5017 | assert(InsertPair.second && "We just checked!"); |
| 5018 | Itr = InsertPair.first; |
| 5019 | } |
| 5020 | |
Sanjoy Das | 97cd7d5 | 2016-06-09 01:13:54 +0000 | [diff] [blame] | 5021 | return Itr->second; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 5022 | } |
| 5023 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5024 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 5025 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5026 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5027 | |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 5028 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 5029 | // Don't attempt to analyze instructions in blocks that aren't |
| 5030 | // reachable. Such instructions don't matter, and they aren't required |
| 5031 | // to obey basic rules for definitions dominating uses which this |
| 5032 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5033 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 5034 | return getUnknown(V); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 5035 | } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 5036 | return getConstant(CI); |
| 5037 | else if (isa<ConstantPointerNull>(V)) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5038 | return getZero(V->getType()); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 5039 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
Sanjoy Das | 5ce3272 | 2016-04-08 00:48:30 +0000 | [diff] [blame] | 5040 | return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 5041 | else if (!isa<ConstantExpr>(V)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5042 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 5043 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 5044 | Operator *U = cast<Operator>(V); |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5045 | if (auto BO = MatchBinaryOp(U, DT)) { |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5046 | switch (BO->Opcode) { |
| 5047 | case Instruction::Add: { |
| 5048 | // The simple thing to do would be to just call getSCEV on both operands |
| 5049 | // and call getAddExpr with the result. However if we're looking at a |
| 5050 | // bunch of things all added together, this can be quite inefficient, |
| 5051 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 5052 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 5053 | // LLVM IR canonical form means we need only traverse the left operands. |
| 5054 | SmallVector<const SCEV *, 4> AddOps; |
| 5055 | do { |
| 5056 | if (BO->Op) { |
| 5057 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 5058 | AddOps.push_back(OpSCEV); |
| 5059 | break; |
| 5060 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 5061 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5062 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 5063 | // addition, then compute the SCEV for this addition by itself |
| 5064 | // with a separate call to getAddExpr. We need to do that |
| 5065 | // instead of pushing the operands of the addition onto AddOps, |
| 5066 | // since the flags are only known to apply to this particular |
| 5067 | // addition - they may not apply to other additions that can be |
| 5068 | // formed with operands from AddOps. |
| 5069 | const SCEV *RHS = getSCEV(BO->RHS); |
| 5070 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5071 | if (Flags != SCEV::FlagAnyWrap) { |
| 5072 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5073 | if (BO->Opcode == Instruction::Sub) |
| 5074 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 5075 | else |
| 5076 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 5077 | break; |
| 5078 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5079 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5080 | |
| 5081 | if (BO->Opcode == Instruction::Sub) |
| 5082 | AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); |
| 5083 | else |
| 5084 | AddOps.push_back(getSCEV(BO->RHS)); |
| 5085 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5086 | auto NewBO = MatchBinaryOp(BO->LHS, DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5087 | if (!NewBO || (NewBO->Opcode != Instruction::Add && |
| 5088 | NewBO->Opcode != Instruction::Sub)) { |
| 5089 | AddOps.push_back(getSCEV(BO->LHS)); |
| 5090 | break; |
| 5091 | } |
| 5092 | BO = NewBO; |
| 5093 | } while (true); |
| 5094 | |
| 5095 | return getAddExpr(AddOps); |
| 5096 | } |
| 5097 | |
| 5098 | case Instruction::Mul: { |
| 5099 | SmallVector<const SCEV *, 4> MulOps; |
| 5100 | do { |
| 5101 | if (BO->Op) { |
| 5102 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 5103 | MulOps.push_back(OpSCEV); |
| 5104 | break; |
| 5105 | } |
| 5106 | |
| 5107 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5108 | if (Flags != SCEV::FlagAnyWrap) { |
| 5109 | MulOps.push_back( |
| 5110 | getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); |
| 5111 | break; |
| 5112 | } |
| 5113 | } |
| 5114 | |
| 5115 | MulOps.push_back(getSCEV(BO->RHS)); |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5116 | auto NewBO = MatchBinaryOp(BO->LHS, DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5117 | if (!NewBO || NewBO->Opcode != Instruction::Mul) { |
| 5118 | MulOps.push_back(getSCEV(BO->LHS)); |
| 5119 | break; |
| 5120 | } |
NAKAMURA Takumi | 940cd93 | 2016-07-04 01:26:21 +0000 | [diff] [blame] | 5121 | BO = NewBO; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5122 | } while (true); |
| 5123 | |
| 5124 | return getMulExpr(MulOps); |
| 5125 | } |
| 5126 | case Instruction::UDiv: |
| 5127 | return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); |
| 5128 | case Instruction::Sub: { |
| 5129 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 5130 | if (BO->Op) |
| 5131 | Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5132 | return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); |
| 5133 | } |
| 5134 | case Instruction::And: |
| 5135 | // For an expression like x&255 that merely masks off the high bits, |
| 5136 | // use zext(trunc(x)) as the SCEV expression. |
| 5137 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5138 | if (CI->isNullValue()) |
| 5139 | return getSCEV(BO->RHS); |
| 5140 | if (CI->isAllOnesValue()) |
| 5141 | return getSCEV(BO->LHS); |
| 5142 | const APInt &A = CI->getValue(); |
| 5143 | |
| 5144 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 5145 | // constants, obscuring what would otherwise be a low-bits mask. |
| 5146 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
| 5147 | // knew about to reconstruct a low-bits mask value. |
| 5148 | unsigned LZ = A.countLeadingZeros(); |
| 5149 | unsigned TZ = A.countTrailingZeros(); |
| 5150 | unsigned BitWidth = A.getBitWidth(); |
| 5151 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 5152 | computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 5153 | 0, &AC, nullptr, &DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5154 | |
| 5155 | APInt EffectiveMask = |
| 5156 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 5157 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
Eli Friedman | f1f49c8 | 2017-01-18 23:56:42 +0000 | [diff] [blame] | 5158 | const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); |
| 5159 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5160 | const SCEV *ShiftedLHS = nullptr; |
| 5161 | if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { |
| 5162 | if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { |
| 5163 | // For an expression like (x * 8) & 8, simplify the multiply. |
| 5164 | unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); |
| 5165 | unsigned GCD = std::min(MulZeros, TZ); |
| 5166 | APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); |
| 5167 | SmallVector<const SCEV*, 4> MulOps; |
| 5168 | MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); |
| 5169 | MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); |
| 5170 | auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); |
| 5171 | ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); |
| 5172 | } |
| 5173 | } |
| 5174 | if (!ShiftedLHS) |
| 5175 | ShiftedLHS = getUDivExpr(LHS, MulCount); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5176 | return getMulExpr( |
| 5177 | getZeroExtendExpr( |
Eli Friedman | f1f49c8 | 2017-01-18 23:56:42 +0000 | [diff] [blame] | 5178 | getTruncateExpr(ShiftedLHS, |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5179 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 5180 | BO->LHS->getType()), |
| 5181 | MulCount); |
| 5182 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5183 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5184 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5185 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5186 | case Instruction::Or: |
| 5187 | // If the RHS of the Or is a constant, we may have something like: |
| 5188 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 5189 | // optimizations will transparently handle this case. |
| 5190 | // |
| 5191 | // In order for this transformation to be safe, the LHS must be of the |
| 5192 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 5193 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5194 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5195 | const APInt &CIVal = CI->getValue(); |
| 5196 | if (GetMinTrailingZeros(LHS) >= |
| 5197 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 5198 | // Build a plain add SCEV. |
| 5199 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 5200 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 5201 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 5202 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 5203 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
| 5204 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 5205 | OldAR->getNoWrapFlags()); |
| 5206 | } |
| 5207 | return S; |
| 5208 | } |
| 5209 | } |
| 5210 | break; |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 5211 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5212 | case Instruction::Xor: |
| 5213 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5214 | // If the RHS of xor is -1, then this is a not operation. |
| 5215 | if (CI->isAllOnesValue()) |
| 5216 | return getNotSCEV(getSCEV(BO->LHS)); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5217 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5218 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 5219 | // This is a variant of the check for xor with -1, and it handles |
| 5220 | // the case where instcombine has trimmed non-demanded bits out |
| 5221 | // of an xor with -1. |
| 5222 | if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) |
| 5223 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) |
| 5224 | if (LBO->getOpcode() == Instruction::And && |
| 5225 | LCI->getValue() == CI->getValue()) |
| 5226 | if (const SCEVZeroExtendExpr *Z = |
| 5227 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { |
| 5228 | Type *UTy = BO->LHS->getType(); |
| 5229 | const SCEV *Z0 = Z->getOperand(); |
| 5230 | Type *Z0Ty = Z0->getType(); |
| 5231 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5232 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5233 | // If C is a low-bits mask, the zero extend is serving to |
| 5234 | // mask off the high bits. Complement the operand and |
| 5235 | // re-apply the zext. |
| 5236 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 5237 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 5238 | |
| 5239 | // If C is a single bit, it may be in the sign-bit position |
| 5240 | // before the zero-extend. In this case, represent the xor |
| 5241 | // using an add, which is equivalent, and re-apply the zext. |
| 5242 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 5243 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
| 5244 | Trunc.isSignBit()) |
| 5245 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 5246 | UTy); |
| 5247 | } |
| 5248 | } |
| 5249 | break; |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5250 | |
| 5251 | case Instruction::Shl: |
| 5252 | // Turn shift left of a constant amount into a multiply. |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5253 | if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5254 | uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5255 | |
| 5256 | // If the shift count is not less than the bitwidth, the result of |
| 5257 | // the shift is undefined. Don't try to analyze it, because the |
| 5258 | // resolution chosen here may differ from the resolution chosen in |
| 5259 | // other parts of the compiler. |
| 5260 | if (SA->getValue().uge(BitWidth)) |
| 5261 | break; |
| 5262 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5263 | // It is currently not resolved how to interpret NSW for left |
| 5264 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 5265 | // case. Remove this check (or this comment) once the situation |
| 5266 | // is resolved. See |
| 5267 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 5268 | // and http://reviews.llvm.org/D8890 . |
| 5269 | auto Flags = SCEV::FlagAnyWrap; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5270 | if (BO->Op && SA->getValue().ult(BitWidth - 1)) |
| 5271 | Flags = getNoWrapFlagsFromUB(BO->Op); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5272 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5273 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 5274 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5275 | return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5276 | } |
| 5277 | break; |
| 5278 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5279 | case Instruction::AShr: |
| 5280 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 5281 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) |
| 5282 | if (Operator *L = dyn_cast<Operator>(BO->LHS)) |
| 5283 | if (L->getOpcode() == Instruction::Shl && |
| 5284 | L->getOperand(1) == BO->RHS) { |
| 5285 | uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5286 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5287 | // If the shift count is not less than the bitwidth, the result of |
| 5288 | // the shift is undefined. Don't try to analyze it, because the |
| 5289 | // resolution chosen here may differ from the resolution chosen in |
| 5290 | // other parts of the compiler. |
| 5291 | if (CI->getValue().uge(BitWidth)) |
| 5292 | break; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5293 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5294 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 5295 | if (Amt == BitWidth) |
| 5296 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
| 5297 | return getSignExtendExpr( |
| 5298 | getTruncateExpr(getSCEV(L->getOperand(0)), |
| 5299 | IntegerType::get(getContext(), Amt)), |
| 5300 | BO->LHS->getType()); |
| 5301 | } |
| 5302 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5303 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5304 | } |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5305 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5306 | switch (U->getOpcode()) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5307 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5308 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5309 | |
| 5310 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5311 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5312 | |
| 5313 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5314 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5315 | |
| 5316 | case Instruction::BitCast: |
| 5317 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 5318 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5319 | return getSCEV(U->getOperand(0)); |
| 5320 | break; |
| 5321 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 5322 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 5323 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 5324 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 5325 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5326 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 5327 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 5328 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5329 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5330 | case Instruction::PHI: |
| 5331 | return createNodeForPHI(cast<PHINode>(U)); |
| 5332 | |
| 5333 | case Instruction::Select: |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 5334 | // U can also be a select constant expr, which let fall through. Since |
| 5335 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and |
| 5336 | // constant expressions cannot have instructions as operands, we'd have |
| 5337 | // returned getUnknown for a select constant expressions anyway. |
| 5338 | if (isa<Instruction>(U)) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 5339 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), |
| 5340 | U->getOperand(1), U->getOperand(2)); |
Hal Finkel | e186deb | 2016-07-11 02:48:23 +0000 | [diff] [blame] | 5341 | break; |
| 5342 | |
| 5343 | case Instruction::Call: |
| 5344 | case Instruction::Invoke: |
| 5345 | if (Value *RV = CallSite(U).getReturnedArgOperand()) |
| 5346 | return getSCEV(RV); |
| 5347 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5348 | } |
| 5349 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5350 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5351 | } |
| 5352 | |
| 5353 | |
| 5354 | |
| 5355 | //===----------------------------------------------------------------------===// |
| 5356 | // Iteration Count Computation Code |
| 5357 | // |
| 5358 | |
Haicheng Wu | 1ef17e9 | 2016-10-12 21:29:38 +0000 | [diff] [blame] | 5359 | static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { |
| 5360 | if (!ExitCount) |
| 5361 | return 0; |
| 5362 | |
| 5363 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 5364 | |
| 5365 | // Guard against huge trip counts. |
| 5366 | if (ExitConst->getValue().getActiveBits() > 32) |
| 5367 | return 0; |
| 5368 | |
| 5369 | // In case of integer overflow, this returns 0, which is correct. |
| 5370 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 5371 | } |
| 5372 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5373 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 5374 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5375 | return getSmallConstantTripCount(L, ExitingBB); |
| 5376 | |
| 5377 | // No trip count information for multiple exits. |
| 5378 | return 0; |
| 5379 | } |
| 5380 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5381 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 5382 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5383 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5384 | assert(L->isLoopExiting(ExitingBlock) && |
| 5385 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5386 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5387 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Haicheng Wu | 1ef17e9 | 2016-10-12 21:29:38 +0000 | [diff] [blame] | 5388 | return getConstantTripCount(ExitCount); |
| 5389 | } |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5390 | |
Haicheng Wu | 1ef17e9 | 2016-10-12 21:29:38 +0000 | [diff] [blame] | 5391 | unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { |
| 5392 | const auto *MaxExitCount = |
| 5393 | dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); |
| 5394 | return getConstantTripCount(MaxExitCount); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5395 | } |
| 5396 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5397 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 5398 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5399 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 5400 | |
| 5401 | // No trip multiple information for multiple exits. |
| 5402 | return 0; |
| 5403 | } |
| 5404 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5405 | /// Returns the largest constant divisor of the trip count of this loop as a |
| 5406 | /// normal unsigned value, if possible. This means that the actual trip count is |
| 5407 | /// always a multiple of the returned value (don't forget the trip count could |
| 5408 | /// very well be zero as well!). |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5409 | /// |
| 5410 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 5411 | /// multiple of a constant (which is also the case if the trip count is simply |
| 5412 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 5413 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5414 | /// |
| 5415 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 5416 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5417 | unsigned |
| 5418 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 5419 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5420 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5421 | assert(L->isLoopExiting(ExitingBlock) && |
| 5422 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5423 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5424 | if (ExitCount == getCouldNotCompute()) |
| 5425 | return 1; |
| 5426 | |
| 5427 | // Get the trip count from the BE count by adding 1. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5428 | const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5429 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 5430 | // to factor simple cases. |
| 5431 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 5432 | TCMul = Mul->getOperand(0); |
| 5433 | |
| 5434 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 5435 | if (!MulC) |
| 5436 | return 1; |
| 5437 | |
| 5438 | ConstantInt *Result = MulC->getValue(); |
| 5439 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 5440 | // Guard against huge trip counts (this requires checking |
| 5441 | // for zero to handle the case where the trip count == -1 and the |
| 5442 | // addition wraps). |
| 5443 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 5444 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5445 | return 1; |
| 5446 | |
| 5447 | return (unsigned)Result->getZExtValue(); |
| 5448 | } |
| 5449 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5450 | /// Get the expression for the number of loop iterations for which this loop is |
| 5451 | /// guaranteed not to exit via ExitingBlock. Otherwise return |
| 5452 | /// SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5453 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 5454 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5455 | } |
| 5456 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5457 | const SCEV * |
| 5458 | ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, |
| 5459 | SCEVUnionPredicate &Preds) { |
| 5460 | return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); |
| 5461 | } |
| 5462 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5463 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5464 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5465 | } |
| 5466 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5467 | /// Similar to getBackedgeTakenCount, except return the least SCEV value that is |
| 5468 | /// known never to be less than the actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5469 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5470 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5471 | } |
| 5472 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5473 | bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { |
| 5474 | return getBackedgeTakenInfo(L).isMaxOrZero(this); |
| 5475 | } |
| 5476 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5477 | /// Push PHI nodes in the header of the given loop onto the given Worklist. |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5478 | static void |
| 5479 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 5480 | BasicBlock *Header = L->getHeader(); |
| 5481 | |
| 5482 | // Push all Loop-header PHIs onto the Worklist stack. |
| 5483 | for (BasicBlock::iterator I = Header->begin(); |
| 5484 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 5485 | Worklist.push_back(PN); |
| 5486 | } |
| 5487 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5488 | const ScalarEvolution::BackedgeTakenInfo & |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5489 | ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { |
| 5490 | auto &BTI = getBackedgeTakenInfo(L); |
| 5491 | if (BTI.hasFullInfo()) |
| 5492 | return BTI; |
| 5493 | |
| 5494 | auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
| 5495 | |
| 5496 | if (!Pair.second) |
| 5497 | return Pair.first->second; |
| 5498 | |
| 5499 | BackedgeTakenInfo Result = |
| 5500 | computeBackedgeTakenCount(L, /*AllowPredicates=*/true); |
| 5501 | |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5502 | return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5503 | } |
| 5504 | |
| 5505 | const ScalarEvolution::BackedgeTakenInfo & |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5506 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5507 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5508 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5509 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 5510 | // code elsewhere that it shouldn't attempt to request a new |
| 5511 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5512 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5513 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5514 | if (!Pair.second) |
| 5515 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5516 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5517 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5518 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 5519 | // must be cleared in this scope. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5520 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5521 | |
| 5522 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 5523 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 5524 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5525 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 5526 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5527 | } |
| 5528 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 5529 | isa<PHINode>(L->getHeader()->begin())) { |
| 5530 | // Only count loops that have phi nodes as not being computable. |
| 5531 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5532 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5533 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5534 | // Now that we know more about the trip count for this loop, forget any |
| 5535 | // existing SCEV values for PHI nodes in this loop since they are only |
| 5536 | // conservative estimates made without the benefit of trip count |
| 5537 | // information. This is similar to the code in forgetLoop, except that |
| 5538 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5539 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5540 | SmallVector<Instruction *, 16> Worklist; |
| 5541 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5542 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5543 | SmallPtrSet<Instruction *, 8> Visited; |
| 5544 | while (!Worklist.empty()) { |
| 5545 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5546 | if (!Visited.insert(I).second) |
| 5547 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5548 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5549 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5550 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5551 | if (It != ValueExprMap.end()) { |
| 5552 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 5553 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5554 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 5555 | // structure, or it's a PHI that's in the progress of being computed |
| 5556 | // by createNodeForPHI. In the former case, additional loop trip |
| 5557 | // count information isn't going to change anything. In the later |
| 5558 | // case, createNodeForPHI will perform the necessary updates on its |
| 5559 | // own when it gets to that point. |
| 5560 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5561 | eraseValueFromMap(It->first); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5562 | forgetMemoizedResults(Old); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5563 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5564 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5565 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5566 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5567 | |
| 5568 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5569 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5570 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5571 | |
| 5572 | // Re-lookup the insert position, since the call to |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5573 | // computeBackedgeTakenCount above could result in a |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5574 | // recusive call to getBackedgeTakenInfo (on a different |
| 5575 | // loop), which would invalidate the iterator computed |
| 5576 | // earlier. |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5577 | return BackedgeTakenCounts.find(L)->second = std::move(Result); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5578 | } |
| 5579 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5580 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 5581 | // Drop any stored trip count value. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5582 | auto RemoveLoopFromBackedgeMap = |
| 5583 | [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 5584 | auto BTCPos = Map.find(L); |
| 5585 | if (BTCPos != Map.end()) { |
| 5586 | BTCPos->second.clear(); |
| 5587 | Map.erase(BTCPos); |
| 5588 | } |
| 5589 | }; |
| 5590 | |
| 5591 | RemoveLoopFromBackedgeMap(BackedgeTakenCounts); |
| 5592 | RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 5593 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5594 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5595 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5596 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5597 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5598 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5599 | while (!Worklist.empty()) { |
| 5600 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5601 | if (!Visited.insert(I).second) |
| 5602 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5603 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5604 | ValueExprMapType::iterator It = |
| 5605 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5606 | if (It != ValueExprMap.end()) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5607 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5608 | forgetMemoizedResults(It->second); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5609 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5610 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5611 | } |
| 5612 | |
| 5613 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5614 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 5615 | |
| 5616 | // Forget all contained loops too, to avoid dangling entries in the |
| 5617 | // ValuesAtScopes map. |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 5618 | for (Loop *I : *L) |
| 5619 | forgetLoop(I); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 5620 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 5621 | LoopPropertiesCache.erase(L); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 5622 | } |
| 5623 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 5624 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5625 | Instruction *I = dyn_cast<Instruction>(V); |
| 5626 | if (!I) return; |
| 5627 | |
| 5628 | // Drop information about expressions based on loop-header PHIs. |
| 5629 | SmallVector<Instruction *, 16> Worklist; |
| 5630 | Worklist.push_back(I); |
| 5631 | |
| 5632 | SmallPtrSet<Instruction *, 8> Visited; |
| 5633 | while (!Worklist.empty()) { |
| 5634 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5635 | if (!Visited.insert(I).second) |
| 5636 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5637 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5638 | ValueExprMapType::iterator It = |
| 5639 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5640 | if (It != ValueExprMap.end()) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5641 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5642 | forgetMemoizedResults(It->second); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5643 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5644 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5645 | } |
| 5646 | |
| 5647 | PushDefUseChildren(I, Worklist); |
| 5648 | } |
| 5649 | } |
| 5650 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5651 | /// Get the exact loop backedge taken count considering all loop exits. A |
| 5652 | /// computable result can only be returned for loops with a single exit. |
| 5653 | /// Returning the minimum taken count among all exits is incorrect because one |
| 5654 | /// of the loop's exit limit's may have been skipped. howFarToZero assumes that |
| 5655 | /// the limit of each loop test is never skipped. This is a valid assumption as |
| 5656 | /// long as the loop exits via that test. For precise results, it is the |
| 5657 | /// caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5658 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5659 | const SCEV * |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5660 | ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, |
| 5661 | SCEVUnionPredicate *Preds) const { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5662 | // If any exits were not computable, the loop is not computable. |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5663 | if (!isComplete() || ExitNotTaken.empty()) |
| 5664 | return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5665 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5666 | const SCEV *BECount = nullptr; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5667 | for (auto &ENT : ExitNotTaken) { |
| 5668 | assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5669 | |
| 5670 | if (!BECount) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5671 | BECount = ENT.ExactNotTaken; |
| 5672 | else if (BECount != ENT.ExactNotTaken) |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5673 | return SE->getCouldNotCompute(); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5674 | if (Preds && !ENT.hasAlwaysTruePredicate()) |
| 5675 | Preds->add(ENT.Predicate.get()); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5676 | |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5677 | assert((Preds || ENT.hasAlwaysTruePredicate()) && |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5678 | "Predicate should be always true!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5679 | } |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5680 | |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 5681 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5682 | return BECount; |
| 5683 | } |
| 5684 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5685 | /// Get the exact not taken count for this loop exit. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5686 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5687 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5688 | ScalarEvolution *SE) const { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5689 | for (auto &ENT : ExitNotTaken) |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5690 | if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5691 | return ENT.ExactNotTaken; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5692 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5693 | return SE->getCouldNotCompute(); |
| 5694 | } |
| 5695 | |
| 5696 | /// getMax - Get the max backedge taken count for the loop. |
| 5697 | const SCEV * |
| 5698 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
Sanjoy Das | 7326861 | 2016-09-26 01:10:22 +0000 | [diff] [blame] | 5699 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { |
| 5700 | return !ENT.hasAlwaysTruePredicate(); |
| 5701 | }; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5702 | |
Sanjoy Das | 7326861 | 2016-09-26 01:10:22 +0000 | [diff] [blame] | 5703 | if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) |
| 5704 | return SE->getCouldNotCompute(); |
| 5705 | |
| 5706 | return getMax(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5707 | } |
| 5708 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5709 | bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { |
| 5710 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { |
| 5711 | return !ENT.hasAlwaysTruePredicate(); |
| 5712 | }; |
| 5713 | return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); |
| 5714 | } |
| 5715 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5716 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 5717 | ScalarEvolution *SE) const { |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5718 | if (getMax() && getMax() != SE->getCouldNotCompute() && |
| 5719 | SE->hasOperand(getMax(), S)) |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5720 | return true; |
| 5721 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5722 | for (auto &ENT : ExitNotTaken) |
| 5723 | if (ENT.ExactNotTaken != SE->getCouldNotCompute() && |
| 5724 | SE->hasOperand(ENT.ExactNotTaken, S)) |
Silviu Baranga | a393baf | 2016-04-06 14:06:32 +0000 | [diff] [blame] | 5725 | return true; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5726 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5727 | return false; |
| 5728 | } |
| 5729 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5730 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 5731 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 5732 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
Sanjoy Das | 5c4869b | 2016-09-26 01:10:27 +0000 | [diff] [blame] | 5733 | SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> |
| 5734 | &&ExitCounts, |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5735 | bool Complete, const SCEV *MaxCount, bool MaxOrZero) |
| 5736 | : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5737 | typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; |
Sanjoy Das | e935c77 | 2016-09-25 23:12:08 +0000 | [diff] [blame] | 5738 | ExitNotTaken.reserve(ExitCounts.size()); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5739 | std::transform( |
| 5740 | ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5741 | [&](const EdgeExitInfo &EEI) { |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5742 | BasicBlock *ExitBB = EEI.first; |
| 5743 | const ExitLimit &EL = EEI.second; |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 5744 | if (EL.Predicates.empty()) |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5745 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 5746 | |
| 5747 | std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); |
| 5748 | for (auto *Pred : EL.Predicates) |
| 5749 | Predicate->add(Pred); |
| 5750 | |
| 5751 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5752 | }); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5753 | } |
| 5754 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5755 | /// Invalidate this result and free the ExitNotTakenInfo array. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5756 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5757 | ExitNotTaken.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5758 | } |
| 5759 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5760 | /// Compute the number of times the backedge of the specified loop will execute. |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5761 | ScalarEvolution::BackedgeTakenInfo |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5762 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L, |
| 5763 | bool AllowPredicates) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5764 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5765 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5766 | |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5767 | typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; |
| 5768 | |
| 5769 | SmallVector<EdgeExitInfo, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5770 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 5771 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5772 | const SCEV *MustExitMaxBECount = nullptr; |
| 5773 | const SCEV *MayExitMaxBECount = nullptr; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5774 | bool MustExitMaxOrZero = false; |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5775 | |
| 5776 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 5777 | // and compute maxBECount. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5778 | // Do a union of all the predicates here. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5779 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5780 | BasicBlock *ExitBB = ExitingBlocks[i]; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5781 | ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); |
| 5782 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 5783 | assert((AllowPredicates || EL.Predicates.empty()) && |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5784 | "Predicated exit limit when predicates are not allowed!"); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5785 | |
| 5786 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 5787 | // CouldComputeBECount is true only if all exits can be computed. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5788 | if (EL.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5789 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 5790 | // 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] | 5791 | CouldComputeBECount = false; |
| 5792 | else |
Sanjoy Das | bdd9710 | 2016-09-25 23:11:55 +0000 | [diff] [blame] | 5793 | ExitCounts.emplace_back(ExitBB, EL); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5794 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5795 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 5796 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 5797 | // LoopMustExits and LoopMayExits. |
| 5798 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5799 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5800 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5801 | // MaxBECount is the minimum EL.MaxNotTaken of computable |
| 5802 | // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum |
| 5803 | // EL.MaxNotTaken, where CouldNotCompute is considered greater than any |
| 5804 | // computable EL.MaxNotTaken. |
| 5805 | if (EL.MaxNotTaken != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5806 | DT.dominates(ExitBB, Latch)) { |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5807 | if (!MustExitMaxBECount) { |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5808 | MustExitMaxBECount = EL.MaxNotTaken; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5809 | MustExitMaxOrZero = EL.MaxOrZero; |
| 5810 | } else { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5811 | MustExitMaxBECount = |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5812 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5813 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5814 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5815 | if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) |
| 5816 | MayExitMaxBECount = EL.MaxNotTaken; |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5817 | else { |
| 5818 | MayExitMaxBECount = |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5819 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5820 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5821 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5822 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5823 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5824 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5825 | // The loop backedge will be taken the maximum or zero times if there's |
| 5826 | // a single exit that must be taken the maximum or zero times. |
| 5827 | bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); |
Sanjoy Das | 5c4869b | 2016-09-26 01:10:27 +0000 | [diff] [blame] | 5828 | return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5829 | MaxBECount, MaxOrZero); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5830 | } |
| 5831 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5832 | ScalarEvolution::ExitLimit |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5833 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, |
| 5834 | bool AllowPredicates) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5835 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5836 | // Okay, we've chosen an exiting block. See what condition causes us to exit |
| 5837 | // 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] | 5838 | // lead to the loop header. |
| 5839 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5840 | BasicBlock *Exit = nullptr; |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5841 | for (auto *SBB : successors(ExitingBlock)) |
| 5842 | if (!L->contains(SBB)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5843 | if (Exit) // Multiple exit successors. |
| 5844 | return getCouldNotCompute(); |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5845 | Exit = SBB; |
| 5846 | } else if (SBB != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5847 | MustExecuteLoopHeader = false; |
| 5848 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5849 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5850 | // At this point, we know we have a conditional branch that determines whether |
| 5851 | // the loop is exited. However, we don't know if the branch is executed each |
| 5852 | // time through the loop. If not, then the execution count of the branch will |
| 5853 | // not be equal to the trip count of the loop. |
| 5854 | // |
| 5855 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5856 | // 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] | 5857 | // 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] | 5858 | // loop header. This is common for un-rotated loops. |
| 5859 | // |
| 5860 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5861 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5862 | // header is reached, the execution count of the branch will be equal to the |
| 5863 | // trip count of the loop. |
| 5864 | // |
| 5865 | // More extensive analysis could be done to handle more cases here. |
| 5866 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5867 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5868 | // The simple checks failed, try climbing the unique predecessor chain |
| 5869 | // up to the header. |
| 5870 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5871 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5872 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5873 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5874 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5875 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5876 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5877 | if (PredSucc == BB) |
| 5878 | continue; |
| 5879 | // If the predecessor has a successor that isn't BB and isn't |
| 5880 | // outside the loop, assume the worst. |
| 5881 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5882 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5883 | } |
| 5884 | if (Pred == L->getHeader()) { |
| 5885 | Ok = true; |
| 5886 | break; |
| 5887 | } |
| 5888 | BB = Pred; |
| 5889 | } |
| 5890 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5891 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5892 | } |
| 5893 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5894 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5895 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5896 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5897 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5898 | // Proceed to the next level to examine the exit condition expression. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5899 | return computeExitLimitFromCond( |
| 5900 | L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), |
| 5901 | /*ControlsExit=*/IsOnlyExit, AllowPredicates); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5902 | } |
| 5903 | |
| 5904 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5905 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5906 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5907 | |
| 5908 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5909 | } |
| 5910 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5911 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5912 | ScalarEvolution::computeExitLimitFromCond(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5913 | Value *ExitCond, |
| 5914 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5915 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5916 | bool ControlsExit, |
| 5917 | bool AllowPredicates) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5918 | // 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] | 5919 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5920 | if (BO->getOpcode() == Instruction::And) { |
| 5921 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5922 | bool EitherMayExit = L->contains(TBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5923 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5924 | ControlsExit && !EitherMayExit, |
| 5925 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5926 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5927 | ControlsExit && !EitherMayExit, |
| 5928 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5929 | const SCEV *BECount = getCouldNotCompute(); |
| 5930 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5931 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5932 | // Both conditions must be true for the loop to continue executing. |
| 5933 | // Choose the less conservative count. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5934 | if (EL0.ExactNotTaken == getCouldNotCompute() || |
| 5935 | EL1.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5936 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5937 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5938 | BECount = |
| 5939 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); |
| 5940 | if (EL0.MaxNotTaken == getCouldNotCompute()) |
| 5941 | MaxBECount = EL1.MaxNotTaken; |
| 5942 | else if (EL1.MaxNotTaken == getCouldNotCompute()) |
| 5943 | MaxBECount = EL0.MaxNotTaken; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5944 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5945 | MaxBECount = |
| 5946 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5947 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5948 | // Both conditions must be true at the same time for the loop to exit. |
| 5949 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5950 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5951 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) |
| 5952 | MaxBECount = EL0.MaxNotTaken; |
| 5953 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) |
| 5954 | BECount = EL0.ExactNotTaken; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5955 | } |
| 5956 | |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5957 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able |
| 5958 | // to be more aggressive when computing BECount than when computing |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5959 | // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and |
| 5960 | // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken |
| 5961 | // to not. |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5962 | if (isa<SCEVCouldNotCompute>(MaxBECount) && |
| 5963 | !isa<SCEVCouldNotCompute>(BECount)) |
| 5964 | MaxBECount = BECount; |
| 5965 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5966 | return ExitLimit(BECount, MaxBECount, false, |
| 5967 | {&EL0.Predicates, &EL1.Predicates}); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5968 | } |
| 5969 | if (BO->getOpcode() == Instruction::Or) { |
| 5970 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5971 | bool EitherMayExit = L->contains(FBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5972 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5973 | ControlsExit && !EitherMayExit, |
| 5974 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5975 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5976 | ControlsExit && !EitherMayExit, |
| 5977 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5978 | const SCEV *BECount = getCouldNotCompute(); |
| 5979 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5980 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5981 | // Both conditions must be false for the loop to continue executing. |
| 5982 | // Choose the less conservative count. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5983 | if (EL0.ExactNotTaken == getCouldNotCompute() || |
| 5984 | EL1.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5985 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5986 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5987 | BECount = |
| 5988 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); |
| 5989 | if (EL0.MaxNotTaken == getCouldNotCompute()) |
| 5990 | MaxBECount = EL1.MaxNotTaken; |
| 5991 | else if (EL1.MaxNotTaken == getCouldNotCompute()) |
| 5992 | MaxBECount = EL0.MaxNotTaken; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5993 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5994 | MaxBECount = |
| 5995 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5996 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5997 | // Both conditions must be false at the same time for the loop to exit. |
| 5998 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5999 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 6000 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) |
| 6001 | MaxBECount = EL0.MaxNotTaken; |
| 6002 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) |
| 6003 | BECount = EL0.ExactNotTaken; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 6004 | } |
| 6005 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 6006 | return ExitLimit(BECount, MaxBECount, false, |
| 6007 | {&EL0.Predicates, &EL1.Predicates}); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 6008 | } |
| 6009 | } |
| 6010 | |
| 6011 | // 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] | 6012 | // Proceed to the next level to examine the icmp. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6013 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { |
| 6014 | ExitLimit EL = |
| 6015 | computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
| 6016 | if (EL.hasFullInfo() || !AllowPredicates) |
| 6017 | return EL; |
| 6018 | |
| 6019 | // Try again, but use SCEV predicates this time. |
| 6020 | return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, |
| 6021 | /*AllowPredicates=*/true); |
| 6022 | } |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6023 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 6024 | // Check for a constant condition. These are normally stripped out by |
| 6025 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 6026 | // preserve the CFG and is temporarily leaving constant conditions |
| 6027 | // in place. |
| 6028 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 6029 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 6030 | // The backedge is always taken. |
| 6031 | return getCouldNotCompute(); |
| 6032 | else |
| 6033 | // The backedge is never taken. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 6034 | return getZero(CI->getType()); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 6035 | } |
| 6036 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6037 | // 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] | 6038 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 6039 | } |
| 6040 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6041 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6042 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6043 | ICmpInst *ExitCond, |
| 6044 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 6045 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6046 | bool ControlsExit, |
| 6047 | bool AllowPredicates) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6048 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6049 | // If the condition was exit on true, convert the condition to exit on false |
| 6050 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 6051 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6052 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6053 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6054 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6055 | |
| 6056 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 6057 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 6058 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6059 | ExitLimit ItCnt = |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6060 | computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 6061 | if (ItCnt.hasAnyInfo()) |
| 6062 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6063 | } |
| 6064 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6065 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 6066 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6067 | |
| 6068 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6069 | LHS = getSCEVAtScope(LHS, L); |
| 6070 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6071 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6072 | // 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] | 6073 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 6074 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 6075 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6076 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6077 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6078 | } |
| 6079 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6080 | // Simplify the operands before analyzing them. |
| 6081 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 6082 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6083 | // If we have a comparison of a chrec against a constant, try to use value |
| 6084 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6085 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 6086 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6087 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6088 | // Form the constant range. |
Sanjoy Das | 1f7b813 | 2016-10-02 00:09:57 +0000 | [diff] [blame] | 6089 | ConstantRange CompRange = |
| 6090 | ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6091 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6092 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6093 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6094 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6095 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6096 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6097 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6098 | // Convert to: while (X-Y != 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6099 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6100 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6101 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6102 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6103 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 6104 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 6105 | // Convert to: while (X-Y == 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6106 | ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6107 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6108 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6109 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 6110 | case ICmpInst::ICMP_SLT: |
| 6111 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 6112 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6113 | ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6114 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6115 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 6116 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6117 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 6118 | case ICmpInst::ICMP_SGT: |
| 6119 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 6120 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6121 | ExitLimit EL = |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6122 | howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6123 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6124 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 6125 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6126 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6127 | default: |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 6128 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6129 | } |
Sanjoy Das | 0da2d14 | 2016-06-30 02:47:28 +0000 | [diff] [blame] | 6130 | |
| 6131 | auto *ExhaustiveCount = |
| 6132 | computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
| 6133 | |
| 6134 | if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) |
| 6135 | return ExhaustiveCount; |
| 6136 | |
| 6137 | return computeShiftCompareExitLimit(ExitCond->getOperand(0), |
| 6138 | ExitCond->getOperand(1), L, Cond); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6139 | } |
| 6140 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6141 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6142 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6143 | SwitchInst *Switch, |
| 6144 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6145 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6146 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 6147 | |
| 6148 | // Give up if the exit is the default dest of a switch. |
| 6149 | if (Switch->getDefaultDest() == ExitingBlock) |
| 6150 | return getCouldNotCompute(); |
| 6151 | |
| 6152 | assert(L->contains(Switch->getDefaultDest()) && |
| 6153 | "Default case must not exit the loop!"); |
| 6154 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 6155 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 6156 | |
| 6157 | // while (X != Y) --> while (X-Y != 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6158 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6159 | if (EL.hasAnyInfo()) |
| 6160 | return EL; |
| 6161 | |
| 6162 | return getCouldNotCompute(); |
| 6163 | } |
| 6164 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6165 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6166 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 6167 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6168 | const SCEV *InVal = SE.getConstant(C); |
| 6169 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6170 | assert(isa<SCEVConstant>(Val) && |
| 6171 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 6172 | return cast<SCEVConstant>(Val)->getValue(); |
| 6173 | } |
| 6174 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6175 | /// Given an exit condition of 'icmp op load X, cst', try to see if we can |
| 6176 | /// compute the backedge execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6177 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6178 | ScalarEvolution::computeLoadConstantCompareExitLimit( |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6179 | LoadInst *LI, |
| 6180 | Constant *RHS, |
| 6181 | const Loop *L, |
| 6182 | ICmpInst::Predicate predicate) { |
| 6183 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6184 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6185 | |
| 6186 | // 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] | 6187 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6188 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6189 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6190 | |
| 6191 | // Make sure that it is really a constant global we are gepping, with an |
| 6192 | // initializer, and make sure the first IDX is really 0. |
| 6193 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 6194 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6195 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 6196 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6197 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6198 | |
| 6199 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6200 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6201 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6202 | unsigned VarIdxNum = 0; |
| 6203 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 6204 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 6205 | Indexes.push_back(CI); |
| 6206 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6207 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6208 | VarIdx = GEP->getOperand(i); |
| 6209 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6210 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6211 | } |
| 6212 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 6213 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 6214 | if (!VarIdx) |
| 6215 | return getCouldNotCompute(); |
| 6216 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6217 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 6218 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6219 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6220 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6221 | |
| 6222 | // We can only recognize very limited forms of loop index expressions, in |
| 6223 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6224 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 6225 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6226 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 6227 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6228 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6229 | |
| 6230 | unsigned MaxSteps = MaxBruteForceIterations; |
| 6231 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6232 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 6233 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6234 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6235 | |
| 6236 | // Form the GEP offset. |
| 6237 | Indexes[VarIdxNum] = Val; |
| 6238 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6239 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 6240 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6241 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6242 | |
| 6243 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6244 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6245 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6246 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6247 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6248 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6249 | } |
| 6250 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6251 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6252 | } |
| 6253 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6254 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( |
| 6255 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { |
| 6256 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); |
| 6257 | if (!RHS) |
| 6258 | return getCouldNotCompute(); |
| 6259 | |
| 6260 | const BasicBlock *Latch = L->getLoopLatch(); |
| 6261 | if (!Latch) |
| 6262 | return getCouldNotCompute(); |
| 6263 | |
| 6264 | const BasicBlock *Predecessor = L->getLoopPredecessor(); |
| 6265 | if (!Predecessor) |
| 6266 | return getCouldNotCompute(); |
| 6267 | |
| 6268 | // Return true if V is of the form "LHS `shift_op` <positive constant>". |
| 6269 | // Return LHS in OutLHS and shift_opt in OutOpCode. |
| 6270 | auto MatchPositiveShift = |
| 6271 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { |
| 6272 | |
| 6273 | using namespace PatternMatch; |
| 6274 | |
| 6275 | ConstantInt *ShiftAmt; |
| 6276 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6277 | OutOpCode = Instruction::LShr; |
| 6278 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6279 | OutOpCode = Instruction::AShr; |
| 6280 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6281 | OutOpCode = Instruction::Shl; |
| 6282 | else |
| 6283 | return false; |
| 6284 | |
| 6285 | return ShiftAmt->getValue().isStrictlyPositive(); |
| 6286 | }; |
| 6287 | |
| 6288 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in |
| 6289 | // |
| 6290 | // loop: |
| 6291 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] |
| 6292 | // %iv.shifted = lshr i32 %iv, <positive constant> |
| 6293 | // |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 6294 | // Return true on a successful match. Return the corresponding PHI node (%iv |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6295 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. |
| 6296 | auto MatchShiftRecurrence = |
| 6297 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { |
| 6298 | Optional<Instruction::BinaryOps> PostShiftOpCode; |
| 6299 | |
| 6300 | { |
| 6301 | Instruction::BinaryOps OpC; |
| 6302 | Value *V; |
| 6303 | |
| 6304 | // If we encounter a shift instruction, "peel off" the shift operation, |
| 6305 | // and remember that we did so. Later when we inspect %iv's backedge |
| 6306 | // value, we will make sure that the backedge value uses the same |
| 6307 | // operation. |
| 6308 | // |
| 6309 | // Note: the peeled shift operation does not have to be the same |
| 6310 | // instruction as the one feeding into the PHI's backedge value. We only |
| 6311 | // really care about it being the same *kind* of shift instruction -- |
| 6312 | // that's all that is required for our later inferences to hold. |
| 6313 | if (MatchPositiveShift(LHS, V, OpC)) { |
| 6314 | PostShiftOpCode = OpC; |
| 6315 | LHS = V; |
| 6316 | } |
| 6317 | } |
| 6318 | |
| 6319 | PNOut = dyn_cast<PHINode>(LHS); |
| 6320 | if (!PNOut || PNOut->getParent() != L->getHeader()) |
| 6321 | return false; |
| 6322 | |
| 6323 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); |
| 6324 | Value *OpLHS; |
| 6325 | |
| 6326 | return |
| 6327 | // The backedge value for the PHI node must be a shift by a positive |
| 6328 | // amount |
| 6329 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && |
| 6330 | |
| 6331 | // of the PHI node itself |
| 6332 | OpLHS == PNOut && |
| 6333 | |
| 6334 | // and the kind of shift should be match the kind of shift we peeled |
| 6335 | // off, if any. |
| 6336 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); |
| 6337 | }; |
| 6338 | |
| 6339 | PHINode *PN; |
| 6340 | Instruction::BinaryOps OpCode; |
| 6341 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) |
| 6342 | return getCouldNotCompute(); |
| 6343 | |
| 6344 | const DataLayout &DL = getDataLayout(); |
| 6345 | |
| 6346 | // The key rationale for this optimization is that for some kinds of shift |
| 6347 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 |
| 6348 | // within a finite number of iterations. If the condition guarding the |
| 6349 | // backedge (in the sense that the backedge is taken if the condition is true) |
| 6350 | // is false for the value the shift recurrence stabilizes to, then we know |
| 6351 | // that the backedge is taken only a finite number of times. |
| 6352 | |
| 6353 | ConstantInt *StableValue = nullptr; |
| 6354 | switch (OpCode) { |
| 6355 | default: |
| 6356 | llvm_unreachable("Impossible case!"); |
| 6357 | |
| 6358 | case Instruction::AShr: { |
| 6359 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most |
| 6360 | // bitwidth(K) iterations. |
| 6361 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); |
| 6362 | bool KnownZero, KnownOne; |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 6363 | ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6364 | Predecessor->getTerminator(), &DT); |
| 6365 | auto *Ty = cast<IntegerType>(RHS->getType()); |
| 6366 | if (KnownZero) |
| 6367 | StableValue = ConstantInt::get(Ty, 0); |
| 6368 | else if (KnownOne) |
| 6369 | StableValue = ConstantInt::get(Ty, -1, true); |
| 6370 | else |
| 6371 | return getCouldNotCompute(); |
| 6372 | |
| 6373 | break; |
| 6374 | } |
| 6375 | case Instruction::LShr: |
| 6376 | case Instruction::Shl: |
| 6377 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} |
| 6378 | // stabilize to 0 in at most bitwidth(K) iterations. |
| 6379 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); |
| 6380 | break; |
| 6381 | } |
| 6382 | |
| 6383 | auto *Result = |
| 6384 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); |
| 6385 | assert(Result->getType()->isIntegerTy(1) && |
| 6386 | "Otherwise cannot be an operand to a branch instruction"); |
| 6387 | |
| 6388 | if (Result->isZeroValue()) { |
| 6389 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 6390 | const SCEV *UpperBound = |
| 6391 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 6392 | return ExitLimit(getCouldNotCompute(), UpperBound, false); |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6393 | } |
| 6394 | |
| 6395 | return getCouldNotCompute(); |
| 6396 | } |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6397 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6398 | /// Return true if we can constant fold an instruction of the specified type, |
| 6399 | /// assuming that all operands were constants. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6400 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 6401 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6402 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 6403 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6404 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6405 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6406 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 6407 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 6408 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6409 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6410 | } |
| 6411 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6412 | /// Determine whether this instruction can constant evolve within this loop |
| 6413 | /// assuming its operands can all constant evolve. |
| 6414 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 6415 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 6416 | if (!L->contains(I)) return false; |
| 6417 | |
| 6418 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 6419 | // We don't currently keep track of the control flow needed to evaluate |
| 6420 | // PHIs, so we cannot handle PHIs inside of loops. |
| 6421 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6422 | } |
| 6423 | |
| 6424 | // If we won't be able to constant fold this expression even if the operands |
| 6425 | // are constants, bail early. |
| 6426 | return CanConstantFold(I); |
| 6427 | } |
| 6428 | |
| 6429 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 6430 | /// recursing through each instruction operand until reaching a loop header phi. |
| 6431 | static PHINode * |
| 6432 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Michael Liao | 468fb74 | 2017-01-13 18:28:30 +0000 | [diff] [blame] | 6433 | DenseMap<Instruction *, PHINode *> &PHIMap, |
| 6434 | unsigned Depth) { |
| 6435 | if (Depth > MaxConstantEvolvingDepth) |
| 6436 | return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6437 | |
| 6438 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 6439 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6440 | PHINode *PHI = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6441 | for (Value *Op : UseInst->operands()) { |
| 6442 | if (isa<Constant>(Op)) continue; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6443 | |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6444 | Instruction *OpInst = dyn_cast<Instruction>(Op); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6445 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6446 | |
| 6447 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 6448 | if (!P) |
| 6449 | // If this operand is already visited, reuse the prior result. |
| 6450 | // We may have P != PHI if this is the deepest point at which the |
| 6451 | // inconsistent paths meet. |
| 6452 | P = PHIMap.lookup(OpInst); |
| 6453 | if (!P) { |
| 6454 | // Recurse and memoize the results, whether a phi is found or not. |
| 6455 | // This recursive call invalidates pointers into PHIMap. |
Michael Liao | 468fb74 | 2017-01-13 18:28:30 +0000 | [diff] [blame] | 6456 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 6457 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6458 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6459 | if (!P) |
| 6460 | return nullptr; // Not evolving from PHI |
| 6461 | if (PHI && PHI != P) |
| 6462 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6463 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6464 | } |
| 6465 | // This is a expression evolving from a constant PHI! |
| 6466 | return PHI; |
| 6467 | } |
| 6468 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6469 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 6470 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 6471 | /// way, but the operands of an operation must either be constants or a value |
| 6472 | /// derived from a constant PHI. If this expression does not fit with these |
| 6473 | /// constraints, return null. |
| 6474 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6475 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6476 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6477 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 6478 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6479 | return PN; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6480 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6481 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6482 | DenseMap<Instruction *, PHINode *> PHIMap; |
Michael Liao | 468fb74 | 2017-01-13 18:28:30 +0000 | [diff] [blame] | 6483 | return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6484 | } |
| 6485 | |
| 6486 | /// EvaluateExpression - Given an expression that passes the |
| 6487 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 6488 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 6489 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6490 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 6491 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6492 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 6493 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6494 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 6495 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6496 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6497 | if (!I) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6498 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6499 | if (Constant *C = Vals.lookup(I)) return C; |
| 6500 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6501 | // An instruction inside the loop depends on a value outside the loop that we |
| 6502 | // 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] | 6503 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6504 | |
| 6505 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 6506 | // or due to this not being the initial iteration through a loop where we |
| 6507 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6508 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6509 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 6510 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6511 | |
| 6512 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6513 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 6514 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 6515 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6516 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6517 | continue; |
| 6518 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6519 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6520 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6521 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6522 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6523 | } |
| 6524 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6525 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 6526 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6527 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6528 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6529 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6530 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6531 | } |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6532 | return ConstantFoldInstOperands(I, Operands, DL, TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6533 | } |
| 6534 | |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6535 | |
| 6536 | // If every incoming value to PN except the one for BB is a specific Constant, |
| 6537 | // return that, else return nullptr. |
| 6538 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { |
| 6539 | Constant *IncomingVal = nullptr; |
| 6540 | |
| 6541 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 6542 | if (PN->getIncomingBlock(i) == BB) |
| 6543 | continue; |
| 6544 | |
| 6545 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 6546 | if (!CurrentVal) |
| 6547 | return nullptr; |
| 6548 | |
| 6549 | if (IncomingVal != CurrentVal) { |
| 6550 | if (IncomingVal) |
| 6551 | return nullptr; |
| 6552 | IncomingVal = CurrentVal; |
| 6553 | } |
| 6554 | } |
| 6555 | |
| 6556 | return IncomingVal; |
| 6557 | } |
| 6558 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6559 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 6560 | /// in the header of its containing loop, we know the loop executes a |
| 6561 | /// constant number of times, and the PHI node is just a recurrence |
| 6562 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6563 | Constant * |
| 6564 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 6565 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6566 | const Loop *L) { |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6567 | auto I = ConstantEvolutionLoopExitValue.find(PN); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6568 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 6569 | return I->second; |
| 6570 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 6571 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6572 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6573 | |
| 6574 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 6575 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6576 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6577 | BasicBlock *Header = L->getHeader(); |
| 6578 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6579 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6580 | BasicBlock *Latch = L->getLoopLatch(); |
| 6581 | if (!Latch) |
| 6582 | return nullptr; |
| 6583 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6584 | for (auto &I : *Header) { |
| 6585 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6586 | if (!PHI) break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6587 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6588 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6589 | CurrentIterVals[PHI] = StartCST; |
| 6590 | } |
| 6591 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6592 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6593 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6594 | Value *BEValue = PN->getIncomingValueForBlock(Latch); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6595 | |
| 6596 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6597 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6598 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6599 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6600 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6601 | unsigned IterationNum = 0; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6602 | const DataLayout &DL = getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6603 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6604 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6605 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6606 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6607 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6608 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6609 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6610 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6611 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6612 | if (!NextPHI) |
| 6613 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6614 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6615 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6616 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 6617 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6618 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 6619 | // cease to be able to evaluate one of them or if they stop evolving, |
| 6620 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6621 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6622 | for (const auto &I : CurrentIterVals) { |
| 6623 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 6624 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6625 | PHIsToCompute.emplace_back(PHI, I.second); |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6626 | } |
| 6627 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 6628 | // iterators into CurrentIterVals. |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6629 | for (const auto &I : PHIsToCompute) { |
| 6630 | PHINode *PHI = I.first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6631 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6632 | if (!NextPHI) { // Not already computed. |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6633 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6634 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6635 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6636 | if (NextPHI != I.second) |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6637 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6638 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6639 | |
| 6640 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 6641 | // iterating, the loop can't continue to change. |
| 6642 | if (StoppedEvolving) |
| 6643 | return RetVal = CurrentIterVals[PN]; |
| 6644 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6645 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6646 | } |
| 6647 | } |
| 6648 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6649 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6650 | Value *Cond, |
| 6651 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6652 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6653 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6654 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 6655 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 6656 | // That's the only form we support here. |
| 6657 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 6658 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6659 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 6660 | BasicBlock *Header = L->getHeader(); |
| 6661 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 6662 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6663 | BasicBlock *Latch = L->getLoopLatch(); |
| 6664 | assert(Latch && "Should follow from NumIncomingValues == 2!"); |
| 6665 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6666 | for (auto &I : *Header) { |
| 6667 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6668 | if (!PHI) |
| 6669 | break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6670 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6671 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6672 | CurrentIterVals[PHI] = StartCST; |
| 6673 | } |
| 6674 | if (!CurrentIterVals.count(PN)) |
| 6675 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6676 | |
| 6677 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 6678 | // the loop symbolically to determine when the condition gets a value of |
| 6679 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 6680 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6681 | const DataLayout &DL = getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6682 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6683 | auto *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6684 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6685 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6686 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6687 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6688 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6689 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6690 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 6691 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6692 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6693 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6694 | // Update all the PHI nodes for the next iteration. |
| 6695 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6696 | |
| 6697 | // Create a list of which PHIs we need to compute. We want to do this before |
| 6698 | // calling EvaluateExpression on them because that may invalidate iterators |
| 6699 | // into CurrentIterVals. |
| 6700 | SmallVector<PHINode *, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6701 | for (const auto &I : CurrentIterVals) { |
| 6702 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6703 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6704 | PHIsToCompute.push_back(PHI); |
| 6705 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6706 | for (PHINode *PHI : PHIsToCompute) { |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6707 | Constant *&NextPHI = NextIterVals[PHI]; |
| 6708 | if (NextPHI) continue; // Already computed! |
| 6709 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6710 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6711 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6712 | } |
| 6713 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6714 | } |
| 6715 | |
| 6716 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6717 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6718 | } |
| 6719 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6720 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6721 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = |
| 6722 | ValuesAtScopes[V]; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6723 | // 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] | 6724 | for (auto &LS : Values) |
| 6725 | if (LS.first == L) |
| 6726 | return LS.second ? LS.second : V; |
| 6727 | |
| 6728 | Values.emplace_back(L, nullptr); |
| 6729 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6730 | // Otherwise compute it. |
| 6731 | const SCEV *C = computeSCEVAtScope(V, L); |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6732 | for (auto &LS : reverse(ValuesAtScopes[V])) |
| 6733 | if (LS.first == L) { |
| 6734 | LS.second = C; |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 6735 | break; |
| 6736 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6737 | return C; |
| 6738 | } |
| 6739 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6740 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 6741 | /// will return Constants for objects which aren't represented by a |
| 6742 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 6743 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 6744 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6745 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6746 | case scCouldNotCompute: |
| 6747 | case scAddRecExpr: |
| 6748 | break; |
| 6749 | case scConstant: |
| 6750 | return cast<SCEVConstant>(V)->getValue(); |
| 6751 | case scUnknown: |
| 6752 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 6753 | case scSignExtend: { |
| 6754 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 6755 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 6756 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 6757 | break; |
| 6758 | } |
| 6759 | case scZeroExtend: { |
| 6760 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 6761 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 6762 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 6763 | break; |
| 6764 | } |
| 6765 | case scTruncate: { |
| 6766 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 6767 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 6768 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 6769 | break; |
| 6770 | } |
| 6771 | case scAddExpr: { |
| 6772 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 6773 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6774 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6775 | unsigned AS = PTy->getAddressSpace(); |
| 6776 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 6777 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 6778 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6779 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 6780 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6781 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6782 | |
| 6783 | // First pointer! |
| 6784 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6785 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6786 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6787 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6788 | // The offsets have been converted to bytes. We can add bytes to an |
| 6789 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6790 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6791 | } |
| 6792 | |
| 6793 | // Don't bother trying to sum two pointers. We probably can't |
| 6794 | // statically compute a load that results from it anyway. |
| 6795 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6796 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6797 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6798 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6799 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6800 | C2 = ConstantExpr::getIntegerCast( |
| 6801 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 6802 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6803 | } else |
| 6804 | C = ConstantExpr::getAdd(C, C2); |
| 6805 | } |
| 6806 | return C; |
| 6807 | } |
| 6808 | break; |
| 6809 | } |
| 6810 | case scMulExpr: { |
| 6811 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 6812 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 6813 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6814 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6815 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 6816 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6817 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6818 | C = ConstantExpr::getMul(C, C2); |
| 6819 | } |
| 6820 | return C; |
| 6821 | } |
| 6822 | break; |
| 6823 | } |
| 6824 | case scUDivExpr: { |
| 6825 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 6826 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 6827 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 6828 | if (LHS->getType() == RHS->getType()) |
| 6829 | return ConstantExpr::getUDiv(LHS, RHS); |
| 6830 | break; |
| 6831 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6832 | case scSMaxExpr: |
| 6833 | case scUMaxExpr: |
| 6834 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6835 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6836 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6837 | } |
| 6838 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6839 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6840 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6841 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6842 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6843 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6844 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6845 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6846 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6847 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 6848 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 6849 | if (PN->getParent() == LI->getHeader()) { |
| 6850 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6851 | // to see if the loop that contains it has a known backedge-taken |
| 6852 | // count. If so, we may be able to force computation of the exit |
| 6853 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6854 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6855 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6856 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6857 | // Okay, we know how many times the containing loop executes. If |
| 6858 | // this is a constant evolving PHI node, get the final value at |
| 6859 | // the specified iteration number. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6860 | Constant *RV = |
| 6861 | getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 6862 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6863 | } |
| 6864 | } |
| 6865 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6866 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6867 | // 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] | 6868 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6869 | // result. This is particularly useful for computing loop exit values. |
| 6870 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6871 | SmallVector<Constant *, 4> Operands; |
| 6872 | bool MadeImprovement = false; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 6873 | for (Value *Op : I->operands()) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6874 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 6875 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6876 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6877 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6878 | |
| 6879 | // If any of the operands is non-constant and if they are |
| 6880 | // non-integer and non-pointer, don't even try to analyze them |
| 6881 | // with scev techniques. |
| 6882 | if (!isSCEVable(Op->getType())) |
| 6883 | return V; |
| 6884 | |
| 6885 | const SCEV *OrigV = getSCEV(Op); |
| 6886 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 6887 | MadeImprovement |= OrigV != OpV; |
| 6888 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6889 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6890 | if (!C) return V; |
| 6891 | if (C->getType() != Op->getType()) |
| 6892 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 6893 | Op->getType(), |
| 6894 | false), |
| 6895 | C, Op->getType()); |
| 6896 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6897 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6898 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6899 | // Check to see if getSCEVAtScope actually made an improvement. |
| 6900 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6901 | Constant *C = nullptr; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6902 | const DataLayout &DL = getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6903 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6904 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6905 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6906 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6907 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6908 | C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6909 | } else |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6910 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6911 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 6912 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6913 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6914 | } |
| 6915 | } |
| 6916 | |
| 6917 | // This is some other type of SCEVUnknown, just return it. |
| 6918 | return V; |
| 6919 | } |
| 6920 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6921 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6922 | // Avoid performing the look-up in the common case where the specified |
| 6923 | // expression has no loop-variant portions. |
| 6924 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6925 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6926 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6927 | // Okay, at least one of these operands is loop variant but might be |
| 6928 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6929 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 6930 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6931 | NewOps.push_back(OpAtScope); |
| 6932 | |
| 6933 | for (++i; i != e; ++i) { |
| 6934 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6935 | NewOps.push_back(OpAtScope); |
| 6936 | } |
| 6937 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6938 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6939 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6940 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6941 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6942 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6943 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6944 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6945 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6946 | } |
| 6947 | } |
| 6948 | // If we got here, all operands are loop invariant. |
| 6949 | return Comm; |
| 6950 | } |
| 6951 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6952 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6953 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 6954 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 6955 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 6956 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6957 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6958 | } |
| 6959 | |
| 6960 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6961 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6962 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6963 | // First, attempt to evaluate each operand. |
| 6964 | // Avoid performing the look-up in the common case where the specified |
| 6965 | // expression has no loop-variant portions. |
| 6966 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6967 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6968 | if (OpAtScope == AddRec->getOperand(i)) |
| 6969 | continue; |
| 6970 | |
| 6971 | // Okay, at least one of these operands is loop variant but might be |
| 6972 | // foldable. Build a new instance of the folded commutative expression. |
| 6973 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6974 | AddRec->op_begin()+i); |
| 6975 | NewOps.push_back(OpAtScope); |
| 6976 | for (++i; i != e; ++i) |
| 6977 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6978 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6979 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6980 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6981 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6982 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6983 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6984 | // induction variable is multiplied by zero after constant folding. Go |
| 6985 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6986 | if (!AddRec) |
| 6987 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6988 | break; |
| 6989 | } |
| 6990 | |
| 6991 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6992 | // loop exit value of the addrec. |
| 6993 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6994 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6995 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6996 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6997 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6998 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6999 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7000 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7001 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 7002 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 7003 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7004 | } |
| 7005 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7006 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7007 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 7008 | if (Op == Cast->getOperand()) |
| 7009 | return Cast; // must be loop invariant |
| 7010 | return getZeroExtendExpr(Op, Cast->getType()); |
| 7011 | } |
| 7012 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7013 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7014 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 7015 | if (Op == Cast->getOperand()) |
| 7016 | return Cast; // must be loop invariant |
| 7017 | return getSignExtendExpr(Op, Cast->getType()); |
| 7018 | } |
| 7019 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7020 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7021 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 7022 | if (Op == Cast->getOperand()) |
| 7023 | return Cast; // must be loop invariant |
| 7024 | return getTruncateExpr(Op, Cast->getType()); |
| 7025 | } |
| 7026 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 7027 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7028 | } |
| 7029 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7030 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7031 | return getSCEVAtScope(getSCEV(V), L); |
| 7032 | } |
| 7033 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7034 | /// Finds the minimum unsigned root of the following equation: |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7035 | /// |
| 7036 | /// A * X = B (mod N) |
| 7037 | /// |
| 7038 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 7039 | /// A and B isn't important. |
| 7040 | /// |
| 7041 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7042 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7043 | ScalarEvolution &SE) { |
| 7044 | uint32_t BW = A.getBitWidth(); |
| 7045 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 7046 | assert(A != 0 && "A must be non-zero."); |
| 7047 | |
| 7048 | // 1. D = gcd(A, N) |
| 7049 | // |
| 7050 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 7051 | // trailing zeros in A is its multiplicity |
| 7052 | uint32_t Mult2 = A.countTrailingZeros(); |
| 7053 | // D = 2^Mult2 |
| 7054 | |
| 7055 | // 2. Check if B is divisible by D. |
| 7056 | // |
| 7057 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 7058 | // is not less than multiplicity of this prime factor for D. |
| 7059 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7060 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7061 | |
| 7062 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 7063 | // modulo (N / D). |
| 7064 | // |
Eli Friedman | b5c3a0d | 2017-01-12 20:21:00 +0000 | [diff] [blame] | 7065 | // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent |
| 7066 | // (N / D) in general. The inverse itself always fits into BW bits, though, |
| 7067 | // so we immediately truncate it. |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7068 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 7069 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 7070 | Mod.setBit(BW - Mult2); // Mod = N / D |
Eli Friedman | b5c3a0d | 2017-01-12 20:21:00 +0000 | [diff] [blame] | 7071 | APInt I = AD.multiplicativeInverse(Mod).trunc(BW); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7072 | |
| 7073 | // 4. Compute the minimum unsigned root of the equation: |
| 7074 | // I * (B / D) mod (N / D) |
Eli Friedman | b5c3a0d | 2017-01-12 20:21:00 +0000 | [diff] [blame] | 7075 | // To simplify the computation, we factor out the divide by D: |
| 7076 | // (I * B mod N) / D |
| 7077 | APInt Result = (I * B).lshr(Mult2); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7078 | |
Eli Friedman | b5c3a0d | 2017-01-12 20:21:00 +0000 | [diff] [blame] | 7079 | return SE.getConstant(Result); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7080 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7081 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7082 | /// Find the roots of the quadratic equation for the given quadratic chrec |
| 7083 | /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or |
| 7084 | /// two SCEVCouldNotCompute objects. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7085 | /// |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7086 | static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7087 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7088 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7089 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 7090 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 7091 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7092 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7093 | // We currently can only solve this if the coefficients are constants. |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7094 | if (!LC || !MC || !NC) |
| 7095 | return None; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7096 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7097 | uint32_t BitWidth = LC->getAPInt().getBitWidth(); |
| 7098 | const APInt &L = LC->getAPInt(); |
| 7099 | const APInt &M = MC->getAPInt(); |
| 7100 | const APInt &N = NC->getAPInt(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7101 | APInt Two(BitWidth, 2); |
| 7102 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7103 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7104 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7105 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 7106 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7107 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 7108 | // The B coefficient is M-N/2 |
| 7109 | APInt B(M); |
| 7110 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7111 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7112 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 7113 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7114 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7115 | // Compute the B^2-4ac term. |
| 7116 | APInt SqrtTerm(B); |
| 7117 | SqrtTerm *= B; |
| 7118 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7119 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 7120 | if (SqrtTerm.isNegative()) { |
| 7121 | // The loop is provably infinite. |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7122 | return None; |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 7123 | } |
| 7124 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7125 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 7126 | // integer value or else APInt::sqrt() will assert. |
| 7127 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7128 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7129 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7130 | // The divisions must be performed as signed divisions. |
| 7131 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7132 | APInt TwoA(A << 1); |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7133 | if (TwoA.isMinValue()) |
| 7134 | return None; |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 7135 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 7136 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7137 | |
| 7138 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7139 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7140 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7141 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7142 | |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7143 | return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), |
| 7144 | cast<SCEVConstant>(SE.getConstant(Solution2))); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7145 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7146 | } |
| 7147 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7148 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 7149 | ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7150 | bool AllowPredicates) { |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7151 | |
| 7152 | // This is only used for loops with a "x != y" exit test. The exit condition |
| 7153 | // is now expressed as a single expression, V = x-y. So the exit test is |
| 7154 | // effectively V != 0. We know and take advantage of the fact that this |
| 7155 | // expression only being used in a comparison by zero context. |
| 7156 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 7157 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7158 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7159 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7160 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 7161 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7162 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7163 | } |
| 7164 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7165 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7166 | if (!AddRec && AllowPredicates) |
| 7167 | // Try to make this an AddRec using runtime tests, in the first X |
| 7168 | // iterations of this loop, where X is the SCEV expression found by the |
| 7169 | // algorithm below. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 7170 | AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7171 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7172 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7173 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7174 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7175 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 7176 | // the quadratic equation to solve it. |
| 7177 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7178 | if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { |
| 7179 | const SCEVConstant *R1 = Roots->first; |
| 7180 | const SCEVConstant *R2 = Roots->second; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7181 | // Pick the smallest positive root value. |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 7182 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 7183 | CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 7184 | if (!CB->getZExtValue()) |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 7185 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7186 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7187 | // We can only use this value if the chrec ends up with an exact zero |
| 7188 | // value at this index. When solving for "X*X != 5", for example, we |
| 7189 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7190 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 7191 | if (Val->isZero()) |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7192 | // We found a quadratic root! |
| 7193 | return ExitLimit(R1, R1, false, Predicates); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7194 | } |
| 7195 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7196 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7197 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7198 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7199 | // Otherwise we can only handle this if it is affine. |
| 7200 | if (!AddRec->isAffine()) |
| 7201 | return getCouldNotCompute(); |
| 7202 | |
| 7203 | // If this is an affine expression, the execution count of this branch is |
| 7204 | // the minimum unsigned root of the following equation: |
| 7205 | // |
| 7206 | // Start + Step*N = 0 (mod 2^BW) |
| 7207 | // |
| 7208 | // equivalent to: |
| 7209 | // |
| 7210 | // Step*N = -Start (mod 2^BW) |
| 7211 | // |
| 7212 | // where BW is the common bit width of Start and Step. |
| 7213 | |
| 7214 | // Get the initial value for the loop. |
| 7215 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 7216 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 7217 | |
| 7218 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7219 | // |
| 7220 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 7221 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 7222 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 7223 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7224 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 7225 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7226 | return getCouldNotCompute(); |
| 7227 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7228 | // For positive steps (counting up until unsigned overflow): |
| 7229 | // N = -Start/Step (as unsigned) |
| 7230 | // For negative steps (counting down to zero): |
| 7231 | // N = Start/-Step |
| 7232 | // First compute the unsigned distance from zero in the direction of Step. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7233 | bool CountDown = StepC->getAPInt().isNegative(); |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7234 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7235 | |
| 7236 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7237 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 7238 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7239 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
Eli Friedman | 8396265 | 2017-01-11 20:55:48 +0000 | [diff] [blame] | 7240 | APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax(); |
Eli Friedman | bd6deda | 2017-01-11 21:07:15 +0000 | [diff] [blame] | 7241 | |
| 7242 | // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, |
| 7243 | // we end up with a loop whose backedge-taken count is n - 1. Detect this |
| 7244 | // case, and see if we can improve the bound. |
| 7245 | // |
| 7246 | // Explicitly handling this here is necessary because getUnsignedRange |
| 7247 | // isn't context-sensitive; it doesn't know that we only care about the |
| 7248 | // range inside the loop. |
| 7249 | const SCEV *Zero = getZero(Distance->getType()); |
| 7250 | const SCEV *One = getOne(Distance->getType()); |
| 7251 | const SCEV *DistancePlusOne = getAddExpr(Distance, One); |
| 7252 | if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { |
| 7253 | // If Distance + 1 doesn't overflow, we can compute the maximum distance |
| 7254 | // as "unsigned_max(Distance + 1) - 1". |
| 7255 | ConstantRange CR = getUnsignedRange(DistancePlusOne); |
| 7256 | MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); |
| 7257 | } |
Eli Friedman | 8396265 | 2017-01-11 20:55:48 +0000 | [diff] [blame] | 7258 | return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7259 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7260 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7261 | // As a special case, handle the instance where Step is a positive power of |
| 7262 | // two. In this case, determining whether Step divides Distance evenly can be |
| 7263 | // done by counting and comparing the number of trailing zeros of Step and |
| 7264 | // Distance. |
| 7265 | if (!CountDown) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7266 | const APInt &StepV = StepC->getAPInt(); |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7267 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 7268 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 7269 | // case is not handled as this code is guarded by !CountDown. |
| 7270 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7271 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 7272 | // Here we've constrained the equation to be of the form |
| 7273 | // |
| 7274 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 7275 | // |
| 7276 | // where we're operating on a W bit wide integer domain and k is |
| 7277 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 7278 | // |
| 7279 | // (0) is equivalent to: |
| 7280 | // |
| 7281 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 7282 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 7283 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 7284 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 7285 | // |
| 7286 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 7287 | // by 2^(W - N). |
| 7288 | // |
| 7289 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 7290 | // |
| 7291 | // E.g. say we're solving |
| 7292 | // |
| 7293 | // 2 * Val = 2 * X (in i8) ... (3) |
| 7294 | // |
| 7295 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 7296 | // |
| 7297 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 7298 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 7299 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 7300 | // is i8 1, not i8 -127 |
| 7301 | |
Eli Friedman | f1f49c8 | 2017-01-18 23:56:42 +0000 | [diff] [blame] | 7302 | const auto *Limit = getUDivExactExpr(Distance, Step); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7303 | return ExitLimit(Limit, Limit, false, Predicates); |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7304 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7305 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7306 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7307 | // If the condition controls loop exit (the loop exits only if the expression |
| 7308 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 7309 | // compute the backedge count. In this case, the step may not divide the |
| 7310 | // distance, but we don't care because if the condition is "missed" the loop |
| 7311 | // will have undefined behavior due to wrapping. |
Sanjoy Das | c7f69b9 | 2016-06-09 01:13:59 +0000 | [diff] [blame] | 7312 | if (ControlsExit && AddRec->hasNoSelfWrap() && |
| 7313 | loopHasNoAbnormalExits(AddRec->getLoop())) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7314 | const SCEV *Exact = |
| 7315 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7316 | return ExitLimit(Exact, Exact, false, Predicates); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7317 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7318 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7319 | // Then, try to solve the above equation provided that Start is constant. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7320 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { |
| 7321 | const SCEV *E = SolveLinEquationWithOverflow( |
| 7322 | StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7323 | return ExitLimit(E, E, false, Predicates); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7324 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7325 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7326 | } |
| 7327 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7328 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 7329 | ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7330 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 7331 | // handle them yet except for the trivial case. This could be expanded in the |
| 7332 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7333 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7334 | // If the value is a constant, check to see if it is known to be non-zero |
| 7335 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7336 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 7337 | if (!C->getValue()->isNullValue()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 7338 | return getZero(C->getType()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7339 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7340 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7341 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7342 | // We could implement others, but I really doubt anyone writes loops like |
| 7343 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7344 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7345 | } |
| 7346 | |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7347 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7348 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 7349 | // If the block has a unique predecessor, then there is no path from the |
| 7350 | // predecessor to the block that does not go through the direct edge |
| 7351 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7352 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7353 | return {Pred, BB}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7354 | |
| 7355 | // 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] | 7356 | // If the header has a unique predecessor outside the loop, it must be |
| 7357 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7358 | if (Loop *L = LI.getLoopFor(BB)) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7359 | return {L->getLoopPredecessor(), L->getHeader()}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7360 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7361 | return {nullptr, nullptr}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7362 | } |
| 7363 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7364 | /// SCEV structural equivalence is usually sufficient for testing whether two |
| 7365 | /// expressions are equal, however for the purposes of looking for a condition |
| 7366 | /// guarding a loop, it can be useful to be a little more general, since a |
| 7367 | /// front-end may have replicated the controlling expression. |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7368 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7369 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7370 | // Quick check to see if they are the same SCEV. |
| 7371 | if (A == B) return true; |
| 7372 | |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7373 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { |
| 7374 | // Not all instructions that are "identical" compute the same value. For |
| 7375 | // instance, two distinct alloca instructions allocating the same type are |
| 7376 | // identical and do not read memory; but compute distinct values. |
| 7377 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); |
| 7378 | }; |
| 7379 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7380 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 7381 | // two different instructions with the same value. Check for this case. |
| 7382 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 7383 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 7384 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 7385 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7386 | if (ComputesEqualValues(AI, BI)) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7387 | return true; |
| 7388 | |
| 7389 | // Otherwise assume they may have a different value. |
| 7390 | return false; |
| 7391 | } |
| 7392 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7393 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7394 | const SCEV *&LHS, const SCEV *&RHS, |
| 7395 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7396 | bool Changed = false; |
| 7397 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7398 | // If we hit the max recursion limit bail out. |
| 7399 | if (Depth >= 3) |
| 7400 | return false; |
| 7401 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7402 | // Canonicalize a constant to the right side. |
| 7403 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 7404 | // Check for both operands constant. |
| 7405 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 7406 | if (ConstantExpr::getICmp(Pred, |
| 7407 | LHSC->getValue(), |
| 7408 | RHSC->getValue())->isNullValue()) |
| 7409 | goto trivially_false; |
| 7410 | else |
| 7411 | goto trivially_true; |
| 7412 | } |
| 7413 | // Otherwise swap the operands to put the constant on the right. |
| 7414 | std::swap(LHS, RHS); |
| 7415 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7416 | Changed = true; |
| 7417 | } |
| 7418 | |
| 7419 | // 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] | 7420 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 7421 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 7422 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 7423 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 7424 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7425 | std::swap(LHS, RHS); |
| 7426 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7427 | Changed = true; |
| 7428 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 7429 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7430 | |
| 7431 | // If there's a constant operand, canonicalize comparisons with boundary |
| 7432 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 7433 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7434 | const APInt &RA = RC->getAPInt(); |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7435 | |
| 7436 | bool SimplifiedByConstantRange = false; |
| 7437 | |
| 7438 | if (!ICmpInst::isEquality(Pred)) { |
| 7439 | ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); |
| 7440 | if (ExactCR.isFullSet()) |
| 7441 | goto trivially_true; |
| 7442 | else if (ExactCR.isEmptySet()) |
| 7443 | goto trivially_false; |
| 7444 | |
| 7445 | APInt NewRHS; |
| 7446 | CmpInst::Predicate NewPred; |
| 7447 | if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && |
| 7448 | ICmpInst::isEquality(NewPred)) { |
| 7449 | // We were able to convert an inequality to an equality. |
| 7450 | Pred = NewPred; |
| 7451 | RHS = getConstant(NewRHS); |
| 7452 | Changed = SimplifiedByConstantRange = true; |
| 7453 | } |
| 7454 | } |
| 7455 | |
| 7456 | if (!SimplifiedByConstantRange) { |
| 7457 | switch (Pred) { |
| 7458 | default: |
| 7459 | break; |
| 7460 | case ICmpInst::ICMP_EQ: |
| 7461 | case ICmpInst::ICMP_NE: |
| 7462 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 7463 | if (!RA) |
| 7464 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 7465 | if (const SCEVMulExpr *ME = |
| 7466 | dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
| 7467 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 7468 | ME->getOperand(0)->isAllOnesValue()) { |
| 7469 | RHS = AE->getOperand(1); |
| 7470 | LHS = ME->getOperand(1); |
| 7471 | Changed = true; |
| 7472 | } |
| 7473 | break; |
| 7474 | |
| 7475 | |
| 7476 | // The "Should have been caught earlier!" messages refer to the fact |
| 7477 | // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above |
| 7478 | // should have fired on the corresponding cases, and canonicalized the |
| 7479 | // check to trivially_true or trivially_false. |
| 7480 | |
| 7481 | case ICmpInst::ICMP_UGE: |
| 7482 | assert(!RA.isMinValue() && "Should have been caught earlier!"); |
| 7483 | Pred = ICmpInst::ICMP_UGT; |
Sanjoy Das | f230b0a | 2016-10-02 02:40:27 +0000 | [diff] [blame] | 7484 | RHS = getConstant(RA - 1); |
| 7485 | Changed = true; |
| 7486 | break; |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7487 | case ICmpInst::ICMP_ULE: |
| 7488 | assert(!RA.isMaxValue() && "Should have been caught earlier!"); |
| 7489 | Pred = ICmpInst::ICMP_ULT; |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7490 | RHS = getConstant(RA + 1); |
| 7491 | Changed = true; |
| 7492 | break; |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7493 | case ICmpInst::ICMP_SGE: |
| 7494 | assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); |
| 7495 | Pred = ICmpInst::ICMP_SGT; |
Sanjoy Das | f230b0a | 2016-10-02 02:40:27 +0000 | [diff] [blame] | 7496 | RHS = getConstant(RA - 1); |
| 7497 | Changed = true; |
| 7498 | break; |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7499 | case ICmpInst::ICMP_SLE: |
| 7500 | assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); |
| 7501 | Pred = ICmpInst::ICMP_SLT; |
Sanjoy Das | f230b0a | 2016-10-02 02:40:27 +0000 | [diff] [blame] | 7502 | RHS = getConstant(RA + 1); |
| 7503 | Changed = true; |
| 7504 | break; |
| 7505 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7506 | } |
| 7507 | } |
| 7508 | |
| 7509 | // Check for obvious equality. |
| 7510 | if (HasSameValue(LHS, RHS)) { |
| 7511 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7512 | goto trivially_true; |
| 7513 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 7514 | goto trivially_false; |
| 7515 | } |
| 7516 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7517 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 7518 | // adding or subtracting 1 from one of the operands. |
| 7519 | switch (Pred) { |
| 7520 | case ICmpInst::ICMP_SLE: |
| 7521 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 7522 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7523 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7524 | Pred = ICmpInst::ICMP_SLT; |
| 7525 | Changed = true; |
| 7526 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7527 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7528 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7529 | Pred = ICmpInst::ICMP_SLT; |
| 7530 | Changed = true; |
| 7531 | } |
| 7532 | break; |
| 7533 | case ICmpInst::ICMP_SGE: |
| 7534 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7535 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7536 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7537 | Pred = ICmpInst::ICMP_SGT; |
| 7538 | Changed = true; |
| 7539 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 7540 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7541 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7542 | Pred = ICmpInst::ICMP_SGT; |
| 7543 | Changed = true; |
| 7544 | } |
| 7545 | break; |
| 7546 | case ICmpInst::ICMP_ULE: |
| 7547 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7548 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7549 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7550 | Pred = ICmpInst::ICMP_ULT; |
| 7551 | Changed = true; |
| 7552 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7553 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7554 | Pred = ICmpInst::ICMP_ULT; |
| 7555 | Changed = true; |
| 7556 | } |
| 7557 | break; |
| 7558 | case ICmpInst::ICMP_UGE: |
| 7559 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7560 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7561 | Pred = ICmpInst::ICMP_UGT; |
| 7562 | Changed = true; |
| 7563 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7564 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7565 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7566 | Pred = ICmpInst::ICMP_UGT; |
| 7567 | Changed = true; |
| 7568 | } |
| 7569 | break; |
| 7570 | default: |
| 7571 | break; |
| 7572 | } |
| 7573 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7574 | // TODO: More simplifications are possible here. |
| 7575 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7576 | // Recursively simplify until we either hit a recursion limit or nothing |
| 7577 | // changes. |
| 7578 | if (Changed) |
| 7579 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 7580 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7581 | return Changed; |
| 7582 | |
| 7583 | trivially_true: |
| 7584 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7585 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7586 | Pred = ICmpInst::ICMP_EQ; |
| 7587 | return true; |
| 7588 | |
| 7589 | trivially_false: |
| 7590 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7591 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7592 | Pred = ICmpInst::ICMP_NE; |
| 7593 | return true; |
| 7594 | } |
| 7595 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7596 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 7597 | return getSignedRange(S).getSignedMax().isNegative(); |
| 7598 | } |
| 7599 | |
| 7600 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 7601 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 7602 | } |
| 7603 | |
| 7604 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 7605 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 7606 | } |
| 7607 | |
| 7608 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 7609 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 7610 | } |
| 7611 | |
| 7612 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 7613 | return isKnownNegative(S) || isKnownPositive(S); |
| 7614 | } |
| 7615 | |
| 7616 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 7617 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 7618 | // Canonicalize the inputs first. |
| 7619 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 7620 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7621 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 7622 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 7623 | // If LHS and RHS are both addrec, both conditions must be true in |
| 7624 | // every iteration of the loop. |
| 7625 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7626 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7627 | bool LeftGuarded = false; |
| 7628 | bool RightGuarded = false; |
| 7629 | if (LAR) { |
| 7630 | const Loop *L = LAR->getLoop(); |
| 7631 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 7632 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 7633 | if (!RAR) return true; |
| 7634 | LeftGuarded = true; |
| 7635 | } |
| 7636 | } |
| 7637 | if (RAR) { |
| 7638 | const Loop *L = RAR->getLoop(); |
| 7639 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 7640 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 7641 | if (!LAR) return true; |
| 7642 | RightGuarded = true; |
| 7643 | } |
| 7644 | } |
| 7645 | if (LeftGuarded && RightGuarded) |
| 7646 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7647 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7648 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) |
| 7649 | return true; |
| 7650 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7651 | // Otherwise see what can be done with known constant ranges. |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7652 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7653 | } |
| 7654 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7655 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 7656 | ICmpInst::Predicate Pred, |
| 7657 | bool &Increasing) { |
| 7658 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 7659 | |
| 7660 | #ifndef NDEBUG |
| 7661 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 7662 | // increasing change to a monotonically decreasing one, and vice versa. |
| 7663 | bool IncreasingSwapped; |
| 7664 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 7665 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 7666 | |
| 7667 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 7668 | if (ResultSwapped) |
| 7669 | assert(Increasing == !IncreasingSwapped && |
| 7670 | "monotonicity should flip as we flip the predicate"); |
| 7671 | #endif |
| 7672 | |
| 7673 | return Result; |
| 7674 | } |
| 7675 | |
| 7676 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 7677 | ICmpInst::Predicate Pred, |
| 7678 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7679 | |
| 7680 | // A zero step value for LHS means the induction variable is essentially a |
| 7681 | // loop invariant value. We don't really depend on the predicate actually |
| 7682 | // flipping from false to true (for increasing predicates, and the other way |
| 7683 | // around for decreasing predicates), all we care about is that *if* the |
| 7684 | // predicate changes then it only changes from false to true. |
| 7685 | // |
| 7686 | // A zero step value in itself is not very useful, but there may be places |
| 7687 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 7688 | // as general as possible. |
| 7689 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7690 | switch (Pred) { |
| 7691 | default: |
| 7692 | return false; // Conservative answer |
| 7693 | |
| 7694 | case ICmpInst::ICMP_UGT: |
| 7695 | case ICmpInst::ICMP_UGE: |
| 7696 | case ICmpInst::ICMP_ULT: |
| 7697 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7698 | if (!LHS->hasNoUnsignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7699 | return false; |
| 7700 | |
| 7701 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7702 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7703 | |
| 7704 | case ICmpInst::ICMP_SGT: |
| 7705 | case ICmpInst::ICMP_SGE: |
| 7706 | case ICmpInst::ICMP_SLT: |
| 7707 | case ICmpInst::ICMP_SLE: { |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7708 | if (!LHS->hasNoSignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7709 | return false; |
| 7710 | |
| 7711 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 7712 | |
| 7713 | if (isKnownNonNegative(Step)) { |
| 7714 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 7715 | return true; |
| 7716 | } |
| 7717 | |
| 7718 | if (isKnownNonPositive(Step)) { |
| 7719 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 7720 | return true; |
| 7721 | } |
| 7722 | |
| 7723 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7724 | } |
| 7725 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7726 | } |
| 7727 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7728 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7729 | } |
| 7730 | |
| 7731 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 7732 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 7733 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 7734 | const SCEV *&InvariantRHS) { |
| 7735 | |
| 7736 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 7737 | if (!isLoopInvariant(RHS, L)) { |
| 7738 | if (!isLoopInvariant(LHS, L)) |
| 7739 | return false; |
| 7740 | |
| 7741 | std::swap(LHS, RHS); |
| 7742 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7743 | } |
| 7744 | |
| 7745 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7746 | if (!ArLHS || ArLHS->getLoop() != L) |
| 7747 | return false; |
| 7748 | |
| 7749 | bool Increasing; |
| 7750 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 7751 | return false; |
| 7752 | |
| 7753 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 7754 | // true as the loop iterates, and the backedge is control dependent on |
| 7755 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 7756 | // |
| 7757 | // * if the predicate was false in the first iteration then the predicate |
| 7758 | // is never evaluated again, since the loop exits without taking the |
| 7759 | // backedge. |
| 7760 | // * if the predicate was true in the first iteration then it will |
| 7761 | // continue to be true for all future iterations since it is |
| 7762 | // monotonically increasing. |
| 7763 | // |
| 7764 | // For both the above possibilities, we can replace the loop varying |
| 7765 | // predicate with its value on the first iteration of the loop (which is |
| 7766 | // loop invariant). |
| 7767 | // |
| 7768 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 7769 | // replacing true with false and false with true in the above two bullets. |
| 7770 | |
| 7771 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 7772 | |
| 7773 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 7774 | return false; |
| 7775 | |
| 7776 | InvariantPred = Pred; |
| 7777 | InvariantLHS = ArLHS->getStart(); |
| 7778 | InvariantRHS = RHS; |
| 7779 | return true; |
| 7780 | } |
| 7781 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7782 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( |
| 7783 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7784 | if (HasSameValue(LHS, RHS)) |
| 7785 | return ICmpInst::isTrueWhenEqual(Pred); |
| 7786 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7787 | // This code is split out from isKnownPredicate because it is called from |
| 7788 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7789 | |
Sanjoy Das | 4c7b6d7 | 2016-02-01 20:48:14 +0000 | [diff] [blame] | 7790 | auto CheckRanges = |
| 7791 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { |
| 7792 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) |
| 7793 | .contains(RangeLHS); |
| 7794 | }; |
| 7795 | |
| 7796 | // The check at the top of the function catches the case where the values are |
| 7797 | // known to be equal. |
| 7798 | if (Pred == CmpInst::ICMP_EQ) |
| 7799 | return false; |
| 7800 | |
| 7801 | if (Pred == CmpInst::ICMP_NE) |
| 7802 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || |
| 7803 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || |
| 7804 | isKnownNonZero(getMinusSCEV(LHS, RHS)); |
| 7805 | |
| 7806 | if (CmpInst::isSigned(Pred)) |
| 7807 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); |
| 7808 | |
| 7809 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7810 | } |
| 7811 | |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7812 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, |
| 7813 | const SCEV *LHS, |
| 7814 | const SCEV *RHS) { |
| 7815 | |
| 7816 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. |
| 7817 | // Return Y via OutY. |
| 7818 | auto MatchBinaryAddToConst = |
| 7819 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, |
| 7820 | SCEV::NoWrapFlags ExpectedFlags) { |
| 7821 | const SCEV *NonConstOp, *ConstOp; |
| 7822 | SCEV::NoWrapFlags FlagsPresent; |
| 7823 | |
| 7824 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || |
| 7825 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) |
| 7826 | return false; |
| 7827 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7828 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7829 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; |
| 7830 | }; |
| 7831 | |
| 7832 | APInt C; |
| 7833 | |
| 7834 | switch (Pred) { |
| 7835 | default: |
| 7836 | break; |
| 7837 | |
| 7838 | case ICmpInst::ICMP_SGE: |
| 7839 | std::swap(LHS, RHS); |
| 7840 | case ICmpInst::ICMP_SLE: |
| 7841 | // X s<= (X + C)<nsw> if C >= 0 |
| 7842 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) |
| 7843 | return true; |
| 7844 | |
| 7845 | // (X + C)<nsw> s<= X if C <= 0 |
| 7846 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && |
| 7847 | !C.isStrictlyPositive()) |
| 7848 | return true; |
| 7849 | break; |
| 7850 | |
| 7851 | case ICmpInst::ICMP_SGT: |
| 7852 | std::swap(LHS, RHS); |
| 7853 | case ICmpInst::ICMP_SLT: |
| 7854 | // X s< (X + C)<nsw> if C > 0 |
| 7855 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && |
| 7856 | C.isStrictlyPositive()) |
| 7857 | return true; |
| 7858 | |
| 7859 | // (X + C)<nsw> s< X if C < 0 |
| 7860 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) |
| 7861 | return true; |
| 7862 | break; |
| 7863 | } |
| 7864 | |
| 7865 | return false; |
| 7866 | } |
| 7867 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7868 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, |
| 7869 | const SCEV *LHS, |
| 7870 | const SCEV *RHS) { |
Sanjoy Das | 10dffcb | 2015-10-08 03:46:00 +0000 | [diff] [blame] | 7871 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7872 | return false; |
| 7873 | |
| 7874 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on |
| 7875 | // the stack can result in exponential time complexity. |
| 7876 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); |
| 7877 | |
| 7878 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L |
| 7879 | // |
| 7880 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use |
| 7881 | // isKnownPredicate. isKnownPredicate is more powerful, but also more |
| 7882 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the |
| 7883 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to |
| 7884 | // use isKnownPredicate later if needed. |
Alexander Kornienko | 484e48e3 | 2015-11-05 21:07:12 +0000 | [diff] [blame] | 7885 | return isKnownNonNegative(RHS) && |
| 7886 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && |
| 7887 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7888 | } |
| 7889 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7890 | bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, |
| 7891 | ICmpInst::Predicate Pred, |
| 7892 | const SCEV *LHS, const SCEV *RHS) { |
| 7893 | // No need to even try if we know the module has no guards. |
| 7894 | if (!HasGuards) |
| 7895 | return false; |
| 7896 | |
| 7897 | return any_of(*BB, [&](Instruction &I) { |
| 7898 | using namespace llvm::PatternMatch; |
| 7899 | |
| 7900 | Value *Condition; |
| 7901 | return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( |
| 7902 | m_Value(Condition))) && |
| 7903 | isImpliedCond(Pred, LHS, RHS, Condition, false); |
| 7904 | }); |
| 7905 | } |
| 7906 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7907 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 7908 | /// protected by a conditional between LHS and RHS. This is used to |
| 7909 | /// to eliminate casts. |
| 7910 | bool |
| 7911 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 7912 | ICmpInst::Predicate Pred, |
| 7913 | const SCEV *LHS, const SCEV *RHS) { |
| 7914 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7915 | // (interprocedural conditions notwithstanding). |
| 7916 | if (!L) return true; |
| 7917 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7918 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7919 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7920 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7921 | BasicBlock *Latch = L->getLoopLatch(); |
| 7922 | if (!Latch) |
| 7923 | return false; |
| 7924 | |
| 7925 | BranchInst *LoopContinuePredicate = |
| 7926 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7927 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 7928 | isImpliedCond(Pred, LHS, RHS, |
| 7929 | LoopContinuePredicate->getCondition(), |
| 7930 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 7931 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7932 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7933 | // 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] | 7934 | // -- that can lead to O(n!) time complexity. |
| 7935 | if (WalkingBEDominatingConds) |
| 7936 | return false; |
| 7937 | |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 7938 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7939 | |
Sanjoy Das | b174f9a | 2015-09-25 23:53:50 +0000 | [diff] [blame] | 7940 | // See if we can exploit a trip count to prove the predicate. |
| 7941 | const auto &BETakenInfo = getBackedgeTakenInfo(L); |
| 7942 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); |
| 7943 | if (LatchBECount != getCouldNotCompute()) { |
| 7944 | // We know that Latch branches back to the loop header exactly |
| 7945 | // LatchBECount times. This means the backdege condition at Latch is |
| 7946 | // equivalent to "{0,+,1} u< LatchBECount". |
| 7947 | Type *Ty = LatchBECount->getType(); |
| 7948 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); |
| 7949 | const SCEV *LoopCounter = |
| 7950 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); |
| 7951 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, |
| 7952 | LatchBECount)) |
| 7953 | return true; |
| 7954 | } |
| 7955 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7956 | // Check conditions due to any @llvm.assume intrinsics. |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 7957 | for (auto &AssumeVH : AC.assumptions()) { |
| 7958 | if (!AssumeVH) |
| 7959 | continue; |
| 7960 | auto *CI = cast<CallInst>(AssumeVH); |
| 7961 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7962 | continue; |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7963 | |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 7964 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7965 | return true; |
| 7966 | } |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7967 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7968 | // If the loop is not reachable from the entry block, we risk running into an |
| 7969 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7970 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7971 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7972 | return false; |
| 7973 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7974 | if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) |
| 7975 | return true; |
| 7976 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7977 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7978 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7979 | |
| 7980 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7981 | |
| 7982 | BasicBlock *BB = DTN->getBlock(); |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7983 | if (isImpliedViaGuard(BB, Pred, LHS, RHS)) |
| 7984 | return true; |
| 7985 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7986 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7987 | if (!PBB) |
| 7988 | continue; |
| 7989 | |
| 7990 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7991 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7992 | continue; |
| 7993 | |
| 7994 | Value *Condition = ContinuePredicate->getCondition(); |
| 7995 | |
| 7996 | // If we have an edge `E` within the loop body that dominates the only |
| 7997 | // latch, the condition guarding `E` also guards the backedge. This |
| 7998 | // reasoning works only for loops with a single latch. |
| 7999 | |
| 8000 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 8001 | if (DominatingEdge.isSingleEdge()) { |
| 8002 | // We're constructively (and conservatively) enumerating edges within the |
| 8003 | // loop body that dominate the latch. The dominator tree better agree |
| 8004 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8005 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 8006 | |
| 8007 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 8008 | BB != ContinuePredicate->getSuccessor(0))) |
| 8009 | return true; |
| 8010 | } |
| 8011 | } |
| 8012 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8013 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8014 | } |
| 8015 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8016 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 8017 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 8018 | ICmpInst::Predicate Pred, |
| 8019 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 8020 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 8021 | // (interprocedural conditions notwithstanding). |
| 8022 | if (!L) return false; |
| 8023 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8024 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 8025 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 8026 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 8027 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 8028 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 8029 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8030 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 8031 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8032 | Pair.first; |
| 8033 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8034 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 8035 | if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) |
| 8036 | return true; |
| 8037 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8038 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8039 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8040 | if (!LoopEntryPredicate || |
| 8041 | LoopEntryPredicate->isUnconditional()) |
| 8042 | continue; |
| 8043 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8044 | if (isImpliedCond(Pred, LHS, RHS, |
| 8045 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8046 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8047 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8048 | } |
| 8049 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8050 | // Check conditions due to any @llvm.assume intrinsics. |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 8051 | for (auto &AssumeVH : AC.assumptions()) { |
| 8052 | if (!AssumeVH) |
| 8053 | continue; |
| 8054 | auto *CI = cast<CallInst>(AssumeVH); |
| 8055 | if (!DT.dominates(CI, L->getHeader())) |
| 8056 | continue; |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8057 | |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 8058 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 8059 | return true; |
| 8060 | } |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8061 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8062 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8063 | } |
| 8064 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8065 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8066 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8067 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8068 | bool Inverse) { |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 8069 | if (!PendingLoopPredicates.insert(FoundCondValue).second) |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8070 | return false; |
| 8071 | |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 8072 | auto ClearOnExit = |
| 8073 | make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); |
| 8074 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8075 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8076 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8077 | if (BO->getOpcode() == Instruction::And) { |
| 8078 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8079 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8080 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8081 | } else if (BO->getOpcode() == Instruction::Or) { |
| 8082 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8083 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8084 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8085 | } |
| 8086 | } |
| 8087 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8088 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8089 | if (!ICI) return false; |
| 8090 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 8091 | // Now that we found a conditional branch that dominates the loop or controls |
| 8092 | // 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] | 8093 | ICmpInst::Predicate FoundPred; |
| 8094 | if (Inverse) |
| 8095 | FoundPred = ICI->getInversePredicate(); |
| 8096 | else |
| 8097 | FoundPred = ICI->getPredicate(); |
| 8098 | |
| 8099 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 8100 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8101 | |
Sanjoy Das | df1635d | 2015-09-25 19:59:52 +0000 | [diff] [blame] | 8102 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); |
| 8103 | } |
| 8104 | |
| 8105 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, |
| 8106 | const SCEV *RHS, |
| 8107 | ICmpInst::Predicate FoundPred, |
| 8108 | const SCEV *FoundLHS, |
| 8109 | const SCEV *FoundRHS) { |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 8110 | // Balance the types. |
| 8111 | if (getTypeSizeInBits(LHS->getType()) < |
| 8112 | getTypeSizeInBits(FoundLHS->getType())) { |
| 8113 | if (CmpInst::isSigned(Pred)) { |
| 8114 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 8115 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 8116 | } else { |
| 8117 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 8118 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 8119 | } |
| 8120 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8121 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 8122 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8123 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 8124 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 8125 | } else { |
| 8126 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 8127 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 8128 | } |
| 8129 | } |
| 8130 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8131 | // Canonicalize the query to match the way instcombine will have |
| 8132 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 8133 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 8134 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 8135 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 8136 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 8137 | if (FoundLHS == FoundRHS) |
| 8138 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8139 | |
| 8140 | // Check to see if we can make the LHS or RHS match. |
| 8141 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 8142 | if (isa<SCEVConstant>(RHS)) { |
| 8143 | std::swap(FoundLHS, FoundRHS); |
| 8144 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 8145 | } else { |
| 8146 | std::swap(LHS, RHS); |
| 8147 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 8148 | } |
| 8149 | } |
| 8150 | |
| 8151 | // Check whether the found predicate is the same as the desired predicate. |
| 8152 | if (FoundPred == Pred) |
| 8153 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8154 | |
| 8155 | // Check whether swapping the found predicate makes it the same as the |
| 8156 | // desired predicate. |
| 8157 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 8158 | if (isa<SCEVConstant>(RHS)) |
| 8159 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 8160 | else |
| 8161 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 8162 | RHS, LHS, FoundLHS, FoundRHS); |
| 8163 | } |
| 8164 | |
Sanjoy Das | 6e78b17 | 2015-10-22 19:57:34 +0000 | [diff] [blame] | 8165 | // Unsigned comparison is the same as signed comparison when both the operands |
| 8166 | // are non-negative. |
| 8167 | if (CmpInst::isUnsigned(FoundPred) && |
| 8168 | CmpInst::getSignedPredicate(FoundPred) == Pred && |
| 8169 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) |
| 8170 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8171 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8172 | // Check if we can make progress by sharpening ranges. |
| 8173 | if (FoundPred == ICmpInst::ICMP_NE && |
| 8174 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 8175 | |
| 8176 | const SCEVConstant *C = nullptr; |
| 8177 | const SCEV *V = nullptr; |
| 8178 | |
| 8179 | if (isa<SCEVConstant>(FoundLHS)) { |
| 8180 | C = cast<SCEVConstant>(FoundLHS); |
| 8181 | V = FoundRHS; |
| 8182 | } else { |
| 8183 | C = cast<SCEVConstant>(FoundRHS); |
| 8184 | V = FoundLHS; |
| 8185 | } |
| 8186 | |
| 8187 | // The guarding predicate tells us that C != V. If the known range |
| 8188 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 8189 | // range we consider has to correspond to same signedness as the |
| 8190 | // predicate we're interested in folding. |
| 8191 | |
| 8192 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 8193 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 8194 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8195 | if (Min == C->getAPInt()) { |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8196 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 8197 | // This is true even if (Min + 1) wraps around -- in case of |
| 8198 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 8199 | |
| 8200 | APInt SharperMin = Min + 1; |
| 8201 | |
| 8202 | switch (Pred) { |
| 8203 | case ICmpInst::ICMP_SGE: |
| 8204 | case ICmpInst::ICMP_UGE: |
| 8205 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 8206 | // RHS, we're done. |
| 8207 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 8208 | getConstant(SharperMin))) |
| 8209 | return true; |
| 8210 | |
| 8211 | case ICmpInst::ICMP_SGT: |
| 8212 | case ICmpInst::ICMP_UGT: |
| 8213 | // We know from the range information that (V `Pred` Min || |
| 8214 | // V == Min). We know from the guarding condition that !(V |
| 8215 | // == Min). This gives us |
| 8216 | // |
| 8217 | // V `Pred` Min || V == Min && !(V == Min) |
| 8218 | // => V `Pred` Min |
| 8219 | // |
| 8220 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 8221 | |
| 8222 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 8223 | return true; |
| 8224 | |
| 8225 | default: |
| 8226 | // No change |
| 8227 | break; |
| 8228 | } |
| 8229 | } |
| 8230 | } |
| 8231 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8232 | // Check whether the actual condition is beyond sufficient. |
| 8233 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 8234 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 8235 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8236 | return true; |
| 8237 | if (Pred == ICmpInst::ICMP_NE) |
| 8238 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 8239 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8240 | return true; |
| 8241 | |
| 8242 | // Otherwise assume the worst. |
| 8243 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8244 | } |
| 8245 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8246 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, |
| 8247 | const SCEV *&L, const SCEV *&R, |
| 8248 | SCEV::NoWrapFlags &Flags) { |
| 8249 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); |
| 8250 | if (!AE || AE->getNumOperands() != 2) |
| 8251 | return false; |
| 8252 | |
| 8253 | L = AE->getOperand(0); |
| 8254 | R = AE->getOperand(1); |
| 8255 | Flags = AE->getNoWrapFlags(); |
| 8256 | return true; |
| 8257 | } |
| 8258 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8259 | Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, |
| 8260 | const SCEV *Less) { |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8261 | // We avoid subtracting expressions here because this function is usually |
| 8262 | // fairly deep in the call stack (i.e. is called many times). |
| 8263 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8264 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { |
| 8265 | const auto *LAR = cast<SCEVAddRecExpr>(Less); |
| 8266 | const auto *MAR = cast<SCEVAddRecExpr>(More); |
| 8267 | |
| 8268 | if (LAR->getLoop() != MAR->getLoop()) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8269 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8270 | |
| 8271 | // We look at affine expressions only; not for correctness but to keep |
| 8272 | // getStepRecurrence cheap. |
| 8273 | if (!LAR->isAffine() || !MAR->isAffine()) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8274 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8275 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8276 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8277 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8278 | |
| 8279 | Less = LAR->getStart(); |
| 8280 | More = MAR->getStart(); |
| 8281 | |
| 8282 | // fall through |
| 8283 | } |
| 8284 | |
| 8285 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8286 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); |
| 8287 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8288 | return M - L; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8289 | } |
| 8290 | |
| 8291 | const SCEV *L, *R; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8292 | SCEV::NoWrapFlags Flags; |
| 8293 | if (splitBinaryAdd(Less, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8294 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8295 | if (R == More) |
| 8296 | return -(LC->getAPInt()); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8297 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8298 | if (splitBinaryAdd(More, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8299 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8300 | if (R == Less) |
| 8301 | return LC->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8302 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8303 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8304 | } |
| 8305 | |
| 8306 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( |
| 8307 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 8308 | const SCEV *FoundLHS, const SCEV *FoundRHS) { |
| 8309 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) |
| 8310 | return false; |
| 8311 | |
| 8312 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8313 | if (!AddRecLHS) |
| 8314 | return false; |
| 8315 | |
| 8316 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); |
| 8317 | if (!AddRecFoundLHS) |
| 8318 | return false; |
| 8319 | |
| 8320 | // We'd like to let SCEV reason about control dependencies, so we constrain |
| 8321 | // both the inequalities to be about add recurrences on the same loop. This |
| 8322 | // way we can use isLoopEntryGuardedByCond later. |
| 8323 | |
| 8324 | const Loop *L = AddRecFoundLHS->getLoop(); |
| 8325 | if (L != AddRecLHS->getLoop()) |
| 8326 | return false; |
| 8327 | |
| 8328 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) |
| 8329 | // |
| 8330 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) |
| 8331 | // ... (2) |
| 8332 | // |
| 8333 | // Informal proof for (2), assuming (1) [*]: |
| 8334 | // |
| 8335 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] |
| 8336 | // |
| 8337 | // Then |
| 8338 | // |
| 8339 | // FoundLHS s< FoundRHS s< INT_MIN - C |
| 8340 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] |
| 8341 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] |
| 8342 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< |
| 8343 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] |
| 8344 | // <=> FoundLHS + C s< FoundRHS + C |
| 8345 | // |
| 8346 | // [*]: (1) can be proved by ruling out overflow. |
| 8347 | // |
| 8348 | // [**]: This can be proved by analyzing all the four possibilities: |
| 8349 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and |
| 8350 | // (A s>= 0, B s>= 0). |
| 8351 | // |
| 8352 | // Note: |
| 8353 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" |
| 8354 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS |
| 8355 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS |
| 8356 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is |
| 8357 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + |
| 8358 | // C)". |
| 8359 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8360 | Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); |
| 8361 | Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); |
| 8362 | if (!LDiff || !RDiff || *LDiff != *RDiff) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8363 | return false; |
| 8364 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8365 | if (LDiff->isMinValue()) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8366 | return true; |
| 8367 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8368 | APInt FoundRHSLimit; |
| 8369 | |
| 8370 | if (Pred == CmpInst::ICMP_ULT) { |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8371 | FoundRHSLimit = -(*RDiff); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8372 | } else { |
| 8373 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8374 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8375 | } |
| 8376 | |
| 8377 | // Try to prove (1) or (2), as needed. |
| 8378 | return isLoopEntryGuardedByCond(L, Pred, FoundRHS, |
| 8379 | getConstant(FoundRHSLimit)); |
| 8380 | } |
| 8381 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8382 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 8383 | const SCEV *LHS, const SCEV *RHS, |
| 8384 | const SCEV *FoundLHS, |
| 8385 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8386 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8387 | return true; |
| 8388 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8389 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8390 | return true; |
| 8391 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8392 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8393 | FoundLHS, FoundRHS) || |
| 8394 | // ~x < ~y --> x > y |
| 8395 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8396 | getNotSCEV(FoundRHS), |
| 8397 | getNotSCEV(FoundLHS)); |
| 8398 | } |
| 8399 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8400 | |
| 8401 | /// If Expr computes ~A, return A else return nullptr |
| 8402 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 8403 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8404 | if (!Add || Add->getNumOperands() != 2 || |
| 8405 | !Add->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8406 | return nullptr; |
| 8407 | |
| 8408 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8409 | if (!AddRHS || AddRHS->getNumOperands() != 2 || |
| 8410 | !AddRHS->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8411 | return nullptr; |
| 8412 | |
| 8413 | return AddRHS->getOperand(1); |
| 8414 | } |
| 8415 | |
| 8416 | |
| 8417 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 8418 | template<typename MaxExprType> |
| 8419 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 8420 | const SCEV *Candidate) { |
| 8421 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 8422 | if (!MaxExpr) return false; |
| 8423 | |
Sanjoy Das | 347d272 | 2015-12-01 07:49:27 +0000 | [diff] [blame] | 8424 | return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8425 | } |
| 8426 | |
| 8427 | |
| 8428 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 8429 | template<typename MaxExprType> |
| 8430 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 8431 | const SCEV *MaybeMinExpr, |
| 8432 | const SCEV *Candidate) { |
| 8433 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 8434 | if (!MaybeMaxExpr) |
| 8435 | return false; |
| 8436 | |
| 8437 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 8438 | } |
| 8439 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8440 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 8441 | ICmpInst::Predicate Pred, |
| 8442 | const SCEV *LHS, const SCEV *RHS) { |
| 8443 | |
| 8444 | // If both sides are affine addrecs for the same loop, with equal |
| 8445 | // steps, and we know the recurrences don't wrap, then we only |
| 8446 | // need to check the predicate on the starting values. |
| 8447 | |
| 8448 | if (!ICmpInst::isRelational(Pred)) |
| 8449 | return false; |
| 8450 | |
| 8451 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8452 | if (!LAR) |
| 8453 | return false; |
| 8454 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 8455 | if (!RAR) |
| 8456 | return false; |
| 8457 | if (LAR->getLoop() != RAR->getLoop()) |
| 8458 | return false; |
| 8459 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 8460 | return false; |
| 8461 | |
| 8462 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 8463 | return false; |
| 8464 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 8465 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 8466 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 8467 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8468 | return false; |
| 8469 | |
| 8470 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 8471 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8472 | |
| 8473 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 8474 | /// expression? |
| 8475 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 8476 | ICmpInst::Predicate Pred, |
| 8477 | const SCEV *LHS, const SCEV *RHS) { |
| 8478 | switch (Pred) { |
| 8479 | default: |
| 8480 | return false; |
| 8481 | |
| 8482 | case ICmpInst::ICMP_SGE: |
| 8483 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 8484 | LLVM_FALLTHROUGH; |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8485 | case ICmpInst::ICMP_SLE: |
| 8486 | return |
| 8487 | // min(A, ...) <= A |
| 8488 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 8489 | // A <= max(A, ...) |
| 8490 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 8491 | |
| 8492 | case ICmpInst::ICMP_UGE: |
| 8493 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 8494 | LLVM_FALLTHROUGH; |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8495 | case ICmpInst::ICMP_ULE: |
| 8496 | return |
| 8497 | // min(A, ...) <= A |
| 8498 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 8499 | // A <= max(A, ...) |
| 8500 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 8501 | } |
| 8502 | |
| 8503 | llvm_unreachable("covered switch fell through?!"); |
| 8504 | } |
| 8505 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8506 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8507 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 8508 | const SCEV *LHS, const SCEV *RHS, |
| 8509 | const SCEV *FoundLHS, |
| 8510 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8511 | auto IsKnownPredicateFull = |
| 8512 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8513 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || |
Sanjoy Das | 1123148 | 2015-10-22 19:57:29 +0000 | [diff] [blame] | 8514 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 8515 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || |
| 8516 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8517 | }; |
| 8518 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8519 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8520 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 8521 | case ICmpInst::ICMP_EQ: |
| 8522 | case ICmpInst::ICMP_NE: |
| 8523 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 8524 | return true; |
| 8525 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8526 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8527 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8528 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 8529 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8530 | return true; |
| 8531 | break; |
| 8532 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8533 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8534 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 8535 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8536 | return true; |
| 8537 | break; |
| 8538 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8539 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8540 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 8541 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8542 | return true; |
| 8543 | break; |
| 8544 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8545 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8546 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 8547 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8548 | return true; |
| 8549 | break; |
| 8550 | } |
| 8551 | |
| 8552 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8553 | } |
| 8554 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8555 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 8556 | const SCEV *LHS, |
| 8557 | const SCEV *RHS, |
| 8558 | const SCEV *FoundLHS, |
| 8559 | const SCEV *FoundRHS) { |
| 8560 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 8561 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 8562 | // reduce the compile time impact of this optimization. |
| 8563 | return false; |
| 8564 | |
Sanjoy Das | a7d9ec8 | 2016-07-23 00:54:36 +0000 | [diff] [blame] | 8565 | Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); |
Sanjoy Das | 095f5b2 | 2016-07-22 20:47:55 +0000 | [diff] [blame] | 8566 | if (!Addend) |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8567 | return false; |
| 8568 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8569 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8570 | |
| 8571 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 8572 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 8573 | ConstantRange FoundLHSRange = |
| 8574 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 8575 | |
Sanjoy Das | 095f5b2 | 2016-07-22 20:47:55 +0000 | [diff] [blame] | 8576 | // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: |
| 8577 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8578 | |
| 8579 | // We can also compute the range of values for `LHS` that satisfy the |
| 8580 | // consequent, "`LHS` `Pred` `RHS`": |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8581 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8582 | ConstantRange SatisfyingLHSRange = |
| 8583 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 8584 | |
| 8585 | // The antecedent implies the consequent if every value of `LHS` that |
| 8586 | // satisfies the antecedent also satisfies the consequent. |
| 8587 | return SatisfyingLHSRange.contains(LHSRange); |
| 8588 | } |
| 8589 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8590 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 8591 | bool IsSigned, bool NoWrap) { |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8592 | assert(isKnownPositive(Stride) && "Positive stride expected!"); |
| 8593 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8594 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8595 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8596 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8597 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8598 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8599 | if (IsSigned) { |
| 8600 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 8601 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 8602 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8603 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8604 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8605 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 8606 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 8607 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8608 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8609 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 8610 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 8611 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8612 | .getUnsignedMax(); |
| 8613 | |
| 8614 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 8615 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 8616 | } |
| 8617 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8618 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 8619 | bool IsSigned, bool NoWrap) { |
| 8620 | if (NoWrap) return false; |
| 8621 | |
| 8622 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8623 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8624 | |
| 8625 | if (IsSigned) { |
| 8626 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 8627 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 8628 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8629 | .getSignedMax(); |
| 8630 | |
| 8631 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 8632 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 8633 | } |
| 8634 | |
| 8635 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 8636 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 8637 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8638 | .getUnsignedMax(); |
| 8639 | |
| 8640 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 8641 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 8642 | } |
| 8643 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8644 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8645 | bool Equality) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8646 | const SCEV *One = getOne(Step->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8647 | Delta = Equality ? getAddExpr(Delta, Step) |
| 8648 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 8649 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8650 | } |
| 8651 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8652 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 8653 | ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8654 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8655 | bool ControlsExit, bool AllowPredicates) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8656 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8657 | // We handle only IV < Invariant |
| 8658 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 8659 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8660 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8661 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8662 | bool PredicatedIV = false; |
| 8663 | |
| 8664 | if (!IV && AllowPredicates) { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8665 | // Try to make this an AddRec using runtime tests, in the first X |
| 8666 | // iterations of this loop, where X is the SCEV expression found by the |
| 8667 | // algorithm below. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8668 | IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8669 | PredicatedIV = true; |
| 8670 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8671 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8672 | // Avoid weird loops |
| 8673 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8674 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8675 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8676 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8677 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8678 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8679 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8680 | |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8681 | bool PositiveStride = isKnownPositive(Stride); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8682 | |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8683 | // Avoid negative or zero stride values. |
| 8684 | if (!PositiveStride) { |
| 8685 | // We can compute the correct backedge taken count for loops with unknown |
| 8686 | // strides if we can prove that the loop is not an infinite loop with side |
| 8687 | // effects. Here's the loop structure we are trying to handle - |
| 8688 | // |
| 8689 | // i = start |
| 8690 | // do { |
| 8691 | // A[i] = i; |
| 8692 | // i += s; |
| 8693 | // } while (i < end); |
| 8694 | // |
| 8695 | // The backedge taken count for such loops is evaluated as - |
| 8696 | // (max(end, start + stride) - start - 1) /u stride |
| 8697 | // |
| 8698 | // The additional preconditions that we need to check to prove correctness |
| 8699 | // of the above formula is as follows - |
| 8700 | // |
| 8701 | // a) IV is either nuw or nsw depending upon signedness (indicated by the |
| 8702 | // NoWrap flag). |
| 8703 | // b) loop is single exit with no side effects. |
| 8704 | // |
| 8705 | // |
| 8706 | // Precondition a) implies that if the stride is negative, this is a single |
| 8707 | // trip loop. The backedge taken count formula reduces to zero in this case. |
| 8708 | // |
| 8709 | // Precondition b) implies that the unknown stride cannot be zero otherwise |
| 8710 | // we have UB. |
| 8711 | // |
| 8712 | // The positive stride case is the same as isKnownPositive(Stride) returning |
| 8713 | // true (original behavior of the function). |
| 8714 | // |
| 8715 | // We want to make sure that the stride is truly unknown as there are edge |
| 8716 | // cases where ScalarEvolution propagates no wrap flags to the |
| 8717 | // post-increment/decrement IV even though the increment/decrement operation |
| 8718 | // itself is wrapping. The computed backedge taken count may be wrong in |
| 8719 | // such cases. This is prevented by checking that the stride is not known to |
| 8720 | // be either positive or non-positive. For example, no wrap flags are |
| 8721 | // propagated to the post-increment IV of this loop with a trip count of 2 - |
| 8722 | // |
| 8723 | // unsigned char i; |
| 8724 | // for(i=127; i<128; i+=129) |
| 8725 | // A[i] = i; |
| 8726 | // |
| 8727 | if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || |
| 8728 | !loopHasNoSideEffects(L)) |
| 8729 | return getCouldNotCompute(); |
| 8730 | |
| 8731 | } else if (!Stride->isOne() && |
| 8732 | doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 8733 | // Avoid proven overflow cases: this will ensure that the backedge taken |
| 8734 | // count will not generate any unsigned overflow. Relaxed no-overflow |
| 8735 | // conditions exploit NoWrapFlags, allowing to optimize in presence of |
| 8736 | // undefined behaviors like the case of C language. |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8737 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8738 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8739 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 8740 | : ICmpInst::ICMP_ULT; |
| 8741 | const SCEV *Start = IV->getStart(); |
| 8742 | const SCEV *End = RHS; |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8743 | // If the backedge is taken at least once, then it will be taken |
| 8744 | // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start |
| 8745 | // is the LHS value of the less-than comparison the first time it is evaluated |
| 8746 | // and End is the RHS. |
| 8747 | const SCEV *BECountIfBackedgeTaken = |
| 8748 | computeBECount(getMinusSCEV(End, Start), Stride, false); |
| 8749 | // If the loop entry is guarded by the result of the backedge test of the |
| 8750 | // first loop iteration, then we know the backedge will be taken at least |
| 8751 | // once and so the backedge taken count is as above. If not then we use the |
| 8752 | // expression (max(End,Start)-Start)/Stride to describe the backedge count, |
| 8753 | // as if the backedge is taken at least once max(End,Start) is End and so the |
| 8754 | // result is as above, and if not max(End,Start) is Start so we get a backedge |
| 8755 | // count of zero. |
| 8756 | const SCEV *BECount; |
| 8757 | if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) |
| 8758 | BECount = BECountIfBackedgeTaken; |
| 8759 | else { |
Sanjoy Das | e8fd956 | 2016-06-18 04:38:31 +0000 | [diff] [blame] | 8760 | End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8761 | BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
| 8762 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8763 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 8764 | const SCEV *MaxBECount; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8765 | bool MaxOrZero = false; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8766 | if (isa<SCEVConstant>(BECount)) |
| 8767 | MaxBECount = BECount; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8768 | else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8769 | // If we know exactly how many times the backedge will be taken if it's |
| 8770 | // taken at least once, then the backedge count will either be that or |
| 8771 | // zero. |
| 8772 | MaxBECount = BECountIfBackedgeTaken; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8773 | MaxOrZero = true; |
| 8774 | } else { |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8775 | // Calculate the maximum backedge count based on the range of values |
| 8776 | // permitted by Start, End, and Stride. |
| 8777 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 8778 | : getUnsignedRange(Start).getUnsignedMin(); |
| 8779 | |
| 8780 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8781 | |
| 8782 | APInt StrideForMaxBECount; |
| 8783 | |
| 8784 | if (PositiveStride) |
| 8785 | StrideForMaxBECount = |
| 8786 | IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8787 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8788 | else |
| 8789 | // Using a stride of 1 is safe when computing max backedge taken count for |
| 8790 | // a loop with unknown stride. |
| 8791 | StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); |
| 8792 | |
| 8793 | APInt Limit = |
| 8794 | IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) |
| 8795 | : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); |
| 8796 | |
| 8797 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 8798 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 8799 | // is zero, leading to a zero maximum backedge taken count. |
| 8800 | APInt MaxEnd = |
| 8801 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 8802 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 8803 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8804 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8805 | getConstant(StrideForMaxBECount), false); |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8806 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8807 | |
| 8808 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8809 | MaxBECount = BECount; |
| 8810 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8811 | return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8812 | } |
| 8813 | |
| 8814 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 8815 | ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8816 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8817 | bool ControlsExit, bool AllowPredicates) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8818 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8819 | // We handle only IV > Invariant |
| 8820 | if (!isLoopInvariant(RHS, L)) |
| 8821 | return getCouldNotCompute(); |
| 8822 | |
| 8823 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8824 | if (!IV && AllowPredicates) |
| 8825 | // Try to make this an AddRec using runtime tests, in the first X |
| 8826 | // iterations of this loop, where X is the SCEV expression found by the |
| 8827 | // algorithm below. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8828 | IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8829 | |
| 8830 | // Avoid weird loops |
| 8831 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8832 | return getCouldNotCompute(); |
| 8833 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8834 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8835 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 8836 | |
| 8837 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 8838 | |
| 8839 | // Avoid negative or zero stride values |
| 8840 | if (!isKnownPositive(Stride)) |
| 8841 | return getCouldNotCompute(); |
| 8842 | |
| 8843 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8844 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8845 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8846 | // behaviors like the case of C language. |
| 8847 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 8848 | return getCouldNotCompute(); |
| 8849 | |
| 8850 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 8851 | : ICmpInst::ICMP_UGT; |
| 8852 | |
| 8853 | const SCEV *Start = IV->getStart(); |
| 8854 | const SCEV *End = RHS; |
Sanjoy Das | e8fd956 | 2016-06-18 04:38:31 +0000 | [diff] [blame] | 8855 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) |
| 8856 | End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8857 | |
| 8858 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 8859 | |
| 8860 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 8861 | : getUnsignedRange(Start).getUnsignedMax(); |
| 8862 | |
| 8863 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8864 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8865 | |
| 8866 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8867 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 8868 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 8869 | |
| 8870 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 8871 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 8872 | // is zero, leading to a zero maximum backedge taken count. |
| 8873 | APInt MinEnd = |
| 8874 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 8875 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 8876 | |
| 8877 | |
| 8878 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 8879 | if (isa<SCEVConstant>(BECount)) |
| 8880 | MaxBECount = BECount; |
| 8881 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8882 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8883 | getConstant(MinStride), false); |
| 8884 | |
| 8885 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8886 | MaxBECount = BECount; |
| 8887 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8888 | return ExitLimit(BECount, MaxBECount, false, Predicates); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8889 | } |
| 8890 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 8891 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8892 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8893 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8894 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8895 | |
| 8896 | // 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] | 8897 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 8898 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8899 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8900 | Operands[0] = SE.getZero(SC->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8901 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 8902 | getNoWrapFlags(FlagNW)); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 8903 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8904 | return ShiftedAddRec->getNumIterationsInRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8905 | Range.subtract(SC->getAPInt()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8906 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8907 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8908 | } |
| 8909 | |
| 8910 | // The only time we can solve this is when we have all constant indices. |
| 8911 | // Otherwise, we cannot determine the overflow conditions. |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 8912 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 8913 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8914 | |
| 8915 | // Okay at this point we know that all elements of the chrec are constants and |
| 8916 | // that the start element is zero. |
| 8917 | |
| 8918 | // First check to see if the range contains zero. If not, the first |
| 8919 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 8920 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8921 | if (!Range.contains(APInt(BitWidth, 0))) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8922 | return SE.getZero(getType()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8923 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8924 | if (isAffine()) { |
| 8925 | // If this is an affine expression then we have this situation: |
| 8926 | // Solve {0,+,A} in Range === Ax in Range |
| 8927 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8928 | // We know that zero is in the range. If A is positive then we know that |
| 8929 | // the upper value of the range must be the first possible exit value. |
| 8930 | // If A is negative then the lower of the range is the last possible loop |
| 8931 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8932 | APInt One(BitWidth,1); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8933 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8934 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8935 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8936 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 8937 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8938 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8939 | |
| 8940 | // Evaluate at the exit value. If we really did fall out of the valid |
| 8941 | // range, then we computed our trip count, otherwise wrap around or other |
| 8942 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8943 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8944 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8945 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8946 | |
| 8947 | // 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] | 8948 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8949 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8950 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8951 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8952 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8953 | } else if (isQuadratic()) { |
| 8954 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 8955 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 8956 | // terms of figuring out when zero is crossed, instead of when |
| 8957 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8958 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8959 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Sanjoy Das | 54e6a21 | 2016-10-02 00:09:45 +0000 | [diff] [blame] | 8960 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8961 | |
| 8962 | // Next, solve the constructed addrec |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8963 | if (auto Roots = |
| 8964 | SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 8965 | const SCEVConstant *R1 = Roots->first; |
| 8966 | const SCEVConstant *R2 = Roots->second; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8967 | // Pick the smallest positive root value. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8968 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 8969 | ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 8970 | if (!CB->getZExtValue()) |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8971 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8972 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8973 | // Make sure the root is not off by one. The returned iteration should |
| 8974 | // not be in the range, but the previous one should be. When solving |
| 8975 | // for "X*X < 5", for example, we should not return a root of 2. |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8976 | ConstantInt *R1Val = |
| 8977 | EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8978 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8979 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8980 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8981 | ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8982 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8983 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8984 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8985 | return SE.getConstant(NextVal); |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8986 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8987 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8988 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8989 | // If R1 was not in the range, then it is a good return value. Make |
| 8990 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8991 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8992 | ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8993 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8994 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8995 | return R1; |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8996 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8997 | } |
| 8998 | } |
| 8999 | } |
| 9000 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 9001 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9002 | } |
| 9003 | |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 9004 | // Return true when S contains at least an undef value. |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 9005 | static inline bool containsUndefs(const SCEV *S) { |
| 9006 | return SCEVExprContains(S, [](const SCEV *S) { |
| 9007 | if (const auto *SU = dyn_cast<SCEVUnknown>(S)) |
| 9008 | return isa<UndefValue>(SU->getValue()); |
| 9009 | else if (const auto *SC = dyn_cast<SCEVConstant>(S)) |
| 9010 | return isa<UndefValue>(SC->getValue()); |
| 9011 | return false; |
| 9012 | }); |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 9013 | } |
| 9014 | |
| 9015 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9016 | // Collect all steps of SCEV expressions. |
| 9017 | struct SCEVCollectStrides { |
| 9018 | ScalarEvolution &SE; |
| 9019 | SmallVectorImpl<const SCEV *> &Strides; |
| 9020 | |
| 9021 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 9022 | : SE(SE), Strides(S) {} |
| 9023 | |
| 9024 | bool follow(const SCEV *S) { |
| 9025 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 9026 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 9027 | return true; |
| 9028 | } |
| 9029 | bool isDone() const { return false; } |
| 9030 | }; |
| 9031 | |
| 9032 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 9033 | struct SCEVCollectTerms { |
| 9034 | SmallVectorImpl<const SCEV *> &Terms; |
| 9035 | |
| 9036 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 9037 | : Terms(T) {} |
| 9038 | |
| 9039 | bool follow(const SCEV *S) { |
Tobias Grosser | 2bbec0e | 2016-10-17 11:56:26 +0000 | [diff] [blame] | 9040 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || |
| 9041 | isa<SCEVSignExtendExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 9042 | if (!containsUndefs(S)) |
| 9043 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9044 | |
| 9045 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9046 | return false; |
| 9047 | } |
| 9048 | |
| 9049 | // Keep looking. |
| 9050 | return true; |
| 9051 | } |
| 9052 | bool isDone() const { return false; } |
| 9053 | }; |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9054 | |
| 9055 | // Check if a SCEV contains an AddRecExpr. |
| 9056 | struct SCEVHasAddRec { |
| 9057 | bool &ContainsAddRec; |
| 9058 | |
| 9059 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { |
| 9060 | ContainsAddRec = false; |
| 9061 | } |
| 9062 | |
| 9063 | bool follow(const SCEV *S) { |
| 9064 | if (isa<SCEVAddRecExpr>(S)) { |
| 9065 | ContainsAddRec = true; |
| 9066 | |
| 9067 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9068 | return false; |
| 9069 | } |
| 9070 | |
| 9071 | // Keep looking. |
| 9072 | return true; |
| 9073 | } |
| 9074 | bool isDone() const { return false; } |
| 9075 | }; |
| 9076 | |
| 9077 | // Find factors that are multiplied with an expression that (possibly as a |
| 9078 | // subexpression) contains an AddRecExpr. In the expression: |
| 9079 | // |
| 9080 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) |
| 9081 | // |
| 9082 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" |
| 9083 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size |
| 9084 | // parameters as they form a product with an induction variable. |
| 9085 | // |
| 9086 | // This collector expects all array size parameters to be in the same MulExpr. |
| 9087 | // It might be necessary to later add support for collecting parameters that are |
| 9088 | // spread over different nested MulExpr. |
| 9089 | struct SCEVCollectAddRecMultiplies { |
| 9090 | SmallVectorImpl<const SCEV *> &Terms; |
| 9091 | ScalarEvolution &SE; |
| 9092 | |
| 9093 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) |
| 9094 | : Terms(T), SE(SE) {} |
| 9095 | |
| 9096 | bool follow(const SCEV *S) { |
| 9097 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { |
| 9098 | bool HasAddRec = false; |
| 9099 | SmallVector<const SCEV *, 0> Operands; |
| 9100 | for (auto Op : Mul->operands()) { |
| 9101 | if (isa<SCEVUnknown>(Op)) { |
| 9102 | Operands.push_back(Op); |
| 9103 | } else { |
| 9104 | bool ContainsAddRec; |
| 9105 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); |
| 9106 | visitAll(Op, ContiansAddRec); |
| 9107 | HasAddRec |= ContainsAddRec; |
| 9108 | } |
| 9109 | } |
| 9110 | if (Operands.size() == 0) |
| 9111 | return true; |
| 9112 | |
| 9113 | if (!HasAddRec) |
| 9114 | return false; |
| 9115 | |
| 9116 | Terms.push_back(SE.getMulExpr(Operands)); |
| 9117 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9118 | return false; |
| 9119 | } |
| 9120 | |
| 9121 | // Keep looking. |
| 9122 | return true; |
| 9123 | } |
| 9124 | bool isDone() const { return false; } |
| 9125 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 9126 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9127 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9128 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in |
| 9129 | /// two places: |
| 9130 | /// 1) The strides of AddRec expressions. |
| 9131 | /// 2) Unknowns that are multiplied with AddRec expressions. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9132 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 9133 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9134 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9135 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 9136 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9137 | |
| 9138 | DEBUG({ |
| 9139 | dbgs() << "Strides:\n"; |
| 9140 | for (const SCEV *S : Strides) |
| 9141 | dbgs() << *S << "\n"; |
| 9142 | }); |
| 9143 | |
| 9144 | for (const SCEV *S : Strides) { |
| 9145 | SCEVCollectTerms TermCollector(Terms); |
| 9146 | visitAll(S, TermCollector); |
| 9147 | } |
| 9148 | |
| 9149 | DEBUG({ |
| 9150 | dbgs() << "Terms:\n"; |
| 9151 | for (const SCEV *T : Terms) |
| 9152 | dbgs() << *T << "\n"; |
| 9153 | }); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9154 | |
| 9155 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); |
| 9156 | visitAll(Expr, MulCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9157 | } |
| 9158 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9159 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9160 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 9161 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9162 | int Last = Terms.size() - 1; |
| 9163 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9164 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9165 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9166 | if (Last == 0) { |
| 9167 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9168 | SmallVector<const SCEV *, 2> Qs; |
| 9169 | for (const SCEV *Op : M->operands()) |
| 9170 | if (!isa<SCEVConstant>(Op)) |
| 9171 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9172 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9173 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9174 | } |
| 9175 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9176 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9177 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9178 | } |
| 9179 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9180 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9181 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 9182 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9183 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9184 | |
| 9185 | // Bail out when GCD does not evenly divide one of the terms. |
| 9186 | if (!R->isZero()) |
| 9187 | return false; |
| 9188 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9189 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9190 | } |
| 9191 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 9192 | // Remove all SCEVConstants. |
David Majnemer | c700490 | 2016-08-12 04:32:37 +0000 | [diff] [blame] | 9193 | Terms.erase( |
| 9194 | remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), |
| 9195 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9196 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9197 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9198 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 9199 | return false; |
| 9200 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9201 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9202 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9203 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9204 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9205 | |
| 9206 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 9207 | static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9208 | for (const SCEV *T : Terms) |
Sanjoy Das | 0ae390a | 2016-11-10 06:33:54 +0000 | [diff] [blame] | 9209 | if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9210 | return true; |
| 9211 | return false; |
| 9212 | } |
| 9213 | |
| 9214 | // Return the number of product terms in S. |
| 9215 | static inline int numberOfTerms(const SCEV *S) { |
| 9216 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 9217 | return Expr->getNumOperands(); |
| 9218 | return 1; |
| 9219 | } |
| 9220 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9221 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 9222 | if (isa<SCEVConstant>(T)) |
| 9223 | return nullptr; |
| 9224 | |
| 9225 | if (isa<SCEVUnknown>(T)) |
| 9226 | return T; |
| 9227 | |
| 9228 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 9229 | SmallVector<const SCEV *, 2> Factors; |
| 9230 | for (const SCEV *Op : M->operands()) |
| 9231 | if (!isa<SCEVConstant>(Op)) |
| 9232 | Factors.push_back(Op); |
| 9233 | |
| 9234 | return SE.getMulExpr(Factors); |
| 9235 | } |
| 9236 | |
| 9237 | return T; |
| 9238 | } |
| 9239 | |
| 9240 | /// Return the size of an element read or written by Inst. |
| 9241 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 9242 | Type *Ty; |
| 9243 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 9244 | Ty = Store->getValueOperand()->getType(); |
| 9245 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 9246 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9247 | else |
| 9248 | return nullptr; |
| 9249 | |
| 9250 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 9251 | return getSizeOfExpr(ETy, Ty); |
| 9252 | } |
| 9253 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9254 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 9255 | SmallVectorImpl<const SCEV *> &Sizes, |
| 9256 | const SCEV *ElementSize) const { |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 9257 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9258 | return; |
| 9259 | |
| 9260 | // Early return when Terms do not contain parameters: we do not delinearize |
| 9261 | // non parametric SCEVs. |
| 9262 | if (!containsParameters(Terms)) |
| 9263 | return; |
| 9264 | |
| 9265 | DEBUG({ |
| 9266 | dbgs() << "Terms:\n"; |
| 9267 | for (const SCEV *T : Terms) |
| 9268 | dbgs() << *T << "\n"; |
| 9269 | }); |
| 9270 | |
| 9271 | // Remove duplicates. |
| 9272 | std::sort(Terms.begin(), Terms.end()); |
| 9273 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 9274 | |
| 9275 | // Put larger terms first. |
| 9276 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 9277 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 9278 | }); |
| 9279 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9280 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9281 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9282 | // Try to divide all terms by the element size. If term is not divisible by |
| 9283 | // element size, proceed with the original term. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9284 | for (const SCEV *&Term : Terms) { |
| 9285 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9286 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9287 | if (!Q->isZero()) |
| 9288 | Term = Q; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9289 | } |
| 9290 | |
| 9291 | SmallVector<const SCEV *, 4> NewTerms; |
| 9292 | |
| 9293 | // Remove constant factors. |
| 9294 | for (const SCEV *T : Terms) |
| 9295 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 9296 | NewTerms.push_back(NewT); |
| 9297 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9298 | DEBUG({ |
| 9299 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9300 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9301 | dbgs() << *T << "\n"; |
| 9302 | }); |
| 9303 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9304 | if (NewTerms.empty() || |
| 9305 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9306 | Sizes.clear(); |
| 9307 | return; |
| 9308 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9309 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9310 | // The last element to be pushed into Sizes is the size of an element. |
| 9311 | Sizes.push_back(ElementSize); |
| 9312 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9313 | DEBUG({ |
| 9314 | dbgs() << "Sizes:\n"; |
| 9315 | for (const SCEV *S : Sizes) |
| 9316 | dbgs() << *S << "\n"; |
| 9317 | }); |
| 9318 | } |
| 9319 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9320 | void ScalarEvolution::computeAccessFunctions( |
| 9321 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 9322 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9323 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9324 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9325 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9326 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9327 | |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 9328 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9329 | if (!AR->isAffine()) |
| 9330 | return; |
| 9331 | |
| 9332 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9333 | int Last = Sizes.size() - 1; |
| 9334 | for (int i = Last; i >= 0; i--) { |
| 9335 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9336 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9337 | |
| 9338 | DEBUG({ |
| 9339 | dbgs() << "Res: " << *Res << "\n"; |
| 9340 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 9341 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 9342 | dbgs() << "Quotient: " << *Q << "\n"; |
| 9343 | dbgs() << "Remainder: " << *R << "\n"; |
| 9344 | }); |
| 9345 | |
| 9346 | Res = Q; |
| 9347 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9348 | // Do not record the last subscript corresponding to the size of elements in |
| 9349 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9350 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9351 | |
| 9352 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9353 | if (isa<SCEVAddRecExpr>(R)) { |
| 9354 | Subscripts.clear(); |
| 9355 | Sizes.clear(); |
| 9356 | return; |
| 9357 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9358 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9359 | continue; |
| 9360 | } |
| 9361 | |
| 9362 | // Record the access function for the current subscript. |
| 9363 | Subscripts.push_back(R); |
| 9364 | } |
| 9365 | |
| 9366 | // Also push in last position the remainder of the last division: it will be |
| 9367 | // the access function of the innermost dimension. |
| 9368 | Subscripts.push_back(Res); |
| 9369 | |
| 9370 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 9371 | |
| 9372 | DEBUG({ |
| 9373 | dbgs() << "Subscripts:\n"; |
| 9374 | for (const SCEV *S : Subscripts) |
| 9375 | dbgs() << *S << "\n"; |
| 9376 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9377 | } |
| 9378 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9379 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 9380 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9381 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 9382 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 9383 | /// expressions in the stride and base of a SCEV corresponding to the |
| 9384 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 9385 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 9386 | /// |
| 9387 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 9388 | /// |
| 9389 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 9390 | /// |
| 9391 | /// for (long i = 0; i < n; i++) |
| 9392 | /// for (long j = 0; j < m; j++) |
| 9393 | /// for (long k = 0; k < o; k++) |
| 9394 | /// A[i][j][k] = 1.0; |
| 9395 | /// } |
| 9396 | /// |
| 9397 | /// the delinearization input is the following AddRec SCEV: |
| 9398 | /// |
| 9399 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 9400 | /// |
| 9401 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 9402 | /// because it appears as an offset that does not divide any of the strides in |
| 9403 | /// the loops: |
| 9404 | /// |
| 9405 | /// CHECK: Base offset: %A |
| 9406 | /// |
| 9407 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 9408 | /// the array as these are the multiples by which the strides are happening: |
| 9409 | /// |
| 9410 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 9411 | /// |
| 9412 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 9413 | /// no strides that would help identifying the size of the last dimension: when |
| 9414 | /// the array has been statically allocated, one could compute the size of that |
| 9415 | /// dimension by dividing the overall size of the array by the size of the known |
| 9416 | /// dimensions: %m * %o * 8. |
| 9417 | /// |
| 9418 | /// Finally delinearize provides the access functions for the array reference |
| 9419 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 9420 | /// |
| 9421 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 9422 | /// |
| 9423 | /// The testcases are checking the output of a function pass: |
| 9424 | /// DelinearizationPass that walks through all loads and stores of a function |
| 9425 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 9426 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 9427 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9428 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9429 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 9430 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9431 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9432 | // First step: collect parametric terms. |
| 9433 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9434 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9435 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9436 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9437 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9438 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9439 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9440 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9441 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9442 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9443 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9444 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9445 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9446 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9447 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9448 | if (Subscripts.empty()) |
| 9449 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9450 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9451 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9452 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9453 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 9454 | for (const SCEV *S : Sizes) |
| 9455 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9456 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 9457 | dbgs() << "\nArrayRef"; |
| 9458 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9459 | dbgs() << "[" << *S << "]"; |
| 9460 | dbgs() << "\n"; |
| 9461 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9462 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9463 | |
| 9464 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9465 | // SCEVCallbackVH Class Implementation |
| 9466 | //===----------------------------------------------------------------------===// |
| 9467 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9468 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9469 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9470 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 9471 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9472 | SE->eraseValueFromMap(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9473 | // this now dangles! |
| 9474 | } |
| 9475 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 9476 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9477 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 9478 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9479 | // Forget all the expressions associated with users of the old value, |
| 9480 | // so that future queries will recompute the expressions using the new |
| 9481 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9482 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9483 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9484 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9485 | while (!Worklist.empty()) { |
| 9486 | User *U = Worklist.pop_back_val(); |
| 9487 | // Deleting the Old value will cause this to dangle. Postpone |
| 9488 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9489 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9490 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 9491 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9492 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9493 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 9494 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9495 | SE->eraseValueFromMap(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9496 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9497 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9498 | // Delete the Old value. |
| 9499 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 9500 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9501 | SE->eraseValueFromMap(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9502 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9503 | } |
| 9504 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9505 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9506 | : CallbackVH(V), SE(se) {} |
| 9507 | |
| 9508 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9509 | // ScalarEvolution Class Implementation |
| 9510 | //===----------------------------------------------------------------------===// |
| 9511 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9512 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 9513 | AssumptionCache &AC, DominatorTree &DT, |
| 9514 | LoopInfo &LI) |
| 9515 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9516 | CouldNotCompute(new SCEVCouldNotCompute()), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9517 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
| 9518 | ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9519 | FirstUnknown(nullptr) { |
| 9520 | |
| 9521 | // To use guards for proving predicates, we need to scan every instruction in |
| 9522 | // relevant basic blocks, and not just terminators. Doing this is a waste of |
| 9523 | // time if the IR does not actually contain any calls to |
| 9524 | // @llvm.experimental.guard, so do a quick check and remember this beforehand. |
| 9525 | // |
| 9526 | // This pessimizes the case where a pass that preserves ScalarEvolution wants |
| 9527 | // to _add_ guards to the module when there weren't any before, and wants |
| 9528 | // ScalarEvolution to optimize based on those guards. For now we prefer to be |
| 9529 | // efficient in lieu of being smart in that rather obscure case. |
| 9530 | |
| 9531 | auto *GuardDecl = F.getParent()->getFunction( |
| 9532 | Intrinsic::getName(Intrinsic::experimental_guard)); |
| 9533 | HasGuards = GuardDecl && !GuardDecl->use_empty(); |
| 9534 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9535 | |
| 9536 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 9537 | : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9538 | LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9539 | ValueExprMap(std::move(Arg.ValueExprMap)), |
Sanjoy Das | db93375 | 2016-09-27 18:01:38 +0000 | [diff] [blame] | 9540 | PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9541 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9542 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9543 | PredicatedBackedgeTakenCounts( |
| 9544 | std::move(Arg.PredicatedBackedgeTakenCounts)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9545 | ConstantEvolutionLoopExitValue( |
| 9546 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 9547 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 9548 | LoopDispositions(std::move(Arg.LoopDispositions)), |
Sanjoy Das | 5cb11b6 | 2016-09-26 02:44:10 +0000 | [diff] [blame] | 9549 | LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), |
Chandler Carruth | 68abda5 | 2016-09-26 04:49:58 +0000 | [diff] [blame] | 9550 | BlockDispositions(std::move(Arg.BlockDispositions)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9551 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 9552 | SignedRanges(std::move(Arg.SignedRanges)), |
| 9553 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9554 | UniquePreds(std::move(Arg.UniquePreds)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9555 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 9556 | FirstUnknown(Arg.FirstUnknown) { |
| 9557 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9558 | } |
| 9559 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9560 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9561 | // Iterate through all the SCEVUnknown instances and call their |
| 9562 | // destructors, so that they release their references to their values. |
Naomi Musgrave | f90c1be | 2015-09-16 23:46:40 +0000 | [diff] [blame] | 9563 | for (SCEVUnknown *U = FirstUnknown; U;) { |
| 9564 | SCEVUnknown *Tmp = U; |
| 9565 | U = U->Next; |
| 9566 | Tmp->~SCEVUnknown(); |
| 9567 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 9568 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9569 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9570 | ExprValueMap.clear(); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 9571 | ValueExprMap.clear(); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9572 | HasRecMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9573 | |
| 9574 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 9575 | // that a loop had multiple computable exits. |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9576 | for (auto &BTCI : BackedgeTakenCounts) |
| 9577 | BTCI.second.clear(); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9578 | for (auto &BTCI : PredicatedBackedgeTakenCounts) |
| 9579 | BTCI.second.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9580 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 9581 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 9582 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9583 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 9584 | } |
| 9585 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9586 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9587 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9588 | } |
| 9589 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9590 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9591 | const Loop *L) { |
| 9592 | // Print all inner loops first |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 9593 | for (Loop *I : *L) |
| 9594 | PrintLoopInfo(OS, SE, I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9595 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9596 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9597 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9598 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9599 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9600 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9601 | L->getExitBlocks(ExitBlocks); |
| 9602 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 9603 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9604 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9605 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 9606 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9607 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9608 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9609 | } |
| 9610 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9611 | OS << "\n" |
| 9612 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9613 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9614 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9615 | |
| 9616 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 9617 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 9618 | if (SE->isBackedgeTakenCountMaxOrZero(L)) |
| 9619 | OS << ", actual taken count either this or zero."; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9620 | } else { |
| 9621 | OS << "Unpredictable max backedge-taken count. "; |
| 9622 | } |
| 9623 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9624 | OS << "\n" |
| 9625 | "Loop "; |
| 9626 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9627 | OS << ": "; |
| 9628 | |
| 9629 | SCEVUnionPredicate Pred; |
| 9630 | auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); |
| 9631 | if (!isa<SCEVCouldNotCompute>(PBT)) { |
| 9632 | OS << "Predicated backedge-taken count is " << *PBT << "\n"; |
| 9633 | OS << " Predicates:\n"; |
| 9634 | Pred.print(OS, 4); |
| 9635 | } else { |
| 9636 | OS << "Unpredictable predicated backedge-taken count. "; |
| 9637 | } |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9638 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9639 | } |
| 9640 | |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9641 | static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { |
| 9642 | switch (LD) { |
| 9643 | case ScalarEvolution::LoopVariant: |
| 9644 | return "Variant"; |
| 9645 | case ScalarEvolution::LoopInvariant: |
| 9646 | return "Invariant"; |
| 9647 | case ScalarEvolution::LoopComputable: |
| 9648 | return "Computable"; |
| 9649 | } |
Simon Pilgrim | 33ae13d | 2016-05-01 15:52:31 +0000 | [diff] [blame] | 9650 | llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9651 | } |
| 9652 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9653 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 9654 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9655 | // out SCEV values of all instructions that are interesting. Doing |
| 9656 | // this potentially causes it to create new SCEV objects though, |
| 9657 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 9658 | // observable from outside the class though, so casting away the |
| 9659 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9660 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9661 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9662 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9663 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9664 | OS << "\n"; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9665 | for (Instruction &I : instructions(F)) |
| 9666 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { |
| 9667 | OS << I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 9668 | OS << " --> "; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9669 | const SCEV *SV = SE.getSCEV(&I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9670 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9671 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 9672 | OS << " U: "; |
| 9673 | SE.getUnsignedRange(SV).print(OS); |
| 9674 | OS << " S: "; |
| 9675 | SE.getSignedRange(SV).print(OS); |
| 9676 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9677 | |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9678 | const Loop *L = LI.getLoopFor(I.getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9679 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9680 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9681 | if (AtUse != SV) { |
| 9682 | OS << " --> "; |
| 9683 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9684 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 9685 | OS << " U: "; |
| 9686 | SE.getUnsignedRange(AtUse).print(OS); |
| 9687 | OS << " S: "; |
| 9688 | SE.getSignedRange(AtUse).print(OS); |
| 9689 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9690 | } |
| 9691 | |
| 9692 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 9693 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9694 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9695 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9696 | OS << "<<Unknown>>"; |
| 9697 | } else { |
| 9698 | OS << *ExitValue; |
| 9699 | } |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9700 | |
| 9701 | bool First = true; |
| 9702 | for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { |
| 9703 | if (First) { |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9704 | OS << "\t\t" "LoopDispositions: { "; |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9705 | First = false; |
| 9706 | } else { |
| 9707 | OS << ", "; |
| 9708 | } |
| 9709 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9710 | Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9711 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9712 | } |
| 9713 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9714 | for (auto *InnerL : depth_first(L)) { |
| 9715 | if (InnerL == L) |
| 9716 | continue; |
| 9717 | if (First) { |
| 9718 | OS << "\t\t" "LoopDispositions: { "; |
| 9719 | First = false; |
| 9720 | } else { |
| 9721 | OS << ", "; |
| 9722 | } |
| 9723 | |
| 9724 | InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9725 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); |
| 9726 | } |
| 9727 | |
| 9728 | OS << " }"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9729 | } |
| 9730 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9731 | OS << "\n"; |
| 9732 | } |
| 9733 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9734 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9735 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9736 | OS << "\n"; |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 9737 | for (Loop *I : LI) |
| 9738 | PrintLoopInfo(OS, &SE, I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9739 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 9740 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9741 | ScalarEvolution::LoopDisposition |
| 9742 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9743 | auto &Values = LoopDispositions[S]; |
| 9744 | for (auto &V : Values) { |
| 9745 | if (V.getPointer() == L) |
| 9746 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9747 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9748 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9749 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9750 | auto &Values2 = LoopDispositions[S]; |
| 9751 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9752 | if (V.getPointer() == L) { |
| 9753 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9754 | break; |
| 9755 | } |
| 9756 | } |
| 9757 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9758 | } |
| 9759 | |
| 9760 | ScalarEvolution::LoopDisposition |
| 9761 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9762 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9763 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9764 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9765 | case scTruncate: |
| 9766 | case scZeroExtend: |
| 9767 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9768 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9769 | case scAddRecExpr: { |
| 9770 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 9771 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9772 | // If L is the addrec's loop, it's computable. |
| 9773 | if (AR->getLoop() == L) |
| 9774 | return LoopComputable; |
| 9775 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9776 | // Add recurrences are never invariant in the function-body (null loop). |
| 9777 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9778 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9779 | |
| 9780 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 9781 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9782 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9783 | |
| 9784 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 9785 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9786 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9787 | |
| 9788 | // This recurrence is variant w.r.t. L if any of its operands |
| 9789 | // are variant. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9790 | for (auto *Op : AR->operands()) |
| 9791 | if (!isLoopInvariant(Op, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9792 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9793 | |
| 9794 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9795 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9796 | } |
| 9797 | case scAddExpr: |
| 9798 | case scMulExpr: |
| 9799 | case scUMaxExpr: |
| 9800 | case scSMaxExpr: { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9801 | bool HasVarying = false; |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9802 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { |
| 9803 | LoopDisposition D = getLoopDisposition(Op, L); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9804 | if (D == LoopVariant) |
| 9805 | return LoopVariant; |
| 9806 | if (D == LoopComputable) |
| 9807 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9808 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9809 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9810 | } |
| 9811 | case scUDivExpr: { |
| 9812 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9813 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 9814 | if (LD == LoopVariant) |
| 9815 | return LoopVariant; |
| 9816 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 9817 | if (RD == LoopVariant) |
| 9818 | return LoopVariant; |
| 9819 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 9820 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9821 | } |
| 9822 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9823 | // All non-instruction values are loop invariant. All instructions are loop |
| 9824 | // invariant if they are not contained in the specified loop. |
| 9825 | // Instructions are never considered invariant in the function body |
| 9826 | // (null loop) because they are defined within the "loop". |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9827 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9828 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 9829 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9830 | case scCouldNotCompute: |
| 9831 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9832 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9833 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9834 | } |
| 9835 | |
| 9836 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 9837 | return getLoopDisposition(S, L) == LoopInvariant; |
| 9838 | } |
| 9839 | |
| 9840 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 9841 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9842 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9843 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9844 | ScalarEvolution::BlockDisposition |
| 9845 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9846 | auto &Values = BlockDispositions[S]; |
| 9847 | for (auto &V : Values) { |
| 9848 | if (V.getPointer() == BB) |
| 9849 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9850 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9851 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9852 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9853 | auto &Values2 = BlockDispositions[S]; |
| 9854 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9855 | if (V.getPointer() == BB) { |
| 9856 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9857 | break; |
| 9858 | } |
| 9859 | } |
| 9860 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9861 | } |
| 9862 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9863 | ScalarEvolution::BlockDisposition |
| 9864 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9865 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9866 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9867 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9868 | case scTruncate: |
| 9869 | case scZeroExtend: |
| 9870 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9871 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9872 | case scAddRecExpr: { |
| 9873 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9874 | // to test for proper dominance too, because the instruction which |
| 9875 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 9876 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9877 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9878 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9879 | return DoesNotDominateBlock; |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 9880 | |
| 9881 | // Fall through into SCEVNAryExpr handling. |
| 9882 | LLVM_FALLTHROUGH; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9883 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9884 | case scAddExpr: |
| 9885 | case scMulExpr: |
| 9886 | case scUMaxExpr: |
| 9887 | case scSMaxExpr: { |
| 9888 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9889 | bool Proper = true; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 9890 | for (const SCEV *NAryOp : NAry->operands()) { |
| 9891 | BlockDisposition D = getBlockDisposition(NAryOp, BB); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9892 | if (D == DoesNotDominateBlock) |
| 9893 | return DoesNotDominateBlock; |
| 9894 | if (D == DominatesBlock) |
| 9895 | Proper = false; |
| 9896 | } |
| 9897 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9898 | } |
| 9899 | case scUDivExpr: { |
| 9900 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9901 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 9902 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 9903 | if (LD == DoesNotDominateBlock) |
| 9904 | return DoesNotDominateBlock; |
| 9905 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 9906 | if (RD == DoesNotDominateBlock) |
| 9907 | return DoesNotDominateBlock; |
| 9908 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 9909 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9910 | } |
| 9911 | case scUnknown: |
| 9912 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9913 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 9914 | if (I->getParent() == BB) |
| 9915 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9916 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9917 | return ProperlyDominatesBlock; |
| 9918 | return DoesNotDominateBlock; |
| 9919 | } |
| 9920 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9921 | case scCouldNotCompute: |
| 9922 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9923 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9924 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9925 | } |
| 9926 | |
| 9927 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 9928 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 9929 | } |
| 9930 | |
| 9931 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 9932 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9933 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9934 | |
| 9935 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 9936 | return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9937 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9938 | |
| 9939 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 9940 | ValuesAtScopes.erase(S); |
| 9941 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9942 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9943 | UnsignedRanges.erase(S); |
| 9944 | SignedRanges.erase(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9945 | ExprValueMap.erase(S); |
| 9946 | HasRecMap.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 9947 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9948 | auto RemoveSCEVFromBackedgeMap = |
| 9949 | [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 9950 | for (auto I = Map.begin(), E = Map.end(); I != E;) { |
| 9951 | BackedgeTakenInfo &BEInfo = I->second; |
| 9952 | if (BEInfo.hasOperand(S, this)) { |
| 9953 | BEInfo.clear(); |
| 9954 | Map.erase(I++); |
| 9955 | } else |
| 9956 | ++I; |
| 9957 | } |
| 9958 | }; |
| 9959 | |
| 9960 | RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); |
| 9961 | RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9962 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9963 | |
| 9964 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9965 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 9966 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9967 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 9968 | size_t Pos = 0; |
| 9969 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 9970 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 9971 | Pos += To.size(); |
| 9972 | } |
| 9973 | } |
| 9974 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9975 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 9976 | static void |
| 9977 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9978 | std::string &S = Map[L]; |
| 9979 | if (S.empty()) { |
| 9980 | raw_string_ostream OS(S); |
| 9981 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9982 | |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9983 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 9984 | replaceSubString(OS.str(), "false", "0"); |
| 9985 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 9986 | // FIXME: Remove this when SCEV gets smarter about them. |
| 9987 | replaceSubString(OS.str(), "<nw>", ""); |
| 9988 | replaceSubString(OS.str(), "<nsw>", ""); |
| 9989 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9990 | } |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9991 | |
JF Bastien | 61ad8b3 | 2015-12-23 18:18:53 +0000 | [diff] [blame] | 9992 | for (auto *R : reverse(*L)) |
| 9993 | getLoopBackedgeTakenCounts(R, Map, SE); // recurse. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9994 | } |
| 9995 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9996 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9997 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9998 | |
| 9999 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 10000 | // FIXME: It would be much better to store actual values instead of strings, |
| 10001 | // but SCEV pointers will change if we drop the caches. |
| 10002 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10003 | 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] | 10004 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 10005 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10006 | // Gather stringified backedge taken counts for all loops using a fresh |
| 10007 | // ScalarEvolution object. |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 10008 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10009 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 10010 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10011 | |
| 10012 | // Now compare whether they're the same with and without caches. This allows |
| 10013 | // verifying that no pass changed the cache. |
| 10014 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 10015 | "New loops suddenly appeared!"); |
| 10016 | |
| 10017 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 10018 | OldE = BackedgeDumpsOld.end(), |
| 10019 | NewI = BackedgeDumpsNew.begin(); |
| 10020 | OldI != OldE; ++OldI, ++NewI) { |
| 10021 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 10022 | |
| 10023 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 10024 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10025 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10026 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 10027 | // usually not harmful. |
| 10028 | if (OldI->second != NewI->second && |
| 10029 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10030 | NewI->second.find("undef") == std::string::npos && |
| 10031 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10032 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10033 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10034 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10035 | << "' changed from '" << OldI->second |
| 10036 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10037 | std::abort(); |
| 10038 | } |
| 10039 | } |
| 10040 | |
| 10041 | // TODO: Verify more things. |
| 10042 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10043 | |
Chandler Carruth | 082c183 | 2017-01-09 07:44:34 +0000 | [diff] [blame] | 10044 | bool ScalarEvolution::invalidate( |
| 10045 | Function &F, const PreservedAnalyses &PA, |
| 10046 | FunctionAnalysisManager::Invalidator &Inv) { |
| 10047 | // Invalidate the ScalarEvolution object whenever it isn't preserved or one |
| 10048 | // of its dependencies is invalidated. |
| 10049 | auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); |
| 10050 | return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || |
| 10051 | Inv.invalidate<AssumptionAnalysis>(F, PA) || |
| 10052 | Inv.invalidate<DominatorTreeAnalysis>(F, PA) || |
| 10053 | Inv.invalidate<LoopAnalysis>(F, PA); |
| 10054 | } |
| 10055 | |
Chandler Carruth | dab4eae | 2016-11-23 17:53:26 +0000 | [diff] [blame] | 10056 | AnalysisKey ScalarEvolutionAnalysis::Key; |
NAKAMURA Takumi | df0cd72 | 2016-02-28 17:17:00 +0000 | [diff] [blame] | 10057 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10058 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 10059 | FunctionAnalysisManager &AM) { |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10060 | return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 10061 | AM.getResult<AssumptionAnalysis>(F), |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10062 | AM.getResult<DominatorTreeAnalysis>(F), |
| 10063 | AM.getResult<LoopAnalysis>(F)); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10064 | } |
| 10065 | |
| 10066 | PreservedAnalyses |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 10067 | ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10068 | AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10069 | return PreservedAnalyses::all(); |
| 10070 | } |
| 10071 | |
| 10072 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10073 | "Scalar Evolution Analysis", false, true) |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 10074 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10075 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 10076 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 10077 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 10078 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10079 | "Scalar Evolution Analysis", false, true) |
| 10080 | char ScalarEvolutionWrapperPass::ID = 0; |
| 10081 | |
| 10082 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 10083 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 10084 | } |
| 10085 | |
| 10086 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 10087 | SE.reset(new ScalarEvolution( |
| 10088 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 10089 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10090 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 10091 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 10092 | return false; |
| 10093 | } |
| 10094 | |
| 10095 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 10096 | |
| 10097 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 10098 | SE->print(OS); |
| 10099 | } |
| 10100 | |
| 10101 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 10102 | if (!VerifySCEV) |
| 10103 | return; |
| 10104 | |
| 10105 | SE->verify(); |
| 10106 | } |
| 10107 | |
| 10108 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 10109 | AU.setPreservesAll(); |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 10110 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10111 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 10112 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 10113 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 10114 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10115 | |
| 10116 | const SCEVPredicate * |
| 10117 | ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, |
| 10118 | const SCEVConstant *RHS) { |
| 10119 | FoldingSetNodeID ID; |
| 10120 | // Unique this node based on the arguments |
| 10121 | ID.AddInteger(SCEVPredicate::P_Equal); |
| 10122 | ID.AddPointer(LHS); |
| 10123 | ID.AddPointer(RHS); |
| 10124 | void *IP = nullptr; |
| 10125 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10126 | return S; |
| 10127 | SCEVEqualPredicate *Eq = new (SCEVAllocator) |
| 10128 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); |
| 10129 | UniquePreds.InsertNode(Eq, IP); |
| 10130 | return Eq; |
| 10131 | } |
| 10132 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10133 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( |
| 10134 | const SCEVAddRecExpr *AR, |
| 10135 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10136 | FoldingSetNodeID ID; |
| 10137 | // Unique this node based on the arguments |
| 10138 | ID.AddInteger(SCEVPredicate::P_Wrap); |
| 10139 | ID.AddPointer(AR); |
| 10140 | ID.AddInteger(AddedFlags); |
| 10141 | void *IP = nullptr; |
| 10142 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10143 | return S; |
| 10144 | auto *OF = new (SCEVAllocator) |
| 10145 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); |
| 10146 | UniquePreds.InsertNode(OF, IP); |
| 10147 | return OF; |
| 10148 | } |
| 10149 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10150 | namespace { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10151 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10152 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { |
| 10153 | public: |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10154 | /// Rewrites \p S in the context of a loop L and the SCEV predication |
| 10155 | /// infrastructure. |
| 10156 | /// |
| 10157 | /// If \p Pred is non-null, the SCEV expression is rewritten to respect the |
| 10158 | /// equivalences present in \p Pred. |
| 10159 | /// |
| 10160 | /// If \p NewPreds is non-null, rewrite is free to add further predicates to |
| 10161 | /// \p NewPreds such that the result will be an AddRecExpr. |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10162 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10163 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, |
| 10164 | SCEVUnionPredicate *Pred) { |
| 10165 | SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10166 | return Rewriter.visit(S); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10167 | } |
| 10168 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10169 | SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10170 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, |
| 10171 | SCEVUnionPredicate *Pred) |
| 10172 | : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10173 | |
| 10174 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10175 | if (Pred) { |
| 10176 | auto ExprPreds = Pred->getPredicatesForExpr(Expr); |
| 10177 | for (auto *Pred : ExprPreds) |
| 10178 | if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) |
| 10179 | if (IPred->getLHS() == Expr) |
| 10180 | return IPred->getRHS(); |
| 10181 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10182 | |
| 10183 | return Expr; |
| 10184 | } |
| 10185 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10186 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { |
| 10187 | const SCEV *Operand = visit(Expr->getOperand()); |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10188 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10189 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10190 | // This couldn't be folded because the operand didn't have the nuw |
| 10191 | // flag. Add the nusw flag as an assumption that we could make. |
| 10192 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10193 | Type *Ty = Expr->getType(); |
| 10194 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) |
| 10195 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), |
| 10196 | SE.getSignExtendExpr(Step, Ty), L, |
| 10197 | AR->getNoWrapFlags()); |
| 10198 | } |
| 10199 | return SE.getZeroExtendExpr(Operand, Expr->getType()); |
| 10200 | } |
| 10201 | |
| 10202 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { |
| 10203 | const SCEV *Operand = visit(Expr->getOperand()); |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10204 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10205 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10206 | // This couldn't be folded because the operand didn't have the nsw |
| 10207 | // flag. Add the nssw flag as an assumption that we could make. |
| 10208 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10209 | Type *Ty = Expr->getType(); |
| 10210 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) |
| 10211 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), |
| 10212 | SE.getSignExtendExpr(Step, Ty), L, |
| 10213 | AR->getNoWrapFlags()); |
| 10214 | } |
| 10215 | return SE.getSignExtendExpr(Operand, Expr->getType()); |
| 10216 | } |
| 10217 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10218 | private: |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10219 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, |
| 10220 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10221 | auto *A = SE.getWrapPredicate(AR, AddedFlags); |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10222 | if (!NewPreds) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10223 | // Check if we've already made this assumption. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10224 | return Pred && Pred->implies(A); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10225 | } |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10226 | NewPreds->insert(A); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10227 | return true; |
| 10228 | } |
| 10229 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10230 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; |
| 10231 | SCEVUnionPredicate *Pred; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10232 | const Loop *L; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10233 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10234 | } // end anonymous namespace |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10235 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10236 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10237 | SCEVUnionPredicate &Preds) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10238 | return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10239 | } |
| 10240 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10241 | const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( |
| 10242 | const SCEV *S, const Loop *L, |
| 10243 | SmallPtrSetImpl<const SCEVPredicate *> &Preds) { |
| 10244 | |
| 10245 | SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; |
| 10246 | S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10247 | auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); |
| 10248 | |
| 10249 | if (!AddRec) |
| 10250 | return nullptr; |
| 10251 | |
| 10252 | // Since the transformation was successful, we can now transfer the SCEV |
| 10253 | // predicates. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10254 | for (auto *P : TransformPreds) |
| 10255 | Preds.insert(P); |
| 10256 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10257 | return AddRec; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10258 | } |
| 10259 | |
| 10260 | /// SCEV predicates |
| 10261 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, |
| 10262 | SCEVPredicateKind Kind) |
| 10263 | : FastID(ID), Kind(Kind) {} |
| 10264 | |
| 10265 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, |
| 10266 | const SCEVUnknown *LHS, |
| 10267 | const SCEVConstant *RHS) |
| 10268 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} |
| 10269 | |
| 10270 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10271 | const auto *Op = dyn_cast<SCEVEqualPredicate>(N); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10272 | |
| 10273 | if (!Op) |
| 10274 | return false; |
| 10275 | |
| 10276 | return Op->LHS == LHS && Op->RHS == RHS; |
| 10277 | } |
| 10278 | |
| 10279 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } |
| 10280 | |
| 10281 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } |
| 10282 | |
| 10283 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10284 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; |
| 10285 | } |
| 10286 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10287 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, |
| 10288 | const SCEVAddRecExpr *AR, |
| 10289 | IncrementWrapFlags Flags) |
| 10290 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} |
| 10291 | |
| 10292 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } |
| 10293 | |
| 10294 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { |
| 10295 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); |
| 10296 | |
| 10297 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; |
| 10298 | } |
| 10299 | |
| 10300 | bool SCEVWrapPredicate::isAlwaysTrue() const { |
| 10301 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); |
| 10302 | IncrementWrapFlags IFlags = Flags; |
| 10303 | |
| 10304 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) |
| 10305 | IFlags = clearFlags(IFlags, IncrementNSSW); |
| 10306 | |
| 10307 | return IFlags == IncrementAnyWrap; |
| 10308 | } |
| 10309 | |
| 10310 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10311 | OS.indent(Depth) << *getExpr() << " Added Flags: "; |
| 10312 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) |
| 10313 | OS << "<nusw>"; |
| 10314 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) |
| 10315 | OS << "<nssw>"; |
| 10316 | OS << "\n"; |
| 10317 | } |
| 10318 | |
| 10319 | SCEVWrapPredicate::IncrementWrapFlags |
| 10320 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, |
| 10321 | ScalarEvolution &SE) { |
| 10322 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; |
| 10323 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); |
| 10324 | |
| 10325 | // We can safely transfer the NSW flag as NSSW. |
| 10326 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) |
| 10327 | ImpliedFlags = IncrementNSSW; |
| 10328 | |
| 10329 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { |
| 10330 | // If the increment is positive, the SCEV NUW flag will also imply the |
| 10331 | // WrapPredicate NUSW flag. |
| 10332 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 10333 | if (Step->getValue()->getValue().isNonNegative()) |
| 10334 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); |
| 10335 | } |
| 10336 | |
| 10337 | return ImpliedFlags; |
| 10338 | } |
| 10339 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10340 | /// Union predicates don't get cached so create a dummy set ID for it. |
| 10341 | SCEVUnionPredicate::SCEVUnionPredicate() |
| 10342 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} |
| 10343 | |
| 10344 | bool SCEVUnionPredicate::isAlwaysTrue() const { |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10345 | return all_of(Preds, |
| 10346 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10347 | } |
| 10348 | |
| 10349 | ArrayRef<const SCEVPredicate *> |
| 10350 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { |
| 10351 | auto I = SCEVToPreds.find(Expr); |
| 10352 | if (I == SCEVToPreds.end()) |
| 10353 | return ArrayRef<const SCEVPredicate *>(); |
| 10354 | return I->second; |
| 10355 | } |
| 10356 | |
| 10357 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10358 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10359 | return all_of(Set->Preds, |
| 10360 | [this](const SCEVPredicate *I) { return this->implies(I); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10361 | |
| 10362 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); |
| 10363 | if (ScevPredsIt == SCEVToPreds.end()) |
| 10364 | return false; |
| 10365 | auto &SCEVPreds = ScevPredsIt->second; |
| 10366 | |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 10367 | return any_of(SCEVPreds, |
| 10368 | [N](const SCEVPredicate *I) { return I->implies(N); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10369 | } |
| 10370 | |
| 10371 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } |
| 10372 | |
| 10373 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10374 | for (auto Pred : Preds) |
| 10375 | Pred->print(OS, Depth); |
| 10376 | } |
| 10377 | |
| 10378 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10379 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10380 | for (auto Pred : Set->Preds) |
| 10381 | add(Pred); |
| 10382 | return; |
| 10383 | } |
| 10384 | |
| 10385 | if (implies(N)) |
| 10386 | return; |
| 10387 | |
| 10388 | const SCEV *Key = N->getExpr(); |
| 10389 | assert(Key && "Only SCEVUnionPredicate doesn't have an " |
| 10390 | " associated expression!"); |
| 10391 | |
| 10392 | SCEVToPreds[Key].push_back(N); |
| 10393 | Preds.push_back(N); |
| 10394 | } |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10395 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10396 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, |
| 10397 | Loop &L) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10398 | : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10399 | |
| 10400 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { |
| 10401 | const SCEV *Expr = SE.getSCEV(V); |
| 10402 | RewriteEntry &Entry = RewriteMap[Expr]; |
| 10403 | |
| 10404 | // If we already have an entry and the version matches, return it. |
| 10405 | if (Entry.second && Generation == Entry.first) |
| 10406 | return Entry.second; |
| 10407 | |
| 10408 | // We found an entry but it's stale. Rewrite the stale entry |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 10409 | // according to the current predicate. |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10410 | if (Entry.second) |
| 10411 | Expr = Entry.second; |
| 10412 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10413 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10414 | Entry = {Generation, NewSCEV}; |
| 10415 | |
| 10416 | return NewSCEV; |
| 10417 | } |
| 10418 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10419 | const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { |
| 10420 | if (!BackedgeCount) { |
| 10421 | SCEVUnionPredicate BackedgePred; |
| 10422 | BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); |
| 10423 | addPredicate(BackedgePred); |
| 10424 | } |
| 10425 | return BackedgeCount; |
| 10426 | } |
| 10427 | |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10428 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { |
| 10429 | if (Preds.implies(&Pred)) |
| 10430 | return; |
| 10431 | Preds.add(&Pred); |
| 10432 | updateGeneration(); |
| 10433 | } |
| 10434 | |
| 10435 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { |
| 10436 | return Preds; |
| 10437 | } |
| 10438 | |
| 10439 | void PredicatedScalarEvolution::updateGeneration() { |
| 10440 | // If the generation number wrapped recompute everything. |
| 10441 | if (++Generation == 0) { |
| 10442 | for (auto &II : RewriteMap) { |
| 10443 | const SCEV *Rewritten = II.second.second; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10444 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10445 | } |
| 10446 | } |
| 10447 | } |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10448 | |
| 10449 | void PredicatedScalarEvolution::setNoOverflow( |
| 10450 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10451 | const SCEV *Expr = getSCEV(V); |
| 10452 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10453 | |
| 10454 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); |
| 10455 | |
| 10456 | // Clear the statically implied flags. |
| 10457 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); |
| 10458 | addPredicate(*SE.getWrapPredicate(AR, Flags)); |
| 10459 | |
| 10460 | auto II = FlagsMap.insert({V, Flags}); |
| 10461 | if (!II.second) |
| 10462 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); |
| 10463 | } |
| 10464 | |
| 10465 | bool PredicatedScalarEvolution::hasNoOverflow( |
| 10466 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10467 | const SCEV *Expr = getSCEV(V); |
| 10468 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10469 | |
| 10470 | Flags = SCEVWrapPredicate::clearFlags( |
| 10471 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); |
| 10472 | |
| 10473 | auto II = FlagsMap.find(V); |
| 10474 | |
| 10475 | if (II != FlagsMap.end()) |
| 10476 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); |
| 10477 | |
| 10478 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; |
| 10479 | } |
| 10480 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10481 | const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10482 | const SCEV *Expr = this->getSCEV(V); |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10483 | SmallPtrSet<const SCEVPredicate *, 4> NewPreds; |
| 10484 | auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10485 | |
| 10486 | if (!New) |
| 10487 | return nullptr; |
| 10488 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10489 | for (auto *P : NewPreds) |
| 10490 | Preds.add(P); |
| 10491 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10492 | updateGeneration(); |
| 10493 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; |
| 10494 | return New; |
| 10495 | } |
| 10496 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10497 | PredicatedScalarEvolution::PredicatedScalarEvolution( |
| 10498 | const PredicatedScalarEvolution &Init) |
| 10499 | : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), |
| 10500 | Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 10501 | for (const auto &I : Init.FlagsMap) |
| 10502 | FlagsMap.insert(I); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10503 | } |
Silviu Baranga | b77365b | 2016-04-14 16:08:45 +0000 | [diff] [blame] | 10504 | |
| 10505 | void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { |
| 10506 | // For each block. |
| 10507 | for (auto *BB : L.getBlocks()) |
| 10508 | for (auto &I : *BB) { |
| 10509 | if (!SE.isSCEVable(I.getType())) |
| 10510 | continue; |
| 10511 | |
| 10512 | auto *Expr = SE.getSCEV(&I); |
| 10513 | auto II = RewriteMap.find(Expr); |
| 10514 | |
| 10515 | if (II == RewriteMap.end()) |
| 10516 | continue; |
| 10517 | |
| 10518 | // Don't print things that are not interesting. |
| 10519 | if (II->second.second == Expr) |
| 10520 | continue; |
| 10521 | |
| 10522 | OS.indent(Depth) << "[PSE]" << I << ":\n"; |
| 10523 | OS.indent(Depth + 2) << *Expr << "\n"; |
| 10524 | OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; |
| 10525 | } |
| 10526 | } |