blob: f42d4654a50c76b709a0f3b99c36937c7f667f43 [file] [log] [blame]
Uday Bondhugula257339b2018-08-21 10:32:24 -07001//===- AffineStructures.cpp - MLIR Affine Structures Class-------*- C++ -*-===//
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// Structures for affine/polyhedral analysis of MLIR functions.
19//
20//===----------------------------------------------------------------------===//
21
22#include "mlir/Analysis/AffineStructures.h"
Uday Bondhugula83a41c92018-08-30 17:35:15 -070023
Uday Bondhugula83a41c92018-08-30 17:35:15 -070024#include "mlir/IR/AffineExprVisitor.h"
Uday Bondhugula257339b2018-08-21 10:32:24 -070025#include "mlir/IR/AffineMap.h"
26#include "mlir/IR/IntegerSet.h"
Uday Bondhugula257339b2018-08-21 10:32:24 -070027#include "mlir/IR/StandardOps.h"
Uday Bondhugula83a41c92018-08-30 17:35:15 -070028#include "llvm/Support/raw_ostream.h"
Uday Bondhugula257339b2018-08-21 10:32:24 -070029
Uday Bondhugula128c7aa2018-09-04 15:55:38 -070030using namespace mlir;
31
32/// Constructs an affine expression from a flat ArrayRef. If there are local
33/// identifiers (neither dimensional nor symbolic) that appear in the sum of
34/// products expression, 'localExprs' is expected to have the AffineExpr for it,
35/// and is substituted into. The ArrayRef 'eq' is expected to be in the format
36/// [dims, symbols, locals, constant term].
37static AffineExpr *toAffineExpr(ArrayRef<int64_t> eq, unsigned numDims,
38 unsigned numSymbols,
39 ArrayRef<AffineExpr *> localExprs,
40 MLIRContext *context) {
41 unsigned numLocals = eq.size() - numDims - numSymbols - 1;
42
43 assert(numLocals == localExprs.size() &&
44 "unexpected number of local expressions");
45
46 AffineExpr *expr = AffineConstantExpr::get(0, context);
47 // Dimensions and symbols.
48 for (unsigned j = 0; j < numDims + numSymbols; j++) {
49 if (eq[j] != 0) {
50 AffineExpr *id =
51 j < numDims
52 ? static_cast<AffineExpr *>(AffineDimExpr::get(j, context))
53 : AffineSymbolExpr::get(j - numDims, context);
54 auto *term = AffineBinaryOpExpr::getMul(
55 AffineConstantExpr::get(eq[j], context), id, context);
56 expr = AffineBinaryOpExpr::getAdd(expr, term, context);
57 }
58 }
59
60 // Local identifiers.
61 for (unsigned j = numDims + numSymbols; j < eq.size() - 1; j++) {
62 if (eq[j] != 0) {
63 auto *term = AffineBinaryOpExpr::getMul(
64 AffineConstantExpr::get(eq[j], context),
65 localExprs[j - numDims - numSymbols], context);
66 expr = AffineBinaryOpExpr::getAdd(expr, term, context);
67 }
68 }
69
70 // Constant term.
71 unsigned constTerm = eq[eq.size() - 1];
72 if (constTerm != 0)
73 expr = AffineBinaryOpExpr::getAdd(
74 expr, AffineConstantExpr::get(constTerm, context), context);
75 return expr;
76}
77
78namespace {
79
80// This class is used to flatten a pure affine expression (AffineExpr *, which
81// is in a tree form) into a sum of products (w.r.t constants) when possible,
82// and in that process simplifying the expression. The simplification performed
83// includes the accumulation of contributions for each dimensional and symbolic
84// identifier together, the simplification of floordiv/ceildiv/mod exprssions
85// and other simplifications that in turn happen as a result. A simplification
86// that this flattening naturally performs is of simplifying the numerator and
87// denominator of floordiv/ceildiv, and folding a modulo expression to a zero,
88// if possible. Three examples are below:
89//
90// (d0 + 3 * d1) + d0) - 2 * d1) - d0 simplified to d0 + d1
91// (d0 - d0 mod 4 + 4) mod 4 simplified to 0.
92// (3*d0 + 2*d1 + d0) floordiv 2 + d1 simplified to 2*d0 + 2*d1
93//
94// For a modulo, floordiv, or a ceildiv expression, an additional identifier
95// (called a local identifier) is introduced to rewrite it as a sum of products
96// (w.r.t constants). For example, for the second example above, d0 % 4 is
97// replaced by d0 - 4*q with q being introduced: the expression then simplifies
98// to: (d0 - (d0 - 4q) + 4) = 4q + 4, modulo of which w.r.t 4 simplifies to
99// zero. Note that an affine expression may not always be expressible in a sum
100// of products form due to the presence of modulo/floordiv/ceildiv expressions
101// that may not be eliminated after simplification; in such cases, the final
102// expression can be reconstructed by replacing the local identifier with its
103// explicit form stored in localExprs (note that the explicit form itself would
104// have been simplified and not necessarily the original form).
105//
106// This is a linear time post order walk for an affine expression that attempts
107// the above simplifications through visit methods, with partial results being
108// stored in 'operandExprStack'. When a parent expr is visited, the flattened
109// expressions corresponding to its two operands would already be on the stack -
110// the parent expr looks at the two flattened expressions and combines the two.
111// It pops off the operand expressions and pushes the combined result (although
112// this is done in-place on its LHS operand expr. When the walk is completed,
113// the flattened form of the top-level expression would be left on the stack.
114//
115class AffineExprFlattener : public AffineExprVisitor<AffineExprFlattener> {
116public:
117 // Flattend expression layout: [dims, symbols, locals, constant]
118 // Stack that holds the LHS and RHS operands while visiting a binary op expr.
119 // In future, consider adding a prepass to determine how big the SmallVector's
120 // will be, and linearize this to std::vector<int64_t> to prevent
121 // SmallVector moves on re-allocation.
122 std::vector<SmallVector<int64_t, 32>> operandExprStack;
123
124 inline unsigned getNumCols() const {
125 return numDims + numSymbols + numLocals + 1;
126 }
127
128 unsigned numDims;
129 unsigned numSymbols;
130 // Number of newly introduced identifiers to flatten mod/floordiv/ceildiv
131 // expressions that could not be simplified.
132 unsigned numLocals;
133 // AffineExpr's corresponding to the floordiv/ceildiv/mod expressions for
134 // which new identifiers were introduced; if the latter do not get canceled
135 // out, these expressions are needed to reconstruct the AffineExpr * / tree
136 // form. Note that these expressions themselves would have been simplified
137 // (recursively) by this pass. Eg. d0 + (d0 + 2*d1 + d0) ceildiv 4 will be
138 // simplified to d0 + q, where q = (d0 + d1) ceildiv 2. (d0 + d1) ceildiv 2
139 // would be the local expression stored for q.
140 SmallVector<AffineExpr *, 4> localExprs;
141 MLIRContext *context;
142
143 AffineExprFlattener(unsigned numDims, unsigned numSymbols,
144 MLIRContext *context)
145 : numDims(numDims), numSymbols(numSymbols), numLocals(0),
146 context(context) {
147 operandExprStack.reserve(8);
148 }
149
150 void visitMulExpr(AffineBinaryOpExpr *expr) {
151 assert(operandExprStack.size() >= 2);
152 // This is a pure affine expr; the RHS will be a constant.
153 assert(isa<AffineConstantExpr>(expr->getRHS()));
154 // Get the RHS constant.
155 auto rhsConst = operandExprStack.back()[getConstantIndex()];
156 operandExprStack.pop_back();
157 // Update the LHS in place instead of pop and push.
158 auto &lhs = operandExprStack.back();
159 for (unsigned i = 0, e = lhs.size(); i < e; i++) {
160 lhs[i] *= rhsConst;
161 }
162 }
163
164 void visitAddExpr(AffineBinaryOpExpr *expr) {
165 assert(operandExprStack.size() >= 2);
166 const auto &rhs = operandExprStack.back();
167 auto &lhs = operandExprStack[operandExprStack.size() - 2];
168 assert(lhs.size() == rhs.size());
169 // Update the LHS in place.
170 for (unsigned i = 0; i < rhs.size(); i++) {
171 lhs[i] += rhs[i];
172 }
173 // Pop off the RHS.
174 operandExprStack.pop_back();
175 }
176
177 void visitModExpr(AffineBinaryOpExpr *expr) {
178 assert(operandExprStack.size() >= 2);
179 // This is a pure affine expr; the RHS will be a constant.
180 assert(isa<AffineConstantExpr>(expr->getRHS()));
181 auto rhsConst = operandExprStack.back()[getConstantIndex()];
182 operandExprStack.pop_back();
183 auto &lhs = operandExprStack.back();
184 // TODO(bondhugula): handle modulo by zero case when this issue is fixed
185 // at the other places in the IR.
186 assert(rhsConst != 0 && "RHS constant can't be zero");
187
188 // Check if the LHS expression is a multiple of modulo factor.
189 unsigned i;
190 for (i = 0; i < lhs.size(); i++)
191 if (lhs[i] % rhsConst != 0)
192 break;
193 // If yes, modulo expression here simplifies to zero.
194 if (i == lhs.size()) {
195 lhs.assign(lhs.size(), 0);
196 return;
197 }
198
199 // Add an existential quantifier. expr1 % expr2 is replaced by (expr1 -
200 // q * expr2) where q is the existential quantifier introduced.
201 addLocalId(AffineBinaryOpExpr::get(
202 AffineExpr::Kind::FloorDiv,
203 toAffineExpr(lhs, numDims, numSymbols, localExprs, context),
204 AffineConstantExpr::get(rhsConst, context), context));
205 lhs[getLocalVarStartIndex() + numLocals - 1] = -rhsConst;
206 }
207 void visitCeilDivExpr(AffineBinaryOpExpr *expr) {
208 visitDivExpr(expr, /*isCeil=*/true);
209 }
210 void visitFloorDivExpr(AffineBinaryOpExpr *expr) {
211 visitDivExpr(expr, /*isCeil=*/false);
212 }
213 void visitDimExpr(AffineDimExpr *expr) {
214 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
215 auto &eq = operandExprStack.back();
216 eq[getDimStartIndex() + expr->getPosition()] = 1;
217 }
218 void visitSymbolExpr(AffineSymbolExpr *expr) {
219 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
220 auto &eq = operandExprStack.back();
221 eq[getSymbolStartIndex() + expr->getPosition()] = 1;
222 }
223 void visitConstantExpr(AffineConstantExpr *expr) {
224 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
225 auto &eq = operandExprStack.back();
226 eq[getConstantIndex()] = expr->getValue();
227 }
228
229private:
230 void visitDivExpr(AffineBinaryOpExpr *expr, bool isCeil) {
231 assert(operandExprStack.size() >= 2);
232 assert(isa<AffineConstantExpr>(expr->getRHS()));
233 // This is a pure affine expr; the RHS is a positive constant.
234 auto rhsConst = operandExprStack.back()[getConstantIndex()];
235 // TODO(bondhugula): handle division by zero at the same time the issue is
236 // fixed at other places.
237 assert(rhsConst != 0 && "RHS constant can't be zero");
238 operandExprStack.pop_back();
239 auto &lhs = operandExprStack.back();
240
241 // Simplify the floordiv, ceildiv if possible by canceling out the greatest
242 // common divisors of the numerator and denominator.
243 uint64_t gcd = std::abs(rhsConst);
244 for (unsigned i = 0; i < lhs.size(); i++)
245 gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i]));
246 // Simplify the numerator and the denominator.
247 if (gcd != 1) {
248 for (unsigned i = 0; i < lhs.size(); i++)
249 lhs[i] = lhs[i] / gcd;
250 }
251 int64_t denominator = rhsConst / gcd;
252 // If the denominator becomes 1, the updated LHS is the result. (The
253 // denominator can't be negative since rhsConst is positive).
254 if (denominator == 1)
255 return;
256
257 // If the denominator cannot be simplified to one, we will have to retain
258 // the ceil/floor expr (simplified up until here). Add an existential
259 // quantifier to express its result, i.e., expr1 div expr2 is replaced
260 // by a new identifier, q.
261 auto divKind =
262 isCeil ? AffineExpr::Kind::CeilDiv : AffineExpr::Kind::FloorDiv;
263 addLocalId(AffineBinaryOpExpr::get(
264 divKind, toAffineExpr(lhs, numDims, numSymbols, localExprs, context),
265 AffineConstantExpr::get(denominator, context), context));
266 lhs.assign(lhs.size(), 0);
267 lhs[getLocalVarStartIndex() + numLocals - 1] = 1;
268 }
269
270 // Add an existential quantifier (used to flatten a mod, floordiv, ceildiv
271 // expr). localExpr is the simplified tree expression (AffineExpr *)
272 // corresponding to the quantifier.
273 void addLocalId(AffineExpr *localExpr) {
274 for (auto &subExpr : operandExprStack) {
275 subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0);
276 }
277 localExprs.push_back(localExpr);
278 numLocals++;
279 }
280
281 inline unsigned getConstantIndex() const { return getNumCols() - 1; }
282 inline unsigned getLocalVarStartIndex() const { return numDims + numSymbols; }
283 inline unsigned getSymbolStartIndex() const { return numDims; }
284 inline unsigned getDimStartIndex() const { return 0; }
285};
286
287} // end anonymous namespace
288
289AffineExpr *mlir::simplifyAffineExpr(AffineExpr *expr, unsigned numDims,
290 unsigned numSymbols,
291 MLIRContext *context) {
292 // TODO(bondhugula): only pure affine for now. The simplification here can be
293 // extended to semi-affine maps as well.
294 if (!expr->isPureAffine())
295 return nullptr;
296
297 AffineExprFlattener flattener(numDims, numSymbols, context);
298 flattener.walkPostOrder(expr);
299 ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back();
300 auto *simplifiedExpr = toAffineExpr(flattenedExpr, numDims, numSymbols,
301 flattener.localExprs, context);
302 flattener.operandExprStack.pop_back();
303 assert(flattener.operandExprStack.empty());
304 if (simplifiedExpr == expr)
305 return nullptr;
306 return simplifiedExpr;
307}
Uday Bondhugula257339b2018-08-21 10:32:24 -0700308
Uday Bondhugula83a41c92018-08-30 17:35:15 -0700309MutableAffineMap::MutableAffineMap(AffineMap *map, MLIRContext *context)
310 : numDims(map->getNumDims()), numSymbols(map->getNumSymbols()),
311 context(context) {
Uday Bondhugula257339b2018-08-21 10:32:24 -0700312 for (auto *result : map->getResults())
313 results.push_back(result);
314 for (auto *rangeSize : map->getRangeSizes())
315 results.push_back(rangeSize);
316}
317
Uday Bondhugula83a41c92018-08-30 17:35:15 -0700318bool MutableAffineMap::isMultipleOf(unsigned idx, int64_t factor) const {
319 if (results[idx]->isMultipleOf(factor))
320 return true;
Uday Bondhugula257339b2018-08-21 10:32:24 -0700321
Uday Bondhugula128c7aa2018-09-04 15:55:38 -0700322 // TODO(bondhugula): use simplifyAffineExpr and FlatAffineConstraints to
323 // complete this (for a more powerful analysis).
Uday Bondhugulab553adb2018-08-25 17:17:56 -0700324 return false;
Uday Bondhugula257339b2018-08-21 10:32:24 -0700325}
326
Uday Bondhugula128c7aa2018-09-04 15:55:38 -0700327// Simplifies the result affine expressions of this map. The expressions have to
328// be pure for the simplification implemented.
329void MutableAffineMap::simplify() {
330 // Simplify each of the results if possible.
331 for (unsigned i = 0, e = getNumResults(); i < e; i++) {
332 AffineExpr *sExpr =
333 simplifyAffineExpr(getResult(i), numDims, numSymbols, context);
334 if (sExpr)
335 results[i] = sExpr;
336 }
337}
338
Uday Bondhugula83a41c92018-08-30 17:35:15 -0700339MutableIntegerSet::MutableIntegerSet(IntegerSet *set, MLIRContext *context)
340 : numDims(set->getNumDims()), numSymbols(set->getNumSymbols()),
341 context(context) {
342 // TODO(bondhugula)
343}
344
345// Universal set.
346MutableIntegerSet::MutableIntegerSet(unsigned numDims, unsigned numSymbols,
347 MLIRContext *context)
348 : numDims(numDims), numSymbols(numSymbols), context(context) {}
349
350AffineValueMap::AffineValueMap(const AffineApplyOp &op, MLIRContext *context)
351 : map(op.getAffineMap(), context) {
352 // TODO: pull operands and results in.
353}
354
355inline bool AffineValueMap::isMultipleOf(unsigned idx, int64_t factor) const {
356 return map.isMultipleOf(idx, factor);
357}
358
Uday Bondhugula257339b2018-08-21 10:32:24 -0700359AffineValueMap::~AffineValueMap() {}
360
Uday Bondhugula83a41c92018-08-30 17:35:15 -0700361void FlatAffineConstraints::addEquality(ArrayRef<int64_t> eq) {
362 assert(eq.size() == getNumCols());
363 unsigned offset = equalities.size();
364 equalities.resize(equalities.size() + eq.size());
365 for (unsigned i = 0, e = eq.size(); i < e; i++) {
366 equalities[offset + i] = eq[i];
367 }
368}