Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 1 | //===- LoopAnalysis.cpp - Misc loop analysis routines //-------------------===// |
| 2 | // |
| 3 | // Copyright 2019 The MLIR Authors. |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | // ============================================================================= |
| 17 | // |
| 18 | // This file implements miscellaneous loop analysis routines. |
| 19 | // |
| 20 | //===----------------------------------------------------------------------===// |
| 21 | |
| 22 | #include "mlir/Analysis/LoopAnalysis.h" |
| 23 | |
| 24 | #include "mlir/Analysis/AffineAnalysis.h" |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 25 | #include "mlir/Analysis/AffineStructures.h" |
| 26 | #include "mlir/Analysis/MLFunctionMatcher.h" |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 27 | #include "mlir/IR/Builders.h" |
| 28 | #include "mlir/IR/BuiltinOps.h" |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 29 | #include "mlir/IR/Statements.h" |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 30 | #include "mlir/StandardOps/StandardOps.h" |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 31 | #include "mlir/Support/Functional.h" |
Uday Bondhugula | 48e4c4b | 2018-10-03 10:07:54 -0700 | [diff] [blame] | 32 | #include "mlir/Support/MathExtras.h" |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 33 | |
Nicolas Vasilache | 5373b09 | 2018-10-03 15:39:12 -0700 | [diff] [blame] | 34 | using namespace mlir; |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 35 | |
| 36 | /// Returns the trip count of the loop as an affine expression if the latter is |
| 37 | /// expressible as an affine expression, and nullptr otherwise. The trip count |
| 38 | /// expression is simplified before returning. |
Nicolas Vasilache | fb11e0e | 2018-10-08 13:47:18 -0700 | [diff] [blame] | 39 | AffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) { |
Nicolas Vasilache | ff30328 | 2018-11-07 05:44:50 -0800 | [diff] [blame^] | 40 | // upper_bound - lower_bound |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 41 | int64_t loopSpan; |
| 42 | |
| 43 | int64_t step = forStmt.getStep(); |
| 44 | auto *context = forStmt.getContext(); |
| 45 | |
| 46 | if (forStmt.hasConstantBounds()) { |
| 47 | int64_t lb = forStmt.getConstantLowerBound(); |
| 48 | int64_t ub = forStmt.getConstantUpperBound(); |
Nicolas Vasilache | ff30328 | 2018-11-07 05:44:50 -0800 | [diff] [blame^] | 49 | loopSpan = ub - lb; |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 50 | } else { |
Nicolas Vasilache | 75ed337 | 2018-10-09 16:39:24 -0700 | [diff] [blame] | 51 | auto lbMap = forStmt.getLowerBoundMap(); |
| 52 | auto ubMap = forStmt.getUpperBoundMap(); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 53 | // TODO(bondhugula): handle max/min of multiple expressions. |
Nicolas Vasilache | 75ed337 | 2018-10-09 16:39:24 -0700 | [diff] [blame] | 54 | if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1) |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 55 | return nullptr; |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 56 | |
| 57 | // TODO(bondhugula): handle bounds with different operands. |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 58 | // Bounds have different operands, unhandled for now. |
Uday Bondhugula | 5912e87 | 2018-09-18 10:22:03 -0700 | [diff] [blame] | 59 | if (!forStmt.matchingBoundOperandList()) |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 60 | return nullptr; |
| 61 | |
Nicolas Vasilache | ff30328 | 2018-11-07 05:44:50 -0800 | [diff] [blame^] | 62 | // ub_expr - lb_expr |
Nicolas Vasilache | 75ed337 | 2018-10-09 16:39:24 -0700 | [diff] [blame] | 63 | AffineExpr lbExpr(lbMap.getResult(0)); |
| 64 | AffineExpr ubExpr(ubMap.getResult(0)); |
Nicolas Vasilache | 5373b09 | 2018-10-03 15:39:12 -0700 | [diff] [blame] | 65 | auto loopSpanExpr = simplifyAffineExpr( |
Nicolas Vasilache | ff30328 | 2018-11-07 05:44:50 -0800 | [diff] [blame^] | 66 | ubExpr - lbExpr, std::max(lbMap.getNumDims(), ubMap.getNumDims()), |
Nicolas Vasilache | 75ed337 | 2018-10-09 16:39:24 -0700 | [diff] [blame] | 67 | std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols())); |
Nicolas Vasilache | fb11e0e | 2018-10-08 13:47:18 -0700 | [diff] [blame] | 68 | auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>(); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 69 | if (!cExpr) |
Nicolas Vasilache | bc74609 | 2018-10-08 10:20:25 -0700 | [diff] [blame] | 70 | return loopSpanExpr.ceilDiv(step); |
Nicolas Vasilache | b771709 | 2018-10-09 10:59:27 -0700 | [diff] [blame] | 71 | loopSpan = cExpr.getValue(); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 72 | } |
| 73 | |
| 74 | // 0 iteration loops. |
Uday Bondhugula | ff5d6bd | 2018-09-27 18:03:27 -0700 | [diff] [blame] | 75 | if (loopSpan < 0) |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 76 | return 0; |
| 77 | |
Nicolas Vasilache | bc74609 | 2018-10-08 10:20:25 -0700 | [diff] [blame] | 78 | return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)), |
| 79 | context); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 80 | } |
| 81 | |
| 82 | /// Returns the trip count of the loop if it's a constant, None otherwise. This |
| 83 | /// method uses affine expression analysis (in turn using getTripCount) and is |
| 84 | /// able to determine constant trip count in non-trivial cases. |
| 85 | llvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) { |
Nicolas Vasilache | 5373b09 | 2018-10-03 15:39:12 -0700 | [diff] [blame] | 86 | auto tripCountExpr = getTripCountExpr(forStmt); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 87 | |
Nicolas Vasilache | 32402e5 | 2018-10-08 08:09:50 -0700 | [diff] [blame] | 88 | if (!tripCountExpr) |
| 89 | return None; |
| 90 | |
Nicolas Vasilache | fb11e0e | 2018-10-08 13:47:18 -0700 | [diff] [blame] | 91 | if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) |
Nicolas Vasilache | b771709 | 2018-10-09 10:59:27 -0700 | [diff] [blame] | 92 | return constExpr.getValue(); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 93 | |
| 94 | return None; |
| 95 | } |
| 96 | |
| 97 | /// Returns the greatest known integral divisor of the trip count. Affine |
| 98 | /// expression analysis is used (indirectly through getTripCount), and |
| 99 | /// this method is thus able to determine non-trivial divisors. |
| 100 | uint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) { |
Nicolas Vasilache | 5373b09 | 2018-10-03 15:39:12 -0700 | [diff] [blame] | 101 | auto tripCountExpr = getTripCountExpr(forStmt); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 102 | |
| 103 | if (!tripCountExpr) |
| 104 | return 1; |
| 105 | |
Nicolas Vasilache | fb11e0e | 2018-10-08 13:47:18 -0700 | [diff] [blame] | 106 | if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) { |
Nicolas Vasilache | b771709 | 2018-10-09 10:59:27 -0700 | [diff] [blame] | 107 | uint64_t tripCount = constExpr.getValue(); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 108 | |
| 109 | // 0 iteration loops (greatest divisor is 2^64 - 1). |
| 110 | if (tripCount == 0) |
| 111 | return ULONG_MAX; |
| 112 | |
| 113 | // The greatest divisor is the trip count. |
| 114 | return tripCount; |
| 115 | } |
| 116 | |
| 117 | // Trip count is not a known constant; return its largest known divisor. |
Nicolas Vasilache | b771709 | 2018-10-09 10:59:27 -0700 | [diff] [blame] | 118 | return tripCountExpr.getLargestKnownDivisor(); |
Uday Bondhugula | cf4f4c4 | 2018-09-12 10:21:23 -0700 | [diff] [blame] | 119 | } |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 120 | |
River Riddle | 666dfbe | 2018-10-30 14:59:22 -0700 | [diff] [blame] | 121 | bool mlir::isAccessInvariant(const MLValue &input, MemRefType memRefType, |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 122 | ArrayRef<const MLValue *> indices, unsigned dim) { |
River Riddle | 666dfbe | 2018-10-30 14:59:22 -0700 | [diff] [blame] | 123 | assert(indices.size() == memRefType.getRank()); |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 124 | assert(dim < indices.size()); |
River Riddle | 666dfbe | 2018-10-30 14:59:22 -0700 | [diff] [blame] | 125 | auto layoutMap = memRefType.getAffineMaps(); |
| 126 | assert(memRefType.getAffineMaps().size() <= 1); |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 127 | // TODO(ntv): remove dependence on Builder once we support non-identity |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 128 | // layout map. |
River Riddle | 666dfbe | 2018-10-30 14:59:22 -0700 | [diff] [blame] | 129 | Builder b(memRefType.getContext()); |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 130 | assert(layoutMap.empty() || |
| 131 | layoutMap[0] == b.getMultiDimIdentityMap(indices.size())); |
Uday Bondhugula | 861fe64 | 2018-10-18 11:14:26 -0700 | [diff] [blame] | 132 | (void)layoutMap; |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 133 | |
| 134 | SmallVector<OperationStmt *, 4> affineApplyOps; |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 135 | getReachableAffineApplyOps({const_cast<MLValue *>(indices[dim])}, |
| 136 | affineApplyOps); |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 137 | |
| 138 | if (affineApplyOps.empty()) { |
| 139 | // Pointer equality test because of MLValue pointer semantics. |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 140 | return indices[dim] != &input; |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | assert(affineApplyOps.size() == 1 && |
| 144 | "CompositionAffineMapsPass must have " |
| 145 | "been run: there should be at most one AffineApplyOp"); |
Feng Liu | ec065d7 | 2018-10-19 09:07:58 -0700 | [diff] [blame] | 146 | auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>(); |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 147 | // We need yet another level of indirection because the `dim` index of the |
| 148 | // access may not correspond to the `dim` index of composeOp. |
| 149 | unsigned idx = std::numeric_limits<unsigned>::max(); |
| 150 | unsigned numResults = composeOp->getNumResults(); |
| 151 | for (unsigned i = 0; i < numResults; ++i) { |
| 152 | if (indices[dim] == composeOp->getResult(i)) { |
| 153 | idx = i; |
| 154 | break; |
| 155 | } |
| 156 | } |
| 157 | assert(idx < std::numeric_limits<unsigned>::max()); |
| 158 | return !AffineValueMap(*composeOp) |
| 159 | .isFunctionOf(idx, &const_cast<MLValue &>(input)); |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 160 | } |
| 161 | |
| 162 | /// Determines whether a load or a store has a contiguous access along the |
| 163 | /// value `input`. Contiguous is defined as either invariant or varying only |
| 164 | /// along the fastest varying memory dimension. |
| 165 | // TODO(ntv): allow more advanced notions of contiguity (non-fastest varying, |
| 166 | // check strides, ...). |
| 167 | template <typename LoadOrStoreOpPointer> |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 168 | static bool isContiguousAccess(const MLValue &input, |
| 169 | LoadOrStoreOpPointer memoryOp, |
| 170 | unsigned fastestVaryingDim) { |
| 171 | using namespace functional; |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 172 | auto indices = map([](const SSAValue *val) { return dyn_cast<MLValue>(val); }, |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 173 | memoryOp->getIndices()); |
River Riddle | 666dfbe | 2018-10-30 14:59:22 -0700 | [diff] [blame] | 174 | auto memRefType = memoryOp->getMemRefType(); |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 175 | for (unsigned d = 0, numIndices = indices.size(); d < numIndices; ++d) { |
| 176 | if (fastestVaryingDim == (numIndices - 1) - d) { |
| 177 | continue; |
| 178 | } |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 179 | if (!isAccessInvariant(input, memRefType, indices, d)) { |
| 180 | return false; |
| 181 | } |
| 182 | } |
| 183 | return true; |
| 184 | } |
| 185 | |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 186 | template <typename LoadOrStoreOpPointer> |
| 187 | static bool isVectorElement(LoadOrStoreOpPointer memoryOp) { |
River Riddle | 666dfbe | 2018-10-30 14:59:22 -0700 | [diff] [blame] | 188 | auto memRefType = memoryOp->getMemRefType(); |
| 189 | return memRefType.getElementType().template isa<VectorType>(); |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 190 | } |
| 191 | |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 192 | using VectorizableStmtFun = |
| 193 | std::function<bool(const ForStmt &, const OperationStmt &)>; |
| 194 | |
| 195 | static bool isVectorizableLoopWithCond(const ForStmt &loop, |
| 196 | VectorizableStmtFun isVectorizableStmt) { |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 197 | if (!matcher::isParallelLoop(loop) && !matcher::isReductionLoop(loop)) { |
| 198 | return false; |
| 199 | } |
| 200 | |
| 201 | // No vectorization across conditionals for now. |
| 202 | auto conditionals = matcher::If(); |
| 203 | auto *forStmt = const_cast<ForStmt *>(&loop); |
| 204 | auto conditionalsMatched = conditionals.match(forStmt); |
| 205 | if (!conditionalsMatched.empty()) { |
| 206 | return false; |
| 207 | } |
| 208 | |
| 209 | auto loadAndStores = matcher::Op(matcher::isLoadOrStore); |
| 210 | auto loadAndStoresMatched = loadAndStores.match(forStmt); |
| 211 | for (auto ls : loadAndStoresMatched) { |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 212 | auto *op = cast<OperationStmt>(ls.first); |
Feng Liu | ec065d7 | 2018-10-19 09:07:58 -0700 | [diff] [blame] | 213 | auto load = op->dyn_cast<LoadOp>(); |
| 214 | auto store = op->dyn_cast<StoreOp>(); |
Nicolas Vasilache | 078d9b9 | 2018-10-30 07:54:23 -0700 | [diff] [blame] | 215 | // Only scalar types are considered vectorizable, all load/store must be |
| 216 | // vectorizable for a loop to qualify as vectorizable. |
| 217 | // TODO(ntv): ponder whether we want to be more general here. |
| 218 | bool vector = load ? isVectorElement(load) : isVectorElement(store); |
| 219 | if (vector) { |
| 220 | return false; |
| 221 | } |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 222 | if (!isVectorizableStmt(loop, *op)) { |
Nicolas Vasilache | fd8d256 | 2018-10-17 18:01:44 -0700 | [diff] [blame] | 223 | return false; |
| 224 | } |
| 225 | } |
| 226 | return true; |
| 227 | } |
Uday Bondhugula | 861fe64 | 2018-10-18 11:14:26 -0700 | [diff] [blame] | 228 | |
Nicolas Vasilache | d64816a | 2018-11-01 07:14:14 -0700 | [diff] [blame] | 229 | bool mlir::isVectorizableLoopAlongFastestVaryingMemRefDim( |
| 230 | const ForStmt &loop, unsigned fastestVaryingDim) { |
| 231 | VectorizableStmtFun fun( |
| 232 | [fastestVaryingDim](const ForStmt &loop, const OperationStmt &op) { |
| 233 | auto load = op.dyn_cast<LoadOp>(); |
| 234 | auto store = op.dyn_cast<StoreOp>(); |
| 235 | return load ? isContiguousAccess(loop, load, fastestVaryingDim) |
| 236 | : isContiguousAccess(loop, store, fastestVaryingDim); |
| 237 | }); |
| 238 | return isVectorizableLoopWithCond(loop, fun); |
| 239 | } |
| 240 | |
| 241 | bool mlir::isVectorizableLoop(const ForStmt &loop) { |
| 242 | VectorizableStmtFun fun( |
| 243 | // TODO: implement me |
| 244 | [](const ForStmt &loop, const OperationStmt &op) { return true; }); |
| 245 | return isVectorizableLoopWithCond(loop, fun); |
| 246 | } |
| 247 | |
Uday Bondhugula | 861fe64 | 2018-10-18 11:14:26 -0700 | [diff] [blame] | 248 | /// Checks whether SSA dominance would be violated if a for stmt's body |
| 249 | /// statements are shifted by the specified shifts. This method checks if a |
| 250 | /// 'def' and all its uses have the same shift factor. |
| 251 | // TODO(mlir-team): extend this to check for memory-based dependence |
| 252 | // violation when we have the support. |
| 253 | bool mlir::isStmtwiseShiftValid(const ForStmt &forStmt, |
| 254 | ArrayRef<uint64_t> shifts) { |
| 255 | assert(shifts.size() == forStmt.getStatements().size()); |
| 256 | unsigned s = 0; |
| 257 | for (const auto &stmt : forStmt) { |
| 258 | // A for or if stmt does not produce any def/results (that are used |
| 259 | // outside). |
| 260 | if (const auto *opStmt = dyn_cast<OperationStmt>(&stmt)) { |
| 261 | for (unsigned i = 0, e = opStmt->getNumResults(); i < e; ++i) { |
| 262 | const MLValue *result = opStmt->getResult(i); |
| 263 | for (const StmtOperand &use : result->getUses()) { |
| 264 | // If an ancestor statement doesn't lie in the block of forStmt, there |
| 265 | // is no shift to check. |
| 266 | // This is a naive way. If performance becomes an issue, a map can |
| 267 | // be used to store 'shifts' - to look up the shift for a statement in |
| 268 | // constant time. |
| 269 | if (auto *ancStmt = forStmt.findAncestorStmtInBlock(*use.getOwner())) |
| 270 | if (shifts[s] != shifts[forStmt.findStmtPosInBlock(*ancStmt)]) |
| 271 | return false; |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | s++; |
| 276 | } |
| 277 | return true; |
| 278 | } |