1 //===- AffineExpr.cpp - MLIR Affine Expr Classes --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/IR/AffineExpr.h"
10 #include "AffineExprDetail.h"
11 #include "mlir/IR/AffineExprVisitor.h"
12 #include "mlir/IR/AffineMap.h"
13 #include "mlir/IR/IntegerSet.h"
14 #include "mlir/Support/MathExtras.h"
15 #include "mlir/Support/TypeID.h"
16 #include "llvm/ADT/STLExtras.h"
17 
18 using namespace mlir;
19 using namespace mlir::detail;
20 
21 MLIRContext *AffineExpr::getContext() const { return expr->context; }
22 
23 AffineExprKind AffineExpr::getKind() const { return expr->kind; }
24 
25 /// Walk all of the AffineExprs in this subgraph in postorder.
26 void AffineExpr::walk(std::function<void(AffineExpr)> callback) const {
27   struct AffineExprWalker : public AffineExprVisitor<AffineExprWalker> {
28     std::function<void(AffineExpr)> callback;
29 
30     AffineExprWalker(std::function<void(AffineExpr)> callback)
31         : callback(callback) {}
32 
33     void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) { callback(expr); }
34     void visitConstantExpr(AffineConstantExpr expr) { callback(expr); }
35     void visitDimExpr(AffineDimExpr expr) { callback(expr); }
36     void visitSymbolExpr(AffineSymbolExpr expr) { callback(expr); }
37   };
38 
39   AffineExprWalker(callback).walkPostOrder(*this);
40 }
41 
42 // Dispatch affine expression construction based on kind.
43 AffineExpr mlir::getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs,
44                                        AffineExpr rhs) {
45   if (kind == AffineExprKind::Add)
46     return lhs + rhs;
47   if (kind == AffineExprKind::Mul)
48     return lhs * rhs;
49   if (kind == AffineExprKind::FloorDiv)
50     return lhs.floorDiv(rhs);
51   if (kind == AffineExprKind::CeilDiv)
52     return lhs.ceilDiv(rhs);
53   if (kind == AffineExprKind::Mod)
54     return lhs % rhs;
55 
56   llvm_unreachable("unknown binary operation on affine expressions");
57 }
58 
59 /// This method substitutes any uses of dimensions and symbols (e.g.
60 /// dim#0 with dimReplacements[0]) and returns the modified expression tree.
61 AffineExpr
62 AffineExpr::replaceDimsAndSymbols(ArrayRef<AffineExpr> dimReplacements,
63                                   ArrayRef<AffineExpr> symReplacements) const {
64   switch (getKind()) {
65   case AffineExprKind::Constant:
66     return *this;
67   case AffineExprKind::DimId: {
68     unsigned dimId = cast<AffineDimExpr>().getPosition();
69     if (dimId >= dimReplacements.size())
70       return *this;
71     return dimReplacements[dimId];
72   }
73   case AffineExprKind::SymbolId: {
74     unsigned symId = cast<AffineSymbolExpr>().getPosition();
75     if (symId >= symReplacements.size())
76       return *this;
77     return symReplacements[symId];
78   }
79   case AffineExprKind::Add:
80   case AffineExprKind::Mul:
81   case AffineExprKind::FloorDiv:
82   case AffineExprKind::CeilDiv:
83   case AffineExprKind::Mod:
84     auto binOp = cast<AffineBinaryOpExpr>();
85     auto lhs = binOp.getLHS(), rhs = binOp.getRHS();
86     auto newLHS = lhs.replaceDimsAndSymbols(dimReplacements, symReplacements);
87     auto newRHS = rhs.replaceDimsAndSymbols(dimReplacements, symReplacements);
88     if (newLHS == lhs && newRHS == rhs)
89       return *this;
90     return getAffineBinaryOpExpr(getKind(), newLHS, newRHS);
91   }
92   llvm_unreachable("Unknown AffineExpr");
93 }
94 
95 AffineExpr AffineExpr::replaceDims(ArrayRef<AffineExpr> dimReplacements) const {
96   return replaceDimsAndSymbols(dimReplacements, {});
97 }
98 
99 AffineExpr
100 AffineExpr::replaceSymbols(ArrayRef<AffineExpr> symReplacements) const {
101   return replaceDimsAndSymbols({}, symReplacements);
102 }
103 
104 /// Replace dims[offset ... numDims)
105 /// by dims[offset + shift ... shift + numDims).
106 AffineExpr AffineExpr::shiftDims(unsigned numDims, unsigned shift,
107                                  unsigned offset) const {
108   SmallVector<AffineExpr, 4> dims;
109   for (unsigned idx = 0; idx < offset; ++idx)
110     dims.push_back(getAffineDimExpr(idx, getContext()));
111   for (unsigned idx = offset; idx < numDims; ++idx)
112     dims.push_back(getAffineDimExpr(idx + shift, getContext()));
113   return replaceDimsAndSymbols(dims, {});
114 }
115 
116 /// Replace symbols[offset ... numSymbols)
117 /// by symbols[offset + shift ... shift + numSymbols).
118 AffineExpr AffineExpr::shiftSymbols(unsigned numSymbols, unsigned shift,
119                                     unsigned offset) const {
120   SmallVector<AffineExpr, 4> symbols;
121   for (unsigned idx = 0; idx < offset; ++idx)
122     symbols.push_back(getAffineSymbolExpr(idx, getContext()));
123   for (unsigned idx = offset; idx < numSymbols; ++idx)
124     symbols.push_back(getAffineSymbolExpr(idx + shift, getContext()));
125   return replaceDimsAndSymbols({}, symbols);
126 }
127 
128 /// Sparse replace method. Return the modified expression tree.
129 AffineExpr
130 AffineExpr::replace(const DenseMap<AffineExpr, AffineExpr> &map) const {
131   auto it = map.find(*this);
132   if (it != map.end())
133     return it->second;
134   switch (getKind()) {
135   default:
136     return *this;
137   case AffineExprKind::Add:
138   case AffineExprKind::Mul:
139   case AffineExprKind::FloorDiv:
140   case AffineExprKind::CeilDiv:
141   case AffineExprKind::Mod:
142     auto binOp = cast<AffineBinaryOpExpr>();
143     auto lhs = binOp.getLHS(), rhs = binOp.getRHS();
144     auto newLHS = lhs.replace(map);
145     auto newRHS = rhs.replace(map);
146     if (newLHS == lhs && newRHS == rhs)
147       return *this;
148     return getAffineBinaryOpExpr(getKind(), newLHS, newRHS);
149   }
150   llvm_unreachable("Unknown AffineExpr");
151 }
152 
153 /// Sparse replace method. Return the modified expression tree.
154 AffineExpr AffineExpr::replace(AffineExpr expr, AffineExpr replacement) const {
155   DenseMap<AffineExpr, AffineExpr> map;
156   map.insert(std::make_pair(expr, replacement));
157   return replace(map);
158 }
159 /// Returns true if this expression is made out of only symbols and
160 /// constants (no dimensional identifiers).
161 bool AffineExpr::isSymbolicOrConstant() const {
162   switch (getKind()) {
163   case AffineExprKind::Constant:
164     return true;
165   case AffineExprKind::DimId:
166     return false;
167   case AffineExprKind::SymbolId:
168     return true;
169 
170   case AffineExprKind::Add:
171   case AffineExprKind::Mul:
172   case AffineExprKind::FloorDiv:
173   case AffineExprKind::CeilDiv:
174   case AffineExprKind::Mod: {
175     auto expr = this->cast<AffineBinaryOpExpr>();
176     return expr.getLHS().isSymbolicOrConstant() &&
177            expr.getRHS().isSymbolicOrConstant();
178   }
179   }
180   llvm_unreachable("Unknown AffineExpr");
181 }
182 
183 /// Returns true if this is a pure affine expression, i.e., multiplication,
184 /// floordiv, ceildiv, and mod is only allowed w.r.t constants.
185 bool AffineExpr::isPureAffine() const {
186   switch (getKind()) {
187   case AffineExprKind::SymbolId:
188   case AffineExprKind::DimId:
189   case AffineExprKind::Constant:
190     return true;
191   case AffineExprKind::Add: {
192     auto op = cast<AffineBinaryOpExpr>();
193     return op.getLHS().isPureAffine() && op.getRHS().isPureAffine();
194   }
195 
196   case AffineExprKind::Mul: {
197     // TODO: Canonicalize the constants in binary operators to the RHS when
198     // possible, allowing this to merge into the next case.
199     auto op = cast<AffineBinaryOpExpr>();
200     return op.getLHS().isPureAffine() && op.getRHS().isPureAffine() &&
201            (op.getLHS().template isa<AffineConstantExpr>() ||
202             op.getRHS().template isa<AffineConstantExpr>());
203   }
204   case AffineExprKind::FloorDiv:
205   case AffineExprKind::CeilDiv:
206   case AffineExprKind::Mod: {
207     auto op = cast<AffineBinaryOpExpr>();
208     return op.getLHS().isPureAffine() &&
209            op.getRHS().template isa<AffineConstantExpr>();
210   }
211   }
212   llvm_unreachable("Unknown AffineExpr");
213 }
214 
215 // Returns the greatest known integral divisor of this affine expression.
216 int64_t AffineExpr::getLargestKnownDivisor() const {
217   AffineBinaryOpExpr binExpr(nullptr);
218   switch (getKind()) {
219   case AffineExprKind::CeilDiv:
220     LLVM_FALLTHROUGH;
221   case AffineExprKind::DimId:
222   case AffineExprKind::FloorDiv:
223   case AffineExprKind::SymbolId:
224     return 1;
225   case AffineExprKind::Constant:
226     return std::abs(this->cast<AffineConstantExpr>().getValue());
227   case AffineExprKind::Mul: {
228     binExpr = this->cast<AffineBinaryOpExpr>();
229     return binExpr.getLHS().getLargestKnownDivisor() *
230            binExpr.getRHS().getLargestKnownDivisor();
231   }
232   case AffineExprKind::Add:
233     LLVM_FALLTHROUGH;
234   case AffineExprKind::Mod: {
235     binExpr = cast<AffineBinaryOpExpr>();
236     return llvm::GreatestCommonDivisor64(
237         binExpr.getLHS().getLargestKnownDivisor(),
238         binExpr.getRHS().getLargestKnownDivisor());
239   }
240   }
241   llvm_unreachable("Unknown AffineExpr");
242 }
243 
244 bool AffineExpr::isMultipleOf(int64_t factor) const {
245   AffineBinaryOpExpr binExpr(nullptr);
246   uint64_t l, u;
247   switch (getKind()) {
248   case AffineExprKind::SymbolId:
249     LLVM_FALLTHROUGH;
250   case AffineExprKind::DimId:
251     return factor * factor == 1;
252   case AffineExprKind::Constant:
253     return cast<AffineConstantExpr>().getValue() % factor == 0;
254   case AffineExprKind::Mul: {
255     binExpr = cast<AffineBinaryOpExpr>();
256     // It's probably not worth optimizing this further (to not traverse the
257     // whole sub-tree under - it that would require a version of isMultipleOf
258     // that on a 'false' return also returns the largest known divisor).
259     return (l = binExpr.getLHS().getLargestKnownDivisor()) % factor == 0 ||
260            (u = binExpr.getRHS().getLargestKnownDivisor()) % factor == 0 ||
261            (l * u) % factor == 0;
262   }
263   case AffineExprKind::Add:
264   case AffineExprKind::FloorDiv:
265   case AffineExprKind::CeilDiv:
266   case AffineExprKind::Mod: {
267     binExpr = cast<AffineBinaryOpExpr>();
268     return llvm::GreatestCommonDivisor64(
269                binExpr.getLHS().getLargestKnownDivisor(),
270                binExpr.getRHS().getLargestKnownDivisor()) %
271                factor ==
272            0;
273   }
274   }
275   llvm_unreachable("Unknown AffineExpr");
276 }
277 
278 bool AffineExpr::isFunctionOfDim(unsigned position) const {
279   if (getKind() == AffineExprKind::DimId) {
280     return *this == mlir::getAffineDimExpr(position, getContext());
281   }
282   if (auto expr = this->dyn_cast<AffineBinaryOpExpr>()) {
283     return expr.getLHS().isFunctionOfDim(position) ||
284            expr.getRHS().isFunctionOfDim(position);
285   }
286   return false;
287 }
288 
289 bool AffineExpr::isFunctionOfSymbol(unsigned position) const {
290   if (getKind() == AffineExprKind::SymbolId) {
291     return *this == mlir::getAffineSymbolExpr(position, getContext());
292   }
293   if (auto expr = this->dyn_cast<AffineBinaryOpExpr>()) {
294     return expr.getLHS().isFunctionOfSymbol(position) ||
295            expr.getRHS().isFunctionOfSymbol(position);
296   }
297   return false;
298 }
299 
300 AffineBinaryOpExpr::AffineBinaryOpExpr(AffineExpr::ImplType *ptr)
301     : AffineExpr(ptr) {}
302 AffineExpr AffineBinaryOpExpr::getLHS() const {
303   return static_cast<ImplType *>(expr)->lhs;
304 }
305 AffineExpr AffineBinaryOpExpr::getRHS() const {
306   return static_cast<ImplType *>(expr)->rhs;
307 }
308 
309 AffineDimExpr::AffineDimExpr(AffineExpr::ImplType *ptr) : AffineExpr(ptr) {}
310 unsigned AffineDimExpr::getPosition() const {
311   return static_cast<ImplType *>(expr)->position;
312 }
313 
314 /// Returns true if the expression is divisible by the given symbol with
315 /// position `symbolPos`. The argument `opKind` specifies here what kind of
316 /// division or mod operation called this division. It helps in implementing the
317 /// commutative property of the floordiv and ceildiv operations. If the argument
318 ///`exprKind` is floordiv and `expr` is also a binary expression of a floordiv
319 /// operation, then the commutative property can be used otherwise, the floordiv
320 /// operation is not divisible. The same argument holds for ceildiv operation.
321 static bool isDivisibleBySymbol(AffineExpr expr, unsigned symbolPos,
322                                 AffineExprKind opKind) {
323   // The argument `opKind` can either be Modulo, Floordiv or Ceildiv only.
324   assert((opKind == AffineExprKind::Mod || opKind == AffineExprKind::FloorDiv ||
325           opKind == AffineExprKind::CeilDiv) &&
326          "unexpected opKind");
327   switch (expr.getKind()) {
328   case AffineExprKind::Constant:
329     if (expr.cast<AffineConstantExpr>().getValue())
330       return false;
331     return true;
332   case AffineExprKind::DimId:
333     return false;
334   case AffineExprKind::SymbolId:
335     return (expr.cast<AffineSymbolExpr>().getPosition() == symbolPos);
336   // Checks divisibility by the given symbol for both operands.
337   case AffineExprKind::Add: {
338     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
339     return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind) &&
340            isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, opKind);
341   }
342   // Checks divisibility by the given symbol for both operands. Consider the
343   // expression `(((s1*s0) floordiv w) mod ((s1 * s2) floordiv p)) floordiv s1`,
344   // this is a division by s1 and both the operands of modulo are divisible by
345   // s1 but it is not divisible by s1 always. The third argument is
346   // `AffineExprKind::Mod` for this reason.
347   case AffineExprKind::Mod: {
348     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
349     return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos,
350                                AffineExprKind::Mod) &&
351            isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos,
352                                AffineExprKind::Mod);
353   }
354   // Checks if any of the operand divisible by the given symbol.
355   case AffineExprKind::Mul: {
356     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
357     return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind) ||
358            isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, opKind);
359   }
360   // Floordiv and ceildiv are divisible by the given symbol when the first
361   // operand is divisible, and the affine expression kind of the argument expr
362   // is same as the argument `opKind`. This can be inferred from commutative
363   // property of floordiv and ceildiv operations and are as follow:
364   // (exp1 floordiv exp2) floordiv exp3 = (exp1 floordiv exp3) floordiv exp2
365   // (exp1 ceildiv exp2) ceildiv exp3 = (exp1 ceildiv exp3) ceildiv expr2
366   // It will fail if operations are not same. For example:
367   // (exps1 ceildiv exp2) floordiv exp3 can not be simplified.
368   case AffineExprKind::FloorDiv:
369   case AffineExprKind::CeilDiv: {
370     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
371     if (opKind != expr.getKind())
372       return false;
373     return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, expr.getKind());
374   }
375   }
376   llvm_unreachable("Unknown AffineExpr");
377 }
378 
379 /// Divides the given expression by the given symbol at position `symbolPos`. It
380 /// considers the divisibility condition is checked before calling itself. A
381 /// null expression is returned whenever the divisibility condition fails.
382 static AffineExpr symbolicDivide(AffineExpr expr, unsigned symbolPos,
383                                  AffineExprKind opKind) {
384   // THe argument `opKind` can either be Modulo, Floordiv or Ceildiv only.
385   assert((opKind == AffineExprKind::Mod || opKind == AffineExprKind::FloorDiv ||
386           opKind == AffineExprKind::CeilDiv) &&
387          "unexpected opKind");
388   switch (expr.getKind()) {
389   case AffineExprKind::Constant:
390     if (expr.cast<AffineConstantExpr>().getValue() != 0)
391       return nullptr;
392     return getAffineConstantExpr(0, expr.getContext());
393   case AffineExprKind::DimId:
394     return nullptr;
395   case AffineExprKind::SymbolId:
396     return getAffineConstantExpr(1, expr.getContext());
397   // Dividing both operands by the given symbol.
398   case AffineExprKind::Add: {
399     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
400     return getAffineBinaryOpExpr(
401         expr.getKind(), symbolicDivide(binaryExpr.getLHS(), symbolPos, opKind),
402         symbolicDivide(binaryExpr.getRHS(), symbolPos, opKind));
403   }
404   // Dividing both operands by the given symbol.
405   case AffineExprKind::Mod: {
406     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
407     return getAffineBinaryOpExpr(
408         expr.getKind(),
409         symbolicDivide(binaryExpr.getLHS(), symbolPos, expr.getKind()),
410         symbolicDivide(binaryExpr.getRHS(), symbolPos, expr.getKind()));
411   }
412   // Dividing any of the operand by the given symbol.
413   case AffineExprKind::Mul: {
414     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
415     if (!isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind))
416       return binaryExpr.getLHS() *
417              symbolicDivide(binaryExpr.getRHS(), symbolPos, opKind);
418     return symbolicDivide(binaryExpr.getLHS(), symbolPos, opKind) *
419            binaryExpr.getRHS();
420   }
421   // Dividing first operand only by the given symbol.
422   case AffineExprKind::FloorDiv:
423   case AffineExprKind::CeilDiv: {
424     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
425     return getAffineBinaryOpExpr(
426         expr.getKind(),
427         symbolicDivide(binaryExpr.getLHS(), symbolPos, expr.getKind()),
428         binaryExpr.getRHS());
429   }
430   }
431   llvm_unreachable("Unknown AffineExpr");
432 }
433 
434 /// Simplify a semi-affine expression by handling modulo, floordiv, or ceildiv
435 /// operations when the second operand simplifies to a symbol and the first
436 /// operand is divisible by that symbol. It can be applied to any semi-affine
437 /// expression. Returned expression can either be a semi-affine or pure affine
438 /// expression.
439 static AffineExpr simplifySemiAffine(AffineExpr expr) {
440   switch (expr.getKind()) {
441   case AffineExprKind::Constant:
442   case AffineExprKind::DimId:
443   case AffineExprKind::SymbolId:
444     return expr;
445   case AffineExprKind::Add:
446   case AffineExprKind::Mul: {
447     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
448     return getAffineBinaryOpExpr(expr.getKind(),
449                                  simplifySemiAffine(binaryExpr.getLHS()),
450                                  simplifySemiAffine(binaryExpr.getRHS()));
451   }
452   // Check if the simplification of the second operand is a symbol, and the
453   // first operand is divisible by it. If the operation is a modulo, a constant
454   // zero expression is returned. In the case of floordiv and ceildiv, the
455   // symbol from the simplification of the second operand divides the first
456   // operand. Otherwise, simplification is not possible.
457   case AffineExprKind::FloorDiv:
458   case AffineExprKind::CeilDiv:
459   case AffineExprKind::Mod: {
460     AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
461     AffineExpr sLHS = simplifySemiAffine(binaryExpr.getLHS());
462     AffineExpr sRHS = simplifySemiAffine(binaryExpr.getRHS());
463     AffineSymbolExpr symbolExpr =
464         simplifySemiAffine(binaryExpr.getRHS()).dyn_cast<AffineSymbolExpr>();
465     if (!symbolExpr)
466       return getAffineBinaryOpExpr(expr.getKind(), sLHS, sRHS);
467     unsigned symbolPos = symbolExpr.getPosition();
468     if (!isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, expr.getKind()))
469       return getAffineBinaryOpExpr(expr.getKind(), sLHS, sRHS);
470     if (expr.getKind() == AffineExprKind::Mod)
471       return getAffineConstantExpr(0, expr.getContext());
472     return symbolicDivide(sLHS, symbolPos, expr.getKind());
473   }
474   }
475   llvm_unreachable("Unknown AffineExpr");
476 }
477 
478 static AffineExpr getAffineDimOrSymbol(AffineExprKind kind, unsigned position,
479                                        MLIRContext *context) {
480   auto assignCtx = [context](AffineDimExprStorage *storage) {
481     storage->context = context;
482   };
483 
484   StorageUniquer &uniquer = context->getAffineUniquer();
485   return uniquer.get<AffineDimExprStorage>(
486       assignCtx, static_cast<unsigned>(kind), position);
487 }
488 
489 AffineExpr mlir::getAffineDimExpr(unsigned position, MLIRContext *context) {
490   return getAffineDimOrSymbol(AffineExprKind::DimId, position, context);
491 }
492 
493 AffineSymbolExpr::AffineSymbolExpr(AffineExpr::ImplType *ptr)
494     : AffineExpr(ptr) {}
495 unsigned AffineSymbolExpr::getPosition() const {
496   return static_cast<ImplType *>(expr)->position;
497 }
498 
499 AffineExpr mlir::getAffineSymbolExpr(unsigned position, MLIRContext *context) {
500   return getAffineDimOrSymbol(AffineExprKind::SymbolId, position, context);
501   ;
502 }
503 
504 AffineConstantExpr::AffineConstantExpr(AffineExpr::ImplType *ptr)
505     : AffineExpr(ptr) {}
506 int64_t AffineConstantExpr::getValue() const {
507   return static_cast<ImplType *>(expr)->constant;
508 }
509 
510 bool AffineExpr::operator==(int64_t v) const {
511   return *this == getAffineConstantExpr(v, getContext());
512 }
513 
514 AffineExpr mlir::getAffineConstantExpr(int64_t constant, MLIRContext *context) {
515   auto assignCtx = [context](AffineConstantExprStorage *storage) {
516     storage->context = context;
517   };
518 
519   StorageUniquer &uniquer = context->getAffineUniquer();
520   return uniquer.get<AffineConstantExprStorage>(assignCtx, constant);
521 }
522 
523 /// Simplify add expression. Return nullptr if it can't be simplified.
524 static AffineExpr simplifyAdd(AffineExpr lhs, AffineExpr rhs) {
525   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
526   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
527   // Fold if both LHS, RHS are a constant.
528   if (lhsConst && rhsConst)
529     return getAffineConstantExpr(lhsConst.getValue() + rhsConst.getValue(),
530                                  lhs.getContext());
531 
532   // Canonicalize so that only the RHS is a constant. (4 + d0 becomes d0 + 4).
533   // If only one of them is a symbolic expressions, make it the RHS.
534   if (lhs.isa<AffineConstantExpr>() ||
535       (lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant())) {
536     return rhs + lhs;
537   }
538 
539   // At this point, if there was a constant, it would be on the right.
540 
541   // Addition with a zero is a noop, return the other input.
542   if (rhsConst) {
543     if (rhsConst.getValue() == 0)
544       return lhs;
545   }
546   // Fold successive additions like (d0 + 2) + 3 into d0 + 5.
547   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
548   if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Add) {
549     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>())
550       return lBin.getLHS() + (lrhs.getValue() + rhsConst.getValue());
551   }
552 
553   // Detect "c1 * expr + c_2 * expr" as "(c1 + c2) * expr".
554   // c1 is rRhsConst, c2 is rLhsConst; firstExpr, secondExpr are their
555   // respective multiplicands.
556   Optional<int64_t> rLhsConst, rRhsConst;
557   AffineExpr firstExpr, secondExpr;
558   AffineConstantExpr rLhsConstExpr;
559   auto lBinOpExpr = lhs.dyn_cast<AffineBinaryOpExpr>();
560   if (lBinOpExpr && lBinOpExpr.getKind() == AffineExprKind::Mul &&
561       (rLhsConstExpr = lBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) {
562     rLhsConst = rLhsConstExpr.getValue();
563     firstExpr = lBinOpExpr.getLHS();
564   } else {
565     rLhsConst = 1;
566     firstExpr = lhs;
567   }
568 
569   auto rBinOpExpr = rhs.dyn_cast<AffineBinaryOpExpr>();
570   AffineConstantExpr rRhsConstExpr;
571   if (rBinOpExpr && rBinOpExpr.getKind() == AffineExprKind::Mul &&
572       (rRhsConstExpr = rBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) {
573     rRhsConst = rRhsConstExpr.getValue();
574     secondExpr = rBinOpExpr.getLHS();
575   } else {
576     rRhsConst = 1;
577     secondExpr = rhs;
578   }
579 
580   if (rLhsConst && rRhsConst && firstExpr == secondExpr)
581     return getAffineBinaryOpExpr(
582         AffineExprKind::Mul, firstExpr,
583         getAffineConstantExpr(rLhsConst.getValue() + rRhsConst.getValue(),
584                               lhs.getContext()));
585 
586   // When doing successive additions, bring constant to the right: turn (d0 + 2)
587   // + d1 into (d0 + d1) + 2.
588   if (lBin && lBin.getKind() == AffineExprKind::Add) {
589     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
590       return lBin.getLHS() + rhs + lrhs;
591     }
592   }
593 
594   // Detect and transform "expr - c * (expr floordiv c)" to "expr mod c". This
595   // leads to a much more efficient form when 'c' is a power of two, and in
596   // general a more compact and readable form.
597 
598   // Process '(expr floordiv c) * (-c)'.
599   if (!rBinOpExpr)
600     return nullptr;
601 
602   auto lrhs = rBinOpExpr.getLHS();
603   auto rrhs = rBinOpExpr.getRHS();
604 
605   // Process lrhs, which is 'expr floordiv c'.
606   AffineBinaryOpExpr lrBinOpExpr = lrhs.dyn_cast<AffineBinaryOpExpr>();
607   if (!lrBinOpExpr || lrBinOpExpr.getKind() != AffineExprKind::FloorDiv)
608     return nullptr;
609 
610   auto llrhs = lrBinOpExpr.getLHS();
611   auto rlrhs = lrBinOpExpr.getRHS();
612 
613   if (lhs == llrhs && rlrhs == -rrhs) {
614     return lhs % rlrhs;
615   }
616   return nullptr;
617 }
618 
619 AffineExpr AffineExpr::operator+(int64_t v) const {
620   return *this + getAffineConstantExpr(v, getContext());
621 }
622 AffineExpr AffineExpr::operator+(AffineExpr other) const {
623   if (auto simplified = simplifyAdd(*this, other))
624     return simplified;
625 
626   StorageUniquer &uniquer = getContext()->getAffineUniquer();
627   return uniquer.get<AffineBinaryOpExprStorage>(
628       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Add), *this, other);
629 }
630 
631 /// Simplify a multiply expression. Return nullptr if it can't be simplified.
632 static AffineExpr simplifyMul(AffineExpr lhs, AffineExpr rhs) {
633   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
634   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
635 
636   if (lhsConst && rhsConst)
637     return getAffineConstantExpr(lhsConst.getValue() * rhsConst.getValue(),
638                                  lhs.getContext());
639 
640   assert(lhs.isSymbolicOrConstant() || rhs.isSymbolicOrConstant());
641 
642   // Canonicalize the mul expression so that the constant/symbolic term is the
643   // RHS. If both the lhs and rhs are symbolic, swap them if the lhs is a
644   // constant. (Note that a constant is trivially symbolic).
645   if (!rhs.isSymbolicOrConstant() || lhs.isa<AffineConstantExpr>()) {
646     // At least one of them has to be symbolic.
647     return rhs * lhs;
648   }
649 
650   // At this point, if there was a constant, it would be on the right.
651 
652   // Multiplication with a one is a noop, return the other input.
653   if (rhsConst) {
654     if (rhsConst.getValue() == 1)
655       return lhs;
656     // Multiplication with zero.
657     if (rhsConst.getValue() == 0)
658       return rhsConst;
659   }
660 
661   // Fold successive multiplications: eg: (d0 * 2) * 3 into d0 * 6.
662   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
663   if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Mul) {
664     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>())
665       return lBin.getLHS() * (lrhs.getValue() * rhsConst.getValue());
666   }
667 
668   // When doing successive multiplication, bring constant to the right: turn (d0
669   // * 2) * d1 into (d0 * d1) * 2.
670   if (lBin && lBin.getKind() == AffineExprKind::Mul) {
671     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
672       return (lBin.getLHS() * rhs) * lrhs;
673     }
674   }
675 
676   return nullptr;
677 }
678 
679 AffineExpr AffineExpr::operator*(int64_t v) const {
680   return *this * getAffineConstantExpr(v, getContext());
681 }
682 AffineExpr AffineExpr::operator*(AffineExpr other) const {
683   if (auto simplified = simplifyMul(*this, other))
684     return simplified;
685 
686   StorageUniquer &uniquer = getContext()->getAffineUniquer();
687   return uniquer.get<AffineBinaryOpExprStorage>(
688       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mul), *this, other);
689 }
690 
691 // Unary minus, delegate to operator*.
692 AffineExpr AffineExpr::operator-() const {
693   return *this * getAffineConstantExpr(-1, getContext());
694 }
695 
696 // Delegate to operator+.
697 AffineExpr AffineExpr::operator-(int64_t v) const { return *this + (-v); }
698 AffineExpr AffineExpr::operator-(AffineExpr other) const {
699   return *this + (-other);
700 }
701 
702 static AffineExpr simplifyFloorDiv(AffineExpr lhs, AffineExpr rhs) {
703   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
704   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
705 
706   // mlir floordiv by zero or negative numbers is undefined and preserved as is.
707   if (!rhsConst || rhsConst.getValue() < 1)
708     return nullptr;
709 
710   if (lhsConst)
711     return getAffineConstantExpr(
712         floorDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext());
713 
714   // Fold floordiv of a multiply with a constant that is a multiple of the
715   // divisor. Eg: (i * 128) floordiv 64 = i * 2.
716   if (rhsConst == 1)
717     return lhs;
718 
719   // Simplify (expr * const) floordiv divConst when expr is known to be a
720   // multiple of divConst.
721   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
722   if (lBin && lBin.getKind() == AffineExprKind::Mul) {
723     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
724       // rhsConst is known to be a positive constant.
725       if (lrhs.getValue() % rhsConst.getValue() == 0)
726         return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue());
727     }
728   }
729 
730   // Simplify (expr1 + expr2) floordiv divConst when either expr1 or expr2 is
731   // known to be a multiple of divConst.
732   if (lBin && lBin.getKind() == AffineExprKind::Add) {
733     int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor();
734     int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor();
735     // rhsConst is known to be a positive constant.
736     if (llhsDiv % rhsConst.getValue() == 0 ||
737         lrhsDiv % rhsConst.getValue() == 0)
738       return lBin.getLHS().floorDiv(rhsConst.getValue()) +
739              lBin.getRHS().floorDiv(rhsConst.getValue());
740   }
741 
742   return nullptr;
743 }
744 
745 AffineExpr AffineExpr::floorDiv(uint64_t v) const {
746   return floorDiv(getAffineConstantExpr(v, getContext()));
747 }
748 AffineExpr AffineExpr::floorDiv(AffineExpr other) const {
749   if (auto simplified = simplifyFloorDiv(*this, other))
750     return simplified;
751 
752   StorageUniquer &uniquer = getContext()->getAffineUniquer();
753   return uniquer.get<AffineBinaryOpExprStorage>(
754       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::FloorDiv), *this,
755       other);
756 }
757 
758 static AffineExpr simplifyCeilDiv(AffineExpr lhs, AffineExpr rhs) {
759   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
760   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
761 
762   if (!rhsConst || rhsConst.getValue() < 1)
763     return nullptr;
764 
765   if (lhsConst)
766     return getAffineConstantExpr(
767         ceilDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext());
768 
769   // Fold ceildiv of a multiply with a constant that is a multiple of the
770   // divisor. Eg: (i * 128) ceildiv 64 = i * 2.
771   if (rhsConst.getValue() == 1)
772     return lhs;
773 
774   // Simplify (expr * const) ceildiv divConst when const is known to be a
775   // multiple of divConst.
776   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
777   if (lBin && lBin.getKind() == AffineExprKind::Mul) {
778     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
779       // rhsConst is known to be a positive constant.
780       if (lrhs.getValue() % rhsConst.getValue() == 0)
781         return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue());
782     }
783   }
784 
785   return nullptr;
786 }
787 
788 AffineExpr AffineExpr::ceilDiv(uint64_t v) const {
789   return ceilDiv(getAffineConstantExpr(v, getContext()));
790 }
791 AffineExpr AffineExpr::ceilDiv(AffineExpr other) const {
792   if (auto simplified = simplifyCeilDiv(*this, other))
793     return simplified;
794 
795   StorageUniquer &uniquer = getContext()->getAffineUniquer();
796   return uniquer.get<AffineBinaryOpExprStorage>(
797       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::CeilDiv), *this,
798       other);
799 }
800 
801 static AffineExpr simplifyMod(AffineExpr lhs, AffineExpr rhs) {
802   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
803   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
804 
805   // mod w.r.t zero or negative numbers is undefined and preserved as is.
806   if (!rhsConst || rhsConst.getValue() < 1)
807     return nullptr;
808 
809   if (lhsConst)
810     return getAffineConstantExpr(mod(lhsConst.getValue(), rhsConst.getValue()),
811                                  lhs.getContext());
812 
813   // Fold modulo of an expression that is known to be a multiple of a constant
814   // to zero if that constant is a multiple of the modulo factor. Eg: (i * 128)
815   // mod 64 is folded to 0, and less trivially, (i*(j*4*(k*32))) mod 128 = 0.
816   if (lhs.getLargestKnownDivisor() % rhsConst.getValue() == 0)
817     return getAffineConstantExpr(0, lhs.getContext());
818 
819   // Simplify (expr1 + expr2) mod divConst when either expr1 or expr2 is
820   // known to be a multiple of divConst.
821   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
822   if (lBin && lBin.getKind() == AffineExprKind::Add) {
823     int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor();
824     int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor();
825     // rhsConst is known to be a positive constant.
826     if (llhsDiv % rhsConst.getValue() == 0)
827       return lBin.getRHS() % rhsConst.getValue();
828     if (lrhsDiv % rhsConst.getValue() == 0)
829       return lBin.getLHS() % rhsConst.getValue();
830   }
831 
832   // Simplify (e % a) % b to e % b when b evenly divides a
833   if (lBin && lBin.getKind() == AffineExprKind::Mod) {
834     auto intermediate = lBin.getRHS().dyn_cast<AffineConstantExpr>();
835     if (intermediate && intermediate.getValue() >= 1 &&
836         mod(intermediate.getValue(), rhsConst.getValue()) == 0) {
837       return lBin.getLHS() % rhsConst.getValue();
838     }
839   }
840 
841   return nullptr;
842 }
843 
844 AffineExpr AffineExpr::operator%(uint64_t v) const {
845   return *this % getAffineConstantExpr(v, getContext());
846 }
847 AffineExpr AffineExpr::operator%(AffineExpr other) const {
848   if (auto simplified = simplifyMod(*this, other))
849     return simplified;
850 
851   StorageUniquer &uniquer = getContext()->getAffineUniquer();
852   return uniquer.get<AffineBinaryOpExprStorage>(
853       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mod), *this, other);
854 }
855 
856 AffineExpr AffineExpr::compose(AffineMap map) const {
857   SmallVector<AffineExpr, 8> dimReplacements(map.getResults().begin(),
858                                              map.getResults().end());
859   return replaceDimsAndSymbols(dimReplacements, {});
860 }
861 raw_ostream &mlir::operator<<(raw_ostream &os, AffineExpr expr) {
862   expr.print(os);
863   return os;
864 }
865 
866 /// Constructs an affine expression from a flat ArrayRef. If there are local
867 /// identifiers (neither dimensional nor symbolic) that appear in the sum of
868 /// products expression, `localExprs` is expected to have the AffineExpr
869 /// for it, and is substituted into. The ArrayRef `flatExprs` is expected to be
870 /// in the format [dims, symbols, locals, constant term].
871 AffineExpr mlir::getAffineExprFromFlatForm(ArrayRef<int64_t> flatExprs,
872                                            unsigned numDims,
873                                            unsigned numSymbols,
874                                            ArrayRef<AffineExpr> localExprs,
875                                            MLIRContext *context) {
876   // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1.
877   assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() &&
878          "unexpected number of local expressions");
879 
880   auto expr = getAffineConstantExpr(0, context);
881   // Dimensions and symbols.
882   for (unsigned j = 0; j < numDims + numSymbols; j++) {
883     if (flatExprs[j] == 0)
884       continue;
885     auto id = j < numDims ? getAffineDimExpr(j, context)
886                           : getAffineSymbolExpr(j - numDims, context);
887     expr = expr + id * flatExprs[j];
888   }
889 
890   // Local identifiers.
891   for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e;
892        j++) {
893     if (flatExprs[j] == 0)
894       continue;
895     auto term = localExprs[j - numDims - numSymbols] * flatExprs[j];
896     expr = expr + term;
897   }
898 
899   // Constant term.
900   int64_t constTerm = flatExprs[flatExprs.size() - 1];
901   if (constTerm != 0)
902     expr = expr + constTerm;
903   return expr;
904 }
905 
906 /// Constructs a semi-affine expression from a flat ArrayRef. If there are
907 /// local identifiers (neither dimensional nor symbolic) that appear in the sum
908 /// of products expression, `localExprs` is expected to have the AffineExprs for
909 /// it, and is substituted into. The ArrayRef `flatExprs` is expected to be in
910 /// the format [dims, symbols, locals, constant term]. The semi-affine
911 /// expression is constructed in the sorted order of dimension and symbol
912 /// position numbers. Note:  local expressions/ids are used for mod, div as well
913 /// as symbolic RHS terms for terms that are not pure affine.
914 static AffineExpr getSemiAffineExprFromFlatForm(ArrayRef<int64_t> flatExprs,
915                                                 unsigned numDims,
916                                                 unsigned numSymbols,
917                                                 ArrayRef<AffineExpr> localExprs,
918                                                 MLIRContext *context) {
919   assert(!flatExprs.empty() && "flatExprs cannot be empty");
920 
921   // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1.
922   assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() &&
923          "unexpected number of local expressions");
924 
925   AffineExpr expr = getAffineConstantExpr(0, context);
926 
927   // We design indices as a pair which help us present the semi-affine map as
928   // sum of product where terms are sorted based on dimension or symbol
929   // position: <keyA, keyB> for expressions of the form dimension * symbol,
930   // where keyA is the position number of the dimension and keyB is the
931   // position number of the symbol. For dimensional expressions we set the index
932   // as (position number of the dimension, -1), as we want dimensional
933   // expressions to appear before symbolic and product of dimensional and
934   // symbolic expressions having the dimension with the same position number.
935   // For symbolic expression set the index as (position number of the symbol,
936   // maximum of last dimension and symbol position) number. For example, we want
937   // the expression we are constructing to look something like: d0 + d0 * s0 +
938   // s0 + d1*s1 + s1.
939 
940   // Stores the affine expression corresponding to a given index.
941   DenseMap<std::pair<unsigned, signed>, AffineExpr> indexToExprMap;
942   // Stores the constant coefficient value corresponding to a given
943   // dimension, symbol or a non-pure affine expression stored in `localExprs`.
944   DenseMap<std::pair<unsigned, signed>, int64_t> coefficients;
945   // Stores the indices as defined above, and later sorted to produce
946   // the semi-affine expression in the desired form.
947   SmallVector<std::pair<unsigned, signed>, 8> indices;
948 
949   // Example: expression = d0 + d0 * s0 + 2 * s0.
950   // indices = [{0,-1}, {0, 0}, {0, 1}]
951   // coefficients = [{{0, -1}, 1}, {{0, 0}, 1}, {{0, 1}, 2}]
952   // indexToExprMap = [{{0, -1}, d0}, {{0, 0}, d0 * s0}, {{0, 1}, s0}]
953 
954   // Adds entries to `indexToExprMap`, `coefficients` and `indices`.
955   auto addEntry = [&](std::pair<unsigned, signed> index, int64_t coefficient,
956                       AffineExpr expr) {
957     assert(std::find(indices.begin(), indices.end(), index) == indices.end() &&
958            "Key is already present in indices vector and overwriting will "
959            "happen in `indexToExprMap` and `coefficients`!");
960 
961     indices.push_back(index);
962     coefficients.insert({index, coefficient});
963     indexToExprMap.insert({index, expr});
964   };
965 
966   // Design indices for dimensional or symbolic terms, and store the indices,
967   // constant coefficient corresponding to the indices in `coefficients` map,
968   // and affine expression corresponding to indices in `indexToExprMap` map.
969 
970   for (unsigned j = 0; j < numDims; ++j) {
971     if (flatExprs[j] == 0)
972       continue;
973     // For dimensional expressions we set the index as <position number of the
974     // dimension, 0>, as we want dimensional expressions to appear before
975     // symbolic ones and products of dimensional and symbolic expressions
976     // having the dimension with the same position number.
977     std::pair<unsigned, signed> indexEntry(j, -1);
978     addEntry(indexEntry, flatExprs[j], getAffineDimExpr(j, context));
979   }
980   for (unsigned j = numDims; j < numDims + numSymbols; ++j) {
981     if (flatExprs[j] == 0)
982       continue;
983     // For symbolic expression set the index as <position number
984     // of the symbol, max(dimCount, symCount)> number,
985     // as we want symbolic expressions with the same positional number to
986     // appear after dimensional expressions having the same positional number.
987     std::pair<unsigned, signed> indexEntry(j - numDims,
988                                            std::max(numDims, numSymbols));
989     addEntry(indexEntry, flatExprs[j],
990              getAffineSymbolExpr(j - numDims, context));
991   }
992 
993   // Denotes semi-affine product, modulo or division terms, which has been added
994   // to the `indexToExpr` map.
995   SmallVector<bool, 4> addedToMap(flatExprs.size() - numDims - numSymbols - 1,
996                                   false);
997   unsigned lhsPos, rhsPos;
998   // Construct indices for product terms involving dimension, symbol or constant
999   // as lhs/rhs, and store the indices, constant coefficient corresponding to
1000   // the indices in `coefficients` map, and affine expression corresponding to
1001   // in indices in `indexToExprMap` map.
1002   for (auto it : llvm::enumerate(localExprs)) {
1003     AffineExpr expr = it.value();
1004     if (flatExprs[numDims + numSymbols + it.index()] == 0)
1005       continue;
1006     AffineExpr lhs = expr.cast<AffineBinaryOpExpr>().getLHS();
1007     AffineExpr rhs = expr.cast<AffineBinaryOpExpr>().getRHS();
1008     if (!((lhs.isa<AffineDimExpr>() || lhs.isa<AffineSymbolExpr>()) &&
1009           (rhs.isa<AffineDimExpr>() || rhs.isa<AffineSymbolExpr>() ||
1010            rhs.isa<AffineConstantExpr>()))) {
1011       continue;
1012     }
1013     if (rhs.isa<AffineConstantExpr>()) {
1014       // For product/modulo/division expressions, when rhs of modulo/division
1015       // expression is constant, we put 0 in place of keyB, because we want
1016       // them to appear earlier in the semi-affine expression we are
1017       // constructing. When rhs is constant, we place 0 in place of keyB.
1018       if (lhs.isa<AffineDimExpr>()) {
1019         lhsPos = lhs.cast<AffineDimExpr>().getPosition();
1020         std::pair<unsigned, signed> indexEntry(lhsPos, -1);
1021         addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()],
1022                  expr);
1023       } else {
1024         lhsPos = lhs.cast<AffineSymbolExpr>().getPosition();
1025         std::pair<unsigned, signed> indexEntry(lhsPos,
1026                                                std::max(numDims, numSymbols));
1027         addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()],
1028                  expr);
1029       }
1030     } else if (lhs.isa<AffineDimExpr>()) {
1031       // For product/modulo/division expressions having lhs as dimension and rhs
1032       // as symbol, we order the terms in the semi-affine expression based on
1033       // the pair: <keyA, keyB> for expressions of the form dimension * symbol,
1034       // where keyA is the position number of the dimension and keyB is the
1035       // position number of the symbol.
1036       lhsPos = lhs.cast<AffineDimExpr>().getPosition();
1037       rhsPos = rhs.cast<AffineSymbolExpr>().getPosition();
1038       std::pair<unsigned, signed> indexEntry(lhsPos, rhsPos);
1039       addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()], expr);
1040     } else {
1041       // For product/modulo/division expressions having both lhs and rhs as
1042       // symbol, we design indices as a pair: <keyA, keyB> for expressions
1043       // of the form dimension * symbol, where keyA is the position number of
1044       // the dimension and keyB is the position number of the symbol.
1045       lhsPos = lhs.cast<AffineSymbolExpr>().getPosition();
1046       rhsPos = rhs.cast<AffineSymbolExpr>().getPosition();
1047       std::pair<unsigned, signed> indexEntry(lhsPos, rhsPos);
1048       addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()], expr);
1049     }
1050     addedToMap[it.index()] = true;
1051   }
1052 
1053   // Constructing the simplified semi-affine sum of product/division/mod
1054   // expression from the flattened form in the desired sorted order of indices
1055   // of the various individual product/division/mod expressions.
1056   std::sort(indices.begin(), indices.end());
1057   for (const std::pair<unsigned, unsigned> index : indices) {
1058     assert(indexToExprMap.lookup(index) &&
1059            "cannot find key in `indexToExprMap` map");
1060     expr = expr + indexToExprMap.lookup(index) * coefficients.lookup(index);
1061   }
1062 
1063   // Local identifiers.
1064   for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e;
1065        j++) {
1066     // If the coefficient of the local expression is 0, continue as we need not
1067     // add it in out final expression.
1068     if (flatExprs[j] == 0 || addedToMap[j - numDims - numSymbols])
1069       continue;
1070     auto term = localExprs[j - numDims - numSymbols] * flatExprs[j];
1071     expr = expr + term;
1072   }
1073 
1074   // Constant term.
1075   int64_t constTerm = flatExprs.back();
1076   if (constTerm != 0)
1077     expr = expr + constTerm;
1078   return expr;
1079 }
1080 
1081 SimpleAffineExprFlattener::SimpleAffineExprFlattener(unsigned numDims,
1082                                                      unsigned numSymbols)
1083     : numDims(numDims), numSymbols(numSymbols), numLocals(0) {
1084   operandExprStack.reserve(8);
1085 }
1086 
1087 // In pure affine t = expr * c, we multiply each coefficient of lhs with c.
1088 //
1089 // In case of semi affine multiplication expressions, t = expr * symbolic_expr,
1090 // introduce a local variable p (= expr * symbolic_expr), and the affine
1091 // expression expr * symbolic_expr is added to `localExprs`.
1092 void SimpleAffineExprFlattener::visitMulExpr(AffineBinaryOpExpr expr) {
1093   assert(operandExprStack.size() >= 2);
1094   SmallVector<int64_t, 8> rhs = operandExprStack.back();
1095   operandExprStack.pop_back();
1096   SmallVector<int64_t, 8> &lhs = operandExprStack.back();
1097 
1098   // Flatten semi-affine multiplication expressions by introducing a local
1099   // variable in place of the product; the affine expression
1100   // corresponding to the quantifier is added to `localExprs`.
1101   if (!expr.getRHS().isa<AffineConstantExpr>()) {
1102     MLIRContext *context = expr.getContext();
1103     AffineExpr a = getAffineExprFromFlatForm(lhs, numDims, numSymbols,
1104                                              localExprs, context);
1105     AffineExpr b = getAffineExprFromFlatForm(rhs, numDims, numSymbols,
1106                                              localExprs, context);
1107     addLocalVariableSemiAffine(a * b, lhs, lhs.size());
1108     return;
1109   }
1110 
1111   // Get the RHS constant.
1112   auto rhsConst = rhs[getConstantIndex()];
1113   for (unsigned i = 0, e = lhs.size(); i < e; i++) {
1114     lhs[i] *= rhsConst;
1115   }
1116 }
1117 
1118 void SimpleAffineExprFlattener::visitAddExpr(AffineBinaryOpExpr expr) {
1119   assert(operandExprStack.size() >= 2);
1120   const auto &rhs = operandExprStack.back();
1121   auto &lhs = operandExprStack[operandExprStack.size() - 2];
1122   assert(lhs.size() == rhs.size());
1123   // Update the LHS in place.
1124   for (unsigned i = 0, e = rhs.size(); i < e; i++) {
1125     lhs[i] += rhs[i];
1126   }
1127   // Pop off the RHS.
1128   operandExprStack.pop_back();
1129 }
1130 
1131 //
1132 // t = expr mod c   <=>  t = expr - c*q and c*q <= expr <= c*q + c - 1
1133 //
1134 // A mod expression "expr mod c" is thus flattened by introducing a new local
1135 // variable q (= expr floordiv c), such that expr mod c is replaced with
1136 // 'expr - c * q' and c * q <= expr <= c * q + c - 1 are added to localVarCst.
1137 //
1138 // In case of semi-affine modulo expressions, t = expr mod symbolic_expr,
1139 // introduce a local variable m (= expr mod symbolic_expr), and the affine
1140 // expression expr mod symbolic_expr is added to `localExprs`.
1141 void SimpleAffineExprFlattener::visitModExpr(AffineBinaryOpExpr expr) {
1142   assert(operandExprStack.size() >= 2);
1143 
1144   SmallVector<int64_t, 8> rhs = operandExprStack.back();
1145   operandExprStack.pop_back();
1146   SmallVector<int64_t, 8> &lhs = operandExprStack.back();
1147   MLIRContext *context = expr.getContext();
1148 
1149   // Flatten semi affine modulo expressions by introducing a local
1150   // variable in place of the modulo value, and the affine expression
1151   // corresponding to the quantifier is added to `localExprs`.
1152   if (!expr.getRHS().isa<AffineConstantExpr>()) {
1153     AffineExpr dividendExpr = getAffineExprFromFlatForm(
1154         lhs, numDims, numSymbols, localExprs, context);
1155     AffineExpr divisorExpr = getAffineExprFromFlatForm(rhs, numDims, numSymbols,
1156                                                        localExprs, context);
1157     AffineExpr modExpr = dividendExpr % divisorExpr;
1158     addLocalVariableSemiAffine(modExpr, lhs, lhs.size());
1159     return;
1160   }
1161 
1162   int64_t rhsConst = rhs[getConstantIndex()];
1163   // TODO: handle modulo by zero case when this issue is fixed
1164   // at the other places in the IR.
1165   assert(rhsConst > 0 && "RHS constant has to be positive");
1166 
1167   // Check if the LHS expression is a multiple of modulo factor.
1168   unsigned i, e;
1169   for (i = 0, e = lhs.size(); i < e; i++)
1170     if (lhs[i] % rhsConst != 0)
1171       break;
1172   // If yes, modulo expression here simplifies to zero.
1173   if (i == lhs.size()) {
1174     std::fill(lhs.begin(), lhs.end(), 0);
1175     return;
1176   }
1177 
1178   // Add a local variable for the quotient, i.e., expr % c is replaced by
1179   // (expr - q * c) where q = expr floordiv c. Do this while canceling out
1180   // the GCD of expr and c.
1181   SmallVector<int64_t, 8> floorDividend(lhs);
1182   uint64_t gcd = rhsConst;
1183   for (unsigned i = 0, e = lhs.size(); i < e; i++)
1184     gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i]));
1185   // Simplify the numerator and the denominator.
1186   if (gcd != 1) {
1187     for (unsigned i = 0, e = floorDividend.size(); i < e; i++)
1188       floorDividend[i] = floorDividend[i] / static_cast<int64_t>(gcd);
1189   }
1190   int64_t floorDivisor = rhsConst / static_cast<int64_t>(gcd);
1191 
1192   // Construct the AffineExpr form of the floordiv to store in localExprs.
1193 
1194   AffineExpr dividendExpr = getAffineExprFromFlatForm(
1195       floorDividend, numDims, numSymbols, localExprs, context);
1196   AffineExpr divisorExpr = getAffineConstantExpr(floorDivisor, context);
1197   AffineExpr floorDivExpr = dividendExpr.floorDiv(divisorExpr);
1198   int loc;
1199   if ((loc = findLocalId(floorDivExpr)) == -1) {
1200     addLocalFloorDivId(floorDividend, floorDivisor, floorDivExpr);
1201     // Set result at top of stack to "lhs - rhsConst * q".
1202     lhs[getLocalVarStartIndex() + numLocals - 1] = -rhsConst;
1203   } else {
1204     // Reuse the existing local id.
1205     lhs[getLocalVarStartIndex() + loc] = -rhsConst;
1206   }
1207 }
1208 
1209 void SimpleAffineExprFlattener::visitCeilDivExpr(AffineBinaryOpExpr expr) {
1210   visitDivExpr(expr, /*isCeil=*/true);
1211 }
1212 void SimpleAffineExprFlattener::visitFloorDivExpr(AffineBinaryOpExpr expr) {
1213   visitDivExpr(expr, /*isCeil=*/false);
1214 }
1215 
1216 void SimpleAffineExprFlattener::visitDimExpr(AffineDimExpr expr) {
1217   operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
1218   auto &eq = operandExprStack.back();
1219   assert(expr.getPosition() < numDims && "Inconsistent number of dims");
1220   eq[getDimStartIndex() + expr.getPosition()] = 1;
1221 }
1222 
1223 void SimpleAffineExprFlattener::visitSymbolExpr(AffineSymbolExpr expr) {
1224   operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
1225   auto &eq = operandExprStack.back();
1226   assert(expr.getPosition() < numSymbols && "inconsistent number of symbols");
1227   eq[getSymbolStartIndex() + expr.getPosition()] = 1;
1228 }
1229 
1230 void SimpleAffineExprFlattener::visitConstantExpr(AffineConstantExpr expr) {
1231   operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
1232   auto &eq = operandExprStack.back();
1233   eq[getConstantIndex()] = expr.getValue();
1234 }
1235 
1236 void SimpleAffineExprFlattener::addLocalVariableSemiAffine(
1237     AffineExpr expr, SmallVectorImpl<int64_t> &result,
1238     unsigned long resultSize) {
1239   assert(result.size() == resultSize &&
1240          "`result` vector passed is not of correct size");
1241   int loc;
1242   if ((loc = findLocalId(expr)) == -1)
1243     addLocalIdSemiAffine(expr);
1244   std::fill(result.begin(), result.end(), 0);
1245   if (loc == -1)
1246     result[getLocalVarStartIndex() + numLocals - 1] = 1;
1247   else
1248     result[getLocalVarStartIndex() + loc] = 1;
1249 }
1250 
1251 // t = expr floordiv c   <=> t = q, c * q <= expr <= c * q + c - 1
1252 // A floordiv is thus flattened by introducing a new local variable q, and
1253 // replacing that expression with 'q' while adding the constraints
1254 // c * q <= expr <= c * q + c - 1 to localVarCst (done by
1255 // FlatAffineConstraints::addLocalFloorDiv).
1256 //
1257 // A ceildiv is similarly flattened:
1258 // t = expr ceildiv c   <=> t =  (expr + c - 1) floordiv c
1259 //
1260 // In case of semi affine division expressions, t = expr floordiv symbolic_expr
1261 // or t = expr ceildiv symbolic_expr, introduce a local variable q (= expr
1262 // floordiv/ceildiv symbolic_expr), and the affine floordiv/ceildiv is added to
1263 // `localExprs`.
1264 void SimpleAffineExprFlattener::visitDivExpr(AffineBinaryOpExpr expr,
1265                                              bool isCeil) {
1266   assert(operandExprStack.size() >= 2);
1267 
1268   MLIRContext *context = expr.getContext();
1269   SmallVector<int64_t, 8> rhs = operandExprStack.back();
1270   operandExprStack.pop_back();
1271   SmallVector<int64_t, 8> &lhs = operandExprStack.back();
1272 
1273   // Flatten semi affine division expressions by introducing a local
1274   // variable in place of the quotient, and the affine expression corresponding
1275   // to the quantifier is added to `localExprs`.
1276   if (!expr.getRHS().isa<AffineConstantExpr>()) {
1277     AffineExpr a = getAffineExprFromFlatForm(lhs, numDims, numSymbols,
1278                                              localExprs, context);
1279     AffineExpr b = getAffineExprFromFlatForm(rhs, numDims, numSymbols,
1280                                              localExprs, context);
1281     AffineExpr divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b);
1282     addLocalVariableSemiAffine(divExpr, lhs, lhs.size());
1283     return;
1284   }
1285 
1286   // This is a pure affine expr; the RHS is a positive constant.
1287   int64_t rhsConst = rhs[getConstantIndex()];
1288   // TODO: handle division by zero at the same time the issue is
1289   // fixed at other places.
1290   assert(rhsConst > 0 && "RHS constant has to be positive");
1291 
1292   // Simplify the floordiv, ceildiv if possible by canceling out the greatest
1293   // common divisors of the numerator and denominator.
1294   uint64_t gcd = std::abs(rhsConst);
1295   for (unsigned i = 0, e = lhs.size(); i < e; i++)
1296     gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i]));
1297   // Simplify the numerator and the denominator.
1298   if (gcd != 1) {
1299     for (unsigned i = 0, e = lhs.size(); i < e; i++)
1300       lhs[i] = lhs[i] / static_cast<int64_t>(gcd);
1301   }
1302   int64_t divisor = rhsConst / static_cast<int64_t>(gcd);
1303   // If the divisor becomes 1, the updated LHS is the result. (The
1304   // divisor can't be negative since rhsConst is positive).
1305   if (divisor == 1)
1306     return;
1307 
1308   // If the divisor cannot be simplified to one, we will have to retain
1309   // the ceil/floor expr (simplified up until here). Add an existential
1310   // quantifier to express its result, i.e., expr1 div expr2 is replaced
1311   // by a new identifier, q.
1312   AffineExpr a =
1313       getAffineExprFromFlatForm(lhs, numDims, numSymbols, localExprs, context);
1314   AffineExpr b = getAffineConstantExpr(divisor, context);
1315 
1316   int loc;
1317   AffineExpr divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b);
1318   if ((loc = findLocalId(divExpr)) == -1) {
1319     if (!isCeil) {
1320       SmallVector<int64_t, 8> dividend(lhs);
1321       addLocalFloorDivId(dividend, divisor, divExpr);
1322     } else {
1323       // lhs ceildiv c <=>  (lhs + c - 1) floordiv c
1324       SmallVector<int64_t, 8> dividend(lhs);
1325       dividend.back() += divisor - 1;
1326       addLocalFloorDivId(dividend, divisor, divExpr);
1327     }
1328   }
1329   // Set the expression on stack to the local var introduced to capture the
1330   // result of the division (floor or ceil).
1331   std::fill(lhs.begin(), lhs.end(), 0);
1332   if (loc == -1)
1333     lhs[getLocalVarStartIndex() + numLocals - 1] = 1;
1334   else
1335     lhs[getLocalVarStartIndex() + loc] = 1;
1336 }
1337 
1338 // Add a local identifier (needed to flatten a mod, floordiv, ceildiv expr).
1339 // The local identifier added is always a floordiv of a pure add/mul affine
1340 // function of other identifiers, coefficients of which are specified in
1341 // dividend and with respect to a positive constant divisor. localExpr is the
1342 // simplified tree expression (AffineExpr) corresponding to the quantifier.
1343 void SimpleAffineExprFlattener::addLocalFloorDivId(ArrayRef<int64_t> dividend,
1344                                                    int64_t divisor,
1345                                                    AffineExpr localExpr) {
1346   assert(divisor > 0 && "positive constant divisor expected");
1347   for (SmallVector<int64_t, 8> &subExpr : operandExprStack)
1348     subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0);
1349   localExprs.push_back(localExpr);
1350   numLocals++;
1351   // dividend and divisor are not used here; an override of this method uses it.
1352 }
1353 
1354 void SimpleAffineExprFlattener::addLocalIdSemiAffine(AffineExpr localExpr) {
1355   for (SmallVector<int64_t, 8> &subExpr : operandExprStack)
1356     subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0);
1357   localExprs.push_back(localExpr);
1358   ++numLocals;
1359 }
1360 
1361 int SimpleAffineExprFlattener::findLocalId(AffineExpr localExpr) {
1362   SmallVectorImpl<AffineExpr>::iterator it;
1363   if ((it = llvm::find(localExprs, localExpr)) == localExprs.end())
1364     return -1;
1365   return it - localExprs.begin();
1366 }
1367 
1368 /// Simplify the affine expression by flattening it and reconstructing it.
1369 AffineExpr mlir::simplifyAffineExpr(AffineExpr expr, unsigned numDims,
1370                                     unsigned numSymbols) {
1371   // Simplify semi-affine expressions separately.
1372   if (!expr.isPureAffine())
1373     expr = simplifySemiAffine(expr);
1374 
1375   SimpleAffineExprFlattener flattener(numDims, numSymbols);
1376   flattener.walkPostOrder(expr);
1377   ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back();
1378   if (!expr.isPureAffine() &&
1379       expr == getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
1380                                         flattener.localExprs,
1381                                         expr.getContext()))
1382     return expr;
1383   AffineExpr simplifiedExpr =
1384       expr.isPureAffine()
1385           ? getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
1386                                       flattener.localExprs, expr.getContext())
1387           : getSemiAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
1388                                           flattener.localExprs,
1389                                           expr.getContext());
1390 
1391   flattener.operandExprStack.pop_back();
1392   assert(flattener.operandExprStack.empty());
1393   return simplifiedExpr;
1394 }
1395