blob: 3455783a208b1299c24c5c54c55de367e40ebba6 [file] [log] [blame]
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -07001//===- 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 Vasilachefd8d2562018-10-17 18:01:44 -070025#include "mlir/Analysis/AffineStructures.h"
26#include "mlir/Analysis/MLFunctionMatcher.h"
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -070027#include "mlir/IR/Builders.h"
28#include "mlir/IR/BuiltinOps.h"
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070029#include "mlir/IR/Statements.h"
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -070030#include "mlir/StandardOps/StandardOps.h"
Nicolas Vasilache078d9b92018-10-30 07:54:23 -070031#include "mlir/Support/Functional.h"
Uday Bondhugula48e4c4b2018-10-03 10:07:54 -070032#include "mlir/Support/MathExtras.h"
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070033
Nicolas Vasilache5373b092018-10-03 15:39:12 -070034using namespace mlir;
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070035
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 Vasilachefb11e0e2018-10-08 13:47:18 -070039AffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) {
Nicolas Vasilacheff303282018-11-07 05:44:50 -080040 // upper_bound - lower_bound
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070041 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 Vasilacheff303282018-11-07 05:44:50 -080049 loopSpan = ub - lb;
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070050 } else {
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070051 auto lbMap = forStmt.getLowerBoundMap();
52 auto ubMap = forStmt.getUpperBoundMap();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070053 // TODO(bondhugula): handle max/min of multiple expressions.
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070054 if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1)
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070055 return nullptr;
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070056
57 // TODO(bondhugula): handle bounds with different operands.
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070058 // Bounds have different operands, unhandled for now.
Uday Bondhugula5912e872018-09-18 10:22:03 -070059 if (!forStmt.matchingBoundOperandList())
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070060 return nullptr;
61
Nicolas Vasilacheff303282018-11-07 05:44:50 -080062 // ub_expr - lb_expr
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070063 AffineExpr lbExpr(lbMap.getResult(0));
64 AffineExpr ubExpr(ubMap.getResult(0));
Nicolas Vasilache5373b092018-10-03 15:39:12 -070065 auto loopSpanExpr = simplifyAffineExpr(
Nicolas Vasilacheff303282018-11-07 05:44:50 -080066 ubExpr - lbExpr, std::max(lbMap.getNumDims(), ubMap.getNumDims()),
Nicolas Vasilache75ed3372018-10-09 16:39:24 -070067 std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols()));
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -070068 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070069 if (!cExpr)
Nicolas Vasilachebc746092018-10-08 10:20:25 -070070 return loopSpanExpr.ceilDiv(step);
Nicolas Vasilacheb7717092018-10-09 10:59:27 -070071 loopSpan = cExpr.getValue();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070072 }
73
74 // 0 iteration loops.
Uday Bondhugulaff5d6bd2018-09-27 18:03:27 -070075 if (loopSpan < 0)
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070076 return 0;
77
Nicolas Vasilachebc746092018-10-08 10:20:25 -070078 return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)),
79 context);
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070080}
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.
85llvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) {
Nicolas Vasilache5373b092018-10-03 15:39:12 -070086 auto tripCountExpr = getTripCountExpr(forStmt);
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070087
Nicolas Vasilache32402e52018-10-08 08:09:50 -070088 if (!tripCountExpr)
89 return None;
90
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -070091 if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>())
Nicolas Vasilacheb7717092018-10-09 10:59:27 -070092 return constExpr.getValue();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -070093
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.
100uint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) {
Nicolas Vasilache5373b092018-10-03 15:39:12 -0700101 auto tripCountExpr = getTripCountExpr(forStmt);
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -0700102
103 if (!tripCountExpr)
104 return 1;
105
Nicolas Vasilachefb11e0e2018-10-08 13:47:18 -0700106 if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) {
Nicolas Vasilacheb7717092018-10-09 10:59:27 -0700107 uint64_t tripCount = constExpr.getValue();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -0700108
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 Vasilacheb7717092018-10-09 10:59:27 -0700118 return tripCountExpr.getLargestKnownDivisor();
Uday Bondhugulacf4f4c42018-09-12 10:21:23 -0700119}
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700120
River Riddle666dfbe2018-10-30 14:59:22 -0700121bool mlir::isAccessInvariant(const MLValue &input, MemRefType memRefType,
Nicolas Vasilached64816a2018-11-01 07:14:14 -0700122 ArrayRef<const MLValue *> indices, unsigned dim) {
River Riddle666dfbe2018-10-30 14:59:22 -0700123 assert(indices.size() == memRefType.getRank());
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700124 assert(dim < indices.size());
River Riddle666dfbe2018-10-30 14:59:22 -0700125 auto layoutMap = memRefType.getAffineMaps();
126 assert(memRefType.getAffineMaps().size() <= 1);
Nicolas Vasilached64816a2018-11-01 07:14:14 -0700127 // TODO(ntv): remove dependence on Builder once we support non-identity
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700128 // layout map.
River Riddle666dfbe2018-10-30 14:59:22 -0700129 Builder b(memRefType.getContext());
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700130 assert(layoutMap.empty() ||
131 layoutMap[0] == b.getMultiDimIdentityMap(indices.size()));
Uday Bondhugula861fe642018-10-18 11:14:26 -0700132 (void)layoutMap;
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700133
134 SmallVector<OperationStmt *, 4> affineApplyOps;
Nicolas Vasilached64816a2018-11-01 07:14:14 -0700135 getReachableAffineApplyOps({const_cast<MLValue *>(indices[dim])},
136 affineApplyOps);
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700137
138 if (affineApplyOps.empty()) {
139 // Pointer equality test because of MLValue pointer semantics.
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700140 return indices[dim] != &input;
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700141 }
142
143 assert(affineApplyOps.size() == 1 &&
144 "CompositionAffineMapsPass must have "
145 "been run: there should be at most one AffineApplyOp");
Feng Liuec065d72018-10-19 09:07:58 -0700146 auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700147 // 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 Vasilachefd8d2562018-10-17 18:01:44 -0700160}
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, ...).
167template <typename LoadOrStoreOpPointer>
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700168static bool isContiguousAccess(const MLValue &input,
169 LoadOrStoreOpPointer memoryOp,
170 unsigned fastestVaryingDim) {
171 using namespace functional;
Nicolas Vasilached64816a2018-11-01 07:14:14 -0700172 auto indices = map([](const SSAValue *val) { return dyn_cast<MLValue>(val); },
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700173 memoryOp->getIndices());
River Riddle666dfbe2018-10-30 14:59:22 -0700174 auto memRefType = memoryOp->getMemRefType();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700175 for (unsigned d = 0, numIndices = indices.size(); d < numIndices; ++d) {
176 if (fastestVaryingDim == (numIndices - 1) - d) {
177 continue;
178 }
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700179 if (!isAccessInvariant(input, memRefType, indices, d)) {
180 return false;
181 }
182 }
183 return true;
184}
185
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700186template <typename LoadOrStoreOpPointer>
187static bool isVectorElement(LoadOrStoreOpPointer memoryOp) {
River Riddle666dfbe2018-10-30 14:59:22 -0700188 auto memRefType = memoryOp->getMemRefType();
189 return memRefType.getElementType().template isa<VectorType>();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700190}
191
Nicolas Vasilached64816a2018-11-01 07:14:14 -0700192using VectorizableStmtFun =
193 std::function<bool(const ForStmt &, const OperationStmt &)>;
194
195static bool isVectorizableLoopWithCond(const ForStmt &loop,
196 VectorizableStmtFun isVectorizableStmt) {
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700197 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 Vasilachefd8d2562018-10-17 18:01:44 -0700212 auto *op = cast<OperationStmt>(ls.first);
Feng Liuec065d72018-10-19 09:07:58 -0700213 auto load = op->dyn_cast<LoadOp>();
214 auto store = op->dyn_cast<StoreOp>();
Nicolas Vasilache078d9b92018-10-30 07:54:23 -0700215 // 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 Vasilached64816a2018-11-01 07:14:14 -0700222 if (!isVectorizableStmt(loop, *op)) {
Nicolas Vasilachefd8d2562018-10-17 18:01:44 -0700223 return false;
224 }
225 }
226 return true;
227}
Uday Bondhugula861fe642018-10-18 11:14:26 -0700228
Nicolas Vasilached64816a2018-11-01 07:14:14 -0700229bool 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
241bool 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 Bondhugula861fe642018-10-18 11:14:26 -0700248/// 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.
253bool 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}