1 //===- Utils.cpp ---- Utilities for affine dialect transformation ---------===//
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 // This file implements miscellaneous transformation utilities for the Affine
10 // dialect.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Dialect/Affine/Utils.h"
15 
16 #include "mlir/Dialect/Affine/Analysis/Utils.h"
17 #include "mlir/Dialect/Affine/IR/AffineOps.h"
18 #include "mlir/Dialect/Affine/IR/AffineValueMap.h"
19 #include "mlir/Dialect/Affine/LoopUtils.h"
20 #include "mlir/Dialect/Func/IR/FuncOps.h"
21 #include "mlir/Dialect/MemRef/IR/MemRef.h"
22 #include "mlir/IR/AffineExprVisitor.h"
23 #include "mlir/IR/BlockAndValueMapping.h"
24 #include "mlir/IR/Dominance.h"
25 #include "mlir/IR/IntegerSet.h"
26 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
27 
28 #define DEBUG_TYPE "affine-utils"
29 
30 using namespace mlir;
31 using namespace presburger;
32 
33 namespace {
34 /// Visit affine expressions recursively and build the sequence of operations
35 /// that correspond to it.  Visitation functions return an Value of the
36 /// expression subtree they visited or `nullptr` on error.
37 class AffineApplyExpander
38     : public AffineExprVisitor<AffineApplyExpander, Value> {
39 public:
40   /// This internal class expects arguments to be non-null, checks must be
41   /// performed at the call site.
42   AffineApplyExpander(OpBuilder &builder, ValueRange dimValues,
43                       ValueRange symbolValues, Location loc)
44       : builder(builder), dimValues(dimValues), symbolValues(symbolValues),
45         loc(loc) {}
46 
47   template <typename OpTy>
48   Value buildBinaryExpr(AffineBinaryOpExpr expr) {
49     auto lhs = visit(expr.getLHS());
50     auto rhs = visit(expr.getRHS());
51     if (!lhs || !rhs)
52       return nullptr;
53     auto op = builder.create<OpTy>(loc, lhs, rhs);
54     return op.getResult();
55   }
56 
57   Value visitAddExpr(AffineBinaryOpExpr expr) {
58     return buildBinaryExpr<arith::AddIOp>(expr);
59   }
60 
61   Value visitMulExpr(AffineBinaryOpExpr expr) {
62     return buildBinaryExpr<arith::MulIOp>(expr);
63   }
64 
65   /// Euclidean modulo operation: negative RHS is not allowed.
66   /// Remainder of the euclidean integer division is always non-negative.
67   ///
68   /// Implemented as
69   ///
70   ///     a mod b =
71   ///         let remainder = srem a, b;
72   ///             negative = a < 0 in
73   ///         select negative, remainder + b, remainder.
74   Value visitModExpr(AffineBinaryOpExpr expr) {
75     auto rhsConst = expr.getRHS().dyn_cast<AffineConstantExpr>();
76     if (!rhsConst) {
77       emitError(
78           loc,
79           "semi-affine expressions (modulo by non-const) are not supported");
80       return nullptr;
81     }
82     if (rhsConst.getValue() <= 0) {
83       emitError(loc, "modulo by non-positive value is not supported");
84       return nullptr;
85     }
86 
87     auto lhs = visit(expr.getLHS());
88     auto rhs = visit(expr.getRHS());
89     assert(lhs && rhs && "unexpected affine expr lowering failure");
90 
91     Value remainder = builder.create<arith::RemSIOp>(loc, lhs, rhs);
92     Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
93     Value isRemainderNegative = builder.create<arith::CmpIOp>(
94         loc, arith::CmpIPredicate::slt, remainder, zeroCst);
95     Value correctedRemainder =
96         builder.create<arith::AddIOp>(loc, remainder, rhs);
97     Value result = builder.create<arith::SelectOp>(
98         loc, isRemainderNegative, correctedRemainder, remainder);
99     return result;
100   }
101 
102   /// Floor division operation (rounds towards negative infinity).
103   ///
104   /// For positive divisors, it can be implemented without branching and with a
105   /// single division operation as
106   ///
107   ///        a floordiv b =
108   ///            let negative = a < 0 in
109   ///            let absolute = negative ? -a - 1 : a in
110   ///            let quotient = absolute / b in
111   ///                negative ? -quotient - 1 : quotient
112   Value visitFloorDivExpr(AffineBinaryOpExpr expr) {
113     auto rhsConst = expr.getRHS().dyn_cast<AffineConstantExpr>();
114     if (!rhsConst) {
115       emitError(
116           loc,
117           "semi-affine expressions (division by non-const) are not supported");
118       return nullptr;
119     }
120     if (rhsConst.getValue() <= 0) {
121       emitError(loc, "division by non-positive value is not supported");
122       return nullptr;
123     }
124 
125     auto lhs = visit(expr.getLHS());
126     auto rhs = visit(expr.getRHS());
127     assert(lhs && rhs && "unexpected affine expr lowering failure");
128 
129     Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
130     Value noneCst = builder.create<arith::ConstantIndexOp>(loc, -1);
131     Value negative = builder.create<arith::CmpIOp>(
132         loc, arith::CmpIPredicate::slt, lhs, zeroCst);
133     Value negatedDecremented = builder.create<arith::SubIOp>(loc, noneCst, lhs);
134     Value dividend =
135         builder.create<arith::SelectOp>(loc, negative, negatedDecremented, lhs);
136     Value quotient = builder.create<arith::DivSIOp>(loc, dividend, rhs);
137     Value correctedQuotient =
138         builder.create<arith::SubIOp>(loc, noneCst, quotient);
139     Value result = builder.create<arith::SelectOp>(loc, negative,
140                                                    correctedQuotient, quotient);
141     return result;
142   }
143 
144   /// Ceiling division operation (rounds towards positive infinity).
145   ///
146   /// For positive divisors, it can be implemented without branching and with a
147   /// single division operation as
148   ///
149   ///     a ceildiv b =
150   ///         let negative = a <= 0 in
151   ///         let absolute = negative ? -a : a - 1 in
152   ///         let quotient = absolute / b in
153   ///             negative ? -quotient : quotient + 1
154   Value visitCeilDivExpr(AffineBinaryOpExpr expr) {
155     auto rhsConst = expr.getRHS().dyn_cast<AffineConstantExpr>();
156     if (!rhsConst) {
157       emitError(loc) << "semi-affine expressions (division by non-const) are "
158                         "not supported";
159       return nullptr;
160     }
161     if (rhsConst.getValue() <= 0) {
162       emitError(loc, "division by non-positive value is not supported");
163       return nullptr;
164     }
165     auto lhs = visit(expr.getLHS());
166     auto rhs = visit(expr.getRHS());
167     assert(lhs && rhs && "unexpected affine expr lowering failure");
168 
169     Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
170     Value oneCst = builder.create<arith::ConstantIndexOp>(loc, 1);
171     Value nonPositive = builder.create<arith::CmpIOp>(
172         loc, arith::CmpIPredicate::sle, lhs, zeroCst);
173     Value negated = builder.create<arith::SubIOp>(loc, zeroCst, lhs);
174     Value decremented = builder.create<arith::SubIOp>(loc, lhs, oneCst);
175     Value dividend =
176         builder.create<arith::SelectOp>(loc, nonPositive, negated, decremented);
177     Value quotient = builder.create<arith::DivSIOp>(loc, dividend, rhs);
178     Value negatedQuotient =
179         builder.create<arith::SubIOp>(loc, zeroCst, quotient);
180     Value incrementedQuotient =
181         builder.create<arith::AddIOp>(loc, quotient, oneCst);
182     Value result = builder.create<arith::SelectOp>(
183         loc, nonPositive, negatedQuotient, incrementedQuotient);
184     return result;
185   }
186 
187   Value visitConstantExpr(AffineConstantExpr expr) {
188     auto op = builder.create<arith::ConstantIndexOp>(loc, expr.getValue());
189     return op.getResult();
190   }
191 
192   Value visitDimExpr(AffineDimExpr expr) {
193     assert(expr.getPosition() < dimValues.size() &&
194            "affine dim position out of range");
195     return dimValues[expr.getPosition()];
196   }
197 
198   Value visitSymbolExpr(AffineSymbolExpr expr) {
199     assert(expr.getPosition() < symbolValues.size() &&
200            "symbol dim position out of range");
201     return symbolValues[expr.getPosition()];
202   }
203 
204 private:
205   OpBuilder &builder;
206   ValueRange dimValues;
207   ValueRange symbolValues;
208 
209   Location loc;
210 };
211 } // namespace
212 
213 /// Create a sequence of operations that implement the `expr` applied to the
214 /// given dimension and symbol values.
215 mlir::Value mlir::expandAffineExpr(OpBuilder &builder, Location loc,
216                                    AffineExpr expr, ValueRange dimValues,
217                                    ValueRange symbolValues) {
218   return AffineApplyExpander(builder, dimValues, symbolValues, loc).visit(expr);
219 }
220 
221 /// Create a sequence of operations that implement the `affineMap` applied to
222 /// the given `operands` (as it it were an AffineApplyOp).
223 Optional<SmallVector<Value, 8>> mlir::expandAffineMap(OpBuilder &builder,
224                                                       Location loc,
225                                                       AffineMap affineMap,
226                                                       ValueRange operands) {
227   auto numDims = affineMap.getNumDims();
228   auto expanded = llvm::to_vector<8>(
229       llvm::map_range(affineMap.getResults(),
230                       [numDims, &builder, loc, operands](AffineExpr expr) {
231                         return expandAffineExpr(builder, loc, expr,
232                                                 operands.take_front(numDims),
233                                                 operands.drop_front(numDims));
234                       }));
235   if (llvm::all_of(expanded, [](Value v) { return v; }))
236     return expanded;
237   return None;
238 }
239 
240 /// Promotes the `then` or the `else` block of `ifOp` (depending on whether
241 /// `elseBlock` is false or true) into `ifOp`'s containing block, and discards
242 /// the rest of the op.
243 static void promoteIfBlock(AffineIfOp ifOp, bool elseBlock) {
244   if (elseBlock)
245     assert(ifOp.hasElse() && "else block expected");
246 
247   Block *destBlock = ifOp->getBlock();
248   Block *srcBlock = elseBlock ? ifOp.getElseBlock() : ifOp.getThenBlock();
249   destBlock->getOperations().splice(
250       Block::iterator(ifOp), srcBlock->getOperations(), srcBlock->begin(),
251       std::prev(srcBlock->end()));
252   ifOp.erase();
253 }
254 
255 /// Returns the outermost affine.for/parallel op that the `ifOp` is invariant
256 /// on. The `ifOp` could be hoisted and placed right before such an operation.
257 /// This method assumes that the ifOp has been canonicalized (to be correct and
258 /// effective).
259 static Operation *getOutermostInvariantForOp(AffineIfOp ifOp) {
260   // Walk up the parents past all for op that this conditional is invariant on.
261   auto ifOperands = ifOp.getOperands();
262   auto *res = ifOp.getOperation();
263   while (!isa<FuncOp>(res->getParentOp())) {
264     auto *parentOp = res->getParentOp();
265     if (auto forOp = dyn_cast<AffineForOp>(parentOp)) {
266       if (llvm::is_contained(ifOperands, forOp.getInductionVar()))
267         break;
268     } else if (auto parallelOp = dyn_cast<AffineParallelOp>(parentOp)) {
269       for (auto iv : parallelOp.getIVs())
270         if (llvm::is_contained(ifOperands, iv))
271           break;
272     } else if (!isa<AffineIfOp>(parentOp)) {
273       // Won't walk up past anything other than affine.for/if ops.
274       break;
275     }
276     // You can always hoist up past any affine.if ops.
277     res = parentOp;
278   }
279   return res;
280 }
281 
282 /// A helper for the mechanics of mlir::hoistAffineIfOp. Hoists `ifOp` just over
283 /// `hoistOverOp`. Returns the new hoisted op if any hoisting happened,
284 /// otherwise the same `ifOp`.
285 static AffineIfOp hoistAffineIfOp(AffineIfOp ifOp, Operation *hoistOverOp) {
286   // No hoisting to do.
287   if (hoistOverOp == ifOp)
288     return ifOp;
289 
290   // Create the hoisted 'if' first. Then, clone the op we are hoisting over for
291   // the else block. Then drop the else block of the original 'if' in the 'then'
292   // branch while promoting its then block, and analogously drop the 'then'
293   // block of the original 'if' from the 'else' branch while promoting its else
294   // block.
295   BlockAndValueMapping operandMap;
296   OpBuilder b(hoistOverOp);
297   auto hoistedIfOp = b.create<AffineIfOp>(ifOp.getLoc(), ifOp.getIntegerSet(),
298                                           ifOp.getOperands(),
299                                           /*elseBlock=*/true);
300 
301   // Create a clone of hoistOverOp to use for the else branch of the hoisted
302   // conditional. The else block may get optimized away if empty.
303   Operation *hoistOverOpClone = nullptr;
304   // We use this unique name to identify/find  `ifOp`'s clone in the else
305   // version.
306   StringAttr idForIfOp = b.getStringAttr("__mlir_if_hoisting");
307   operandMap.clear();
308   b.setInsertionPointAfter(hoistOverOp);
309   // We'll set an attribute to identify this op in a clone of this sub-tree.
310   ifOp->setAttr(idForIfOp, b.getBoolAttr(true));
311   hoistOverOpClone = b.clone(*hoistOverOp, operandMap);
312 
313   // Promote the 'then' block of the original affine.if in the then version.
314   promoteIfBlock(ifOp, /*elseBlock=*/false);
315 
316   // Move the then version to the hoisted if op's 'then' block.
317   auto *thenBlock = hoistedIfOp.getThenBlock();
318   thenBlock->getOperations().splice(thenBlock->begin(),
319                                     hoistOverOp->getBlock()->getOperations(),
320                                     Block::iterator(hoistOverOp));
321 
322   // Find the clone of the original affine.if op in the else version.
323   AffineIfOp ifCloneInElse;
324   hoistOverOpClone->walk([&](AffineIfOp ifClone) {
325     if (!ifClone->getAttr(idForIfOp))
326       return WalkResult::advance();
327     ifCloneInElse = ifClone;
328     return WalkResult::interrupt();
329   });
330   assert(ifCloneInElse && "if op clone should exist");
331   // For the else block, promote the else block of the original 'if' if it had
332   // one; otherwise, the op itself is to be erased.
333   if (!ifCloneInElse.hasElse())
334     ifCloneInElse.erase();
335   else
336     promoteIfBlock(ifCloneInElse, /*elseBlock=*/true);
337 
338   // Move the else version into the else block of the hoisted if op.
339   auto *elseBlock = hoistedIfOp.getElseBlock();
340   elseBlock->getOperations().splice(
341       elseBlock->begin(), hoistOverOpClone->getBlock()->getOperations(),
342       Block::iterator(hoistOverOpClone));
343 
344   return hoistedIfOp;
345 }
346 
347 LogicalResult
348 mlir::affineParallelize(AffineForOp forOp,
349                         ArrayRef<LoopReduction> parallelReductions) {
350   // Fail early if there are iter arguments that are not reductions.
351   unsigned numReductions = parallelReductions.size();
352   if (numReductions != forOp.getNumIterOperands())
353     return failure();
354 
355   Location loc = forOp.getLoc();
356   OpBuilder outsideBuilder(forOp);
357   AffineMap lowerBoundMap = forOp.getLowerBoundMap();
358   ValueRange lowerBoundOperands = forOp.getLowerBoundOperands();
359   AffineMap upperBoundMap = forOp.getUpperBoundMap();
360   ValueRange upperBoundOperands = forOp.getUpperBoundOperands();
361 
362   // Creating empty 1-D affine.parallel op.
363   auto reducedValues = llvm::to_vector<4>(llvm::map_range(
364       parallelReductions, [](const LoopReduction &red) { return red.value; }));
365   auto reductionKinds = llvm::to_vector<4>(llvm::map_range(
366       parallelReductions, [](const LoopReduction &red) { return red.kind; }));
367   AffineParallelOp newPloop = outsideBuilder.create<AffineParallelOp>(
368       loc, ValueRange(reducedValues).getTypes(), reductionKinds,
369       llvm::makeArrayRef(lowerBoundMap), lowerBoundOperands,
370       llvm::makeArrayRef(upperBoundMap), upperBoundOperands,
371       llvm::makeArrayRef(forOp.getStep()));
372   // Steal the body of the old affine for op.
373   newPloop.region().takeBody(forOp.region());
374   Operation *yieldOp = &newPloop.getBody()->back();
375 
376   // Handle the initial values of reductions because the parallel loop always
377   // starts from the neutral value.
378   SmallVector<Value> newResults;
379   newResults.reserve(numReductions);
380   for (unsigned i = 0; i < numReductions; ++i) {
381     Value init = forOp.getIterOperands()[i];
382     // This works because we are only handling single-op reductions at the
383     // moment. A switch on reduction kind or a mechanism to collect operations
384     // participating in the reduction will be necessary for multi-op reductions.
385     Operation *reductionOp = yieldOp->getOperand(i).getDefiningOp();
386     assert(reductionOp && "yielded value is expected to be produced by an op");
387     outsideBuilder.getInsertionBlock()->getOperations().splice(
388         outsideBuilder.getInsertionPoint(), newPloop.getBody()->getOperations(),
389         reductionOp);
390     reductionOp->setOperands({init, newPloop->getResult(i)});
391     forOp->getResult(i).replaceAllUsesWith(reductionOp->getResult(0));
392   }
393 
394   // Update the loop terminator to yield reduced values bypassing the reduction
395   // operation itself (now moved outside of the loop) and erase the block
396   // arguments that correspond to reductions. Note that the loop always has one
397   // "main" induction variable whenc coming from a non-parallel for.
398   unsigned numIVs = 1;
399   yieldOp->setOperands(reducedValues);
400   newPloop.getBody()->eraseArguments(
401       llvm::to_vector<4>(llvm::seq<unsigned>(numIVs, numReductions + numIVs)));
402 
403   forOp.erase();
404   return success();
405 }
406 
407 // Returns success if any hoisting happened.
408 LogicalResult mlir::hoistAffineIfOp(AffineIfOp ifOp, bool *folded) {
409   // Bail out early if the ifOp returns a result.  TODO: Consider how to
410   // properly support this case.
411   if (ifOp.getNumResults() != 0)
412     return failure();
413 
414   // Apply canonicalization patterns and folding - this is necessary for the
415   // hoisting check to be correct (operands should be composed), and to be more
416   // effective (no unused operands). Since the pattern rewriter's folding is
417   // entangled with application of patterns, we may fold/end up erasing the op,
418   // in which case we return with `folded` being set.
419   RewritePatternSet patterns(ifOp.getContext());
420   AffineIfOp::getCanonicalizationPatterns(patterns, ifOp.getContext());
421   bool erased;
422   FrozenRewritePatternSet frozenPatterns(std::move(patterns));
423   (void)applyOpPatternsAndFold(ifOp, frozenPatterns, &erased);
424   if (erased) {
425     if (folded)
426       *folded = true;
427     return failure();
428   }
429   if (folded)
430     *folded = false;
431 
432   // The folding above should have ensured this, but the affine.if's
433   // canonicalization is missing composition of affine.applys into it.
434   assert(llvm::all_of(ifOp.getOperands(),
435                       [](Value v) {
436                         return isTopLevelValue(v) || isForInductionVar(v);
437                       }) &&
438          "operands not composed");
439 
440   // We are going hoist as high as possible.
441   // TODO: this could be customized in the future.
442   auto *hoistOverOp = getOutermostInvariantForOp(ifOp);
443 
444   AffineIfOp hoistedIfOp = ::hoistAffineIfOp(ifOp, hoistOverOp);
445   // Nothing to hoist over.
446   if (hoistedIfOp == ifOp)
447     return failure();
448 
449   // Canonicalize to remove dead else blocks (happens whenever an 'if' moves up
450   // a sequence of affine.fors that are all perfectly nested).
451   (void)applyPatternsAndFoldGreedily(
452       hoistedIfOp->getParentWithTrait<OpTrait::IsIsolatedFromAbove>(),
453       frozenPatterns);
454 
455   return success();
456 }
457 
458 // Return the min expr after replacing the given dim.
459 AffineExpr mlir::substWithMin(AffineExpr e, AffineExpr dim, AffineExpr min,
460                               AffineExpr max, bool positivePath) {
461   if (e == dim)
462     return positivePath ? min : max;
463   if (auto bin = e.dyn_cast<AffineBinaryOpExpr>()) {
464     AffineExpr lhs = bin.getLHS();
465     AffineExpr rhs = bin.getRHS();
466     if (bin.getKind() == mlir::AffineExprKind::Add)
467       return substWithMin(lhs, dim, min, max, positivePath) +
468              substWithMin(rhs, dim, min, max, positivePath);
469 
470     auto c1 = bin.getLHS().dyn_cast<AffineConstantExpr>();
471     auto c2 = bin.getRHS().dyn_cast<AffineConstantExpr>();
472     if (c1 && c1.getValue() < 0)
473       return getAffineBinaryOpExpr(
474           bin.getKind(), c1, substWithMin(rhs, dim, min, max, !positivePath));
475     if (c2 && c2.getValue() < 0)
476       return getAffineBinaryOpExpr(
477           bin.getKind(), substWithMin(lhs, dim, min, max, !positivePath), c2);
478     return getAffineBinaryOpExpr(
479         bin.getKind(), substWithMin(lhs, dim, min, max, positivePath),
480         substWithMin(rhs, dim, min, max, positivePath));
481   }
482   return e;
483 }
484 
485 void mlir::normalizeAffineParallel(AffineParallelOp op) {
486   // Loops with min/max in bounds are not normalized at the moment.
487   if (op.hasMinMaxBounds())
488     return;
489 
490   AffineMap lbMap = op.lowerBoundsMap();
491   SmallVector<int64_t, 8> steps = op.getSteps();
492   // No need to do any work if the parallel op is already normalized.
493   bool isAlreadyNormalized =
494       llvm::all_of(llvm::zip(steps, lbMap.getResults()), [](auto tuple) {
495         int64_t step = std::get<0>(tuple);
496         auto lbExpr =
497             std::get<1>(tuple).template dyn_cast<AffineConstantExpr>();
498         return lbExpr && lbExpr.getValue() == 0 && step == 1;
499       });
500   if (isAlreadyNormalized)
501     return;
502 
503   AffineValueMap ranges;
504   AffineValueMap::difference(op.getUpperBoundsValueMap(),
505                              op.getLowerBoundsValueMap(), &ranges);
506   auto builder = OpBuilder::atBlockBegin(op.getBody());
507   auto zeroExpr = builder.getAffineConstantExpr(0);
508   SmallVector<AffineExpr, 8> lbExprs;
509   SmallVector<AffineExpr, 8> ubExprs;
510   for (unsigned i = 0, e = steps.size(); i < e; ++i) {
511     int64_t step = steps[i];
512 
513     // Adjust the lower bound to be 0.
514     lbExprs.push_back(zeroExpr);
515 
516     // Adjust the upper bound expression: 'range / step'.
517     AffineExpr ubExpr = ranges.getResult(i).ceilDiv(step);
518     ubExprs.push_back(ubExpr);
519 
520     // Adjust the corresponding IV: 'lb + i * step'.
521     BlockArgument iv = op.getBody()->getArgument(i);
522     AffineExpr lbExpr = lbMap.getResult(i);
523     unsigned nDims = lbMap.getNumDims();
524     auto expr = lbExpr + builder.getAffineDimExpr(nDims) * step;
525     auto map = AffineMap::get(/*dimCount=*/nDims + 1,
526                               /*symbolCount=*/lbMap.getNumSymbols(), expr);
527 
528     // Use an 'affine.apply' op that will be simplified later in subsequent
529     // canonicalizations.
530     OperandRange lbOperands = op.getLowerBoundsOperands();
531     OperandRange dimOperands = lbOperands.take_front(nDims);
532     OperandRange symbolOperands = lbOperands.drop_front(nDims);
533     SmallVector<Value, 8> applyOperands{dimOperands};
534     applyOperands.push_back(iv);
535     applyOperands.append(symbolOperands.begin(), symbolOperands.end());
536     auto apply = builder.create<AffineApplyOp>(op.getLoc(), map, applyOperands);
537     iv.replaceAllUsesExcept(apply, apply);
538   }
539 
540   SmallVector<int64_t, 8> newSteps(op.getNumDims(), 1);
541   op.setSteps(newSteps);
542   auto newLowerMap = AffineMap::get(
543       /*dimCount=*/0, /*symbolCount=*/0, lbExprs, op.getContext());
544   op.setLowerBounds({}, newLowerMap);
545   auto newUpperMap = AffineMap::get(ranges.getNumDims(), ranges.getNumSymbols(),
546                                     ubExprs, op.getContext());
547   op.setUpperBounds(ranges.getOperands(), newUpperMap);
548 }
549 
550 /// Normalizes affine.for ops. If the affine.for op has only a single iteration
551 /// only then it is simply promoted, else it is normalized in the traditional
552 /// way, by converting the lower bound to zero and loop step to one. The upper
553 /// bound is set to the trip count of the loop. For now, original loops must
554 /// have lower bound with a single result only. There is no such restriction on
555 /// upper bounds.
556 LogicalResult mlir::normalizeAffineFor(AffineForOp op) {
557   if (succeeded(promoteIfSingleIteration(op)))
558     return success();
559 
560   // Check if the forop is already normalized.
561   if (op.hasConstantLowerBound() && (op.getConstantLowerBound() == 0) &&
562       (op.getStep() == 1))
563     return success();
564 
565   // Check if the lower bound has a single result only. Loops with a max lower
566   // bound can't be normalized without additional support like
567   // affine.execute_region's. If the lower bound does not have a single result
568   // then skip this op.
569   if (op.getLowerBoundMap().getNumResults() != 1)
570     return failure();
571 
572   Location loc = op.getLoc();
573   OpBuilder opBuilder(op);
574   int64_t origLoopStep = op.getStep();
575 
576   // Calculate upperBound for normalized loop.
577   SmallVector<Value, 4> ubOperands;
578   AffineBound lb = op.getLowerBound();
579   AffineBound ub = op.getUpperBound();
580   ubOperands.reserve(ub.getNumOperands() + lb.getNumOperands());
581   AffineMap origLbMap = lb.getMap();
582   AffineMap origUbMap = ub.getMap();
583 
584   // Add dimension operands from upper/lower bound.
585   for (unsigned j = 0, e = origUbMap.getNumDims(); j < e; ++j)
586     ubOperands.push_back(ub.getOperand(j));
587   for (unsigned j = 0, e = origLbMap.getNumDims(); j < e; ++j)
588     ubOperands.push_back(lb.getOperand(j));
589 
590   // Add symbol operands from upper/lower bound.
591   for (unsigned j = 0, e = origUbMap.getNumSymbols(); j < e; ++j)
592     ubOperands.push_back(ub.getOperand(origUbMap.getNumDims() + j));
593   for (unsigned j = 0, e = origLbMap.getNumSymbols(); j < e; ++j)
594     ubOperands.push_back(lb.getOperand(origLbMap.getNumDims() + j));
595 
596   // Add original result expressions from lower/upper bound map.
597   SmallVector<AffineExpr, 1> origLbExprs(origLbMap.getResults().begin(),
598                                          origLbMap.getResults().end());
599   SmallVector<AffineExpr, 2> origUbExprs(origUbMap.getResults().begin(),
600                                          origUbMap.getResults().end());
601   SmallVector<AffineExpr, 4> newUbExprs;
602 
603   // The original upperBound can have more than one result. For the new
604   // upperBound of this loop, take difference of all possible combinations of
605   // the ub results and lb result and ceildiv with the loop step. For e.g.,
606   //
607   //  affine.for %i1 = 0 to min affine_map<(d0)[] -> (d0 + 32, 1024)>(%i0)
608   //  will have an upperBound map as,
609   //  affine_map<(d0)[] -> (((d0 + 32) - 0) ceildiv 1, (1024 - 0) ceildiv
610   //  1)>(%i0)
611   //
612   // Insert all combinations of upper/lower bound results.
613   for (unsigned i = 0, e = origUbExprs.size(); i < e; ++i) {
614     newUbExprs.push_back(
615         (origUbExprs[i] - origLbExprs[0]).ceilDiv(origLoopStep));
616   }
617 
618   // Construct newUbMap.
619   AffineMap newUbMap =
620       AffineMap::get(origLbMap.getNumDims() + origUbMap.getNumDims(),
621                      origLbMap.getNumSymbols() + origUbMap.getNumSymbols(),
622                      newUbExprs, opBuilder.getContext());
623   canonicalizeMapAndOperands(&newUbMap, &ubOperands);
624 
625   // Normalize the loop.
626   op.setUpperBound(ubOperands, newUbMap);
627   op.setLowerBound({}, opBuilder.getConstantAffineMap(0));
628   op.setStep(1);
629 
630   // Calculate the Value of new loopIV. Create affine.apply for the value of
631   // the loopIV in normalized loop.
632   opBuilder.setInsertionPointToStart(op.getBody());
633   SmallVector<Value, 4> lbOperands(lb.getOperands().begin(),
634                                    lb.getOperands().begin() +
635                                        lb.getMap().getNumDims());
636   // Add an extra dim operand for loopIV.
637   lbOperands.push_back(op.getInductionVar());
638   // Add symbol operands from lower bound.
639   for (unsigned j = 0, e = origLbMap.getNumSymbols(); j < e; ++j)
640     lbOperands.push_back(lb.getOperand(origLbMap.getNumDims() + j));
641 
642   AffineExpr origIVExpr = opBuilder.getAffineDimExpr(lb.getMap().getNumDims());
643   AffineExpr newIVExpr = origIVExpr * origLoopStep + origLbMap.getResult(0);
644   AffineMap ivMap = AffineMap::get(origLbMap.getNumDims() + 1,
645                                    origLbMap.getNumSymbols(), newIVExpr);
646   canonicalizeMapAndOperands(&ivMap, &lbOperands);
647   Operation *newIV = opBuilder.create<AffineApplyOp>(loc, ivMap, lbOperands);
648   op.getInductionVar().replaceAllUsesExcept(newIV->getResult(0), newIV);
649   return success();
650 }
651 
652 /// Ensure that all operations that could be executed after `start`
653 /// (noninclusive) and prior to `memOp` (e.g. on a control flow/op path
654 /// between the operations) do not have the potential memory effect
655 /// `EffectType` on `memOp`. `memOp`  is an operation that reads or writes to
656 /// a memref. For example, if `EffectType` is MemoryEffects::Write, this method
657 /// will check if there is no write to the memory between `start` and `memOp`
658 /// that would change the read within `memOp`.
659 template <typename EffectType, typename T>
660 static bool hasNoInterveningEffect(Operation *start, T memOp) {
661   Value memref = memOp.getMemRef();
662   bool isOriginalAllocation = memref.getDefiningOp<memref::AllocaOp>() ||
663                               memref.getDefiningOp<memref::AllocOp>();
664 
665   // A boolean representing whether an intervening operation could have impacted
666   // memOp.
667   bool hasSideEffect = false;
668 
669   // Check whether the effect on memOp can be caused by a given operation op.
670   std::function<void(Operation *)> checkOperation = [&](Operation *op) {
671     // If the effect has alreay been found, early exit,
672     if (hasSideEffect)
673       return;
674 
675     if (auto memEffect = dyn_cast<MemoryEffectOpInterface>(op)) {
676       SmallVector<MemoryEffects::EffectInstance, 1> effects;
677       memEffect.getEffects(effects);
678 
679       bool opMayHaveEffect = false;
680       for (auto effect : effects) {
681         // If op causes EffectType on a potentially aliasing location for
682         // memOp, mark as having the effect.
683         if (isa<EffectType>(effect.getEffect())) {
684           if (isOriginalAllocation && effect.getValue() &&
685               (effect.getValue().getDefiningOp<memref::AllocaOp>() ||
686                effect.getValue().getDefiningOp<memref::AllocOp>())) {
687             if (effect.getValue() != memref)
688               continue;
689           }
690           opMayHaveEffect = true;
691           break;
692         }
693       }
694 
695       if (!opMayHaveEffect)
696         return;
697 
698       // If the side effect comes from an affine read or write, try to
699       // prove the side effecting `op` cannot reach `memOp`.
700       if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op)) {
701         MemRefAccess srcAccess(op);
702         MemRefAccess destAccess(memOp);
703         // Dependence analysis is only correct if both ops operate on the same
704         // memref.
705         if (srcAccess.memref == destAccess.memref) {
706           FlatAffineValueConstraints dependenceConstraints;
707 
708           // Number of loops containing the start op and the ending operation.
709           unsigned minSurroundingLoops =
710               getNumCommonSurroundingLoops(*start, *memOp);
711 
712           // Number of loops containing the operation `op` which has the
713           // potential memory side effect and can occur on a path between
714           // `start` and `memOp`.
715           unsigned nsLoops = getNumCommonSurroundingLoops(*op, *memOp);
716 
717           // For ease, let's consider the case that `op` is a store and we're
718           // looking for other potential stores (e.g `op`) that overwrite memory
719           // after `start`, and before being read in `memOp`. In this case, we
720           // only need to consider other potential stores with depth >
721           // minSurrounding loops since `start` would overwrite any store with a
722           // smaller number of surrounding loops before.
723           unsigned d;
724           for (d = nsLoops + 1; d > minSurroundingLoops; d--) {
725             DependenceResult result = checkMemrefAccessDependence(
726                 srcAccess, destAccess, d, &dependenceConstraints,
727                 /*dependenceComponents=*/nullptr);
728             if (hasDependence(result)) {
729               hasSideEffect = true;
730               return;
731             }
732           }
733 
734           // No side effect was seen, simply return.
735           return;
736         }
737       }
738       hasSideEffect = true;
739       return;
740     }
741 
742     if (op->hasTrait<OpTrait::HasRecursiveSideEffects>()) {
743       // Recurse into the regions for this op and check whether the internal
744       // operations may have the side effect `EffectType` on memOp.
745       for (Region &region : op->getRegions())
746         for (Block &block : region)
747           for (Operation &op : block)
748             checkOperation(&op);
749       return;
750     }
751 
752     // Otherwise, conservatively assume generic operations have the effect
753     // on the operation
754     hasSideEffect = true;
755   };
756 
757   // Check all paths from ancestor op `parent` to the operation `to` for the
758   // effect. It is known that `to` must be contained within `parent`.
759   auto until = [&](Operation *parent, Operation *to) {
760     // TODO check only the paths from `parent` to `to`.
761     // Currently we fallback and check the entire parent op, rather than
762     // just the paths from the parent path, stopping after reaching `to`.
763     // This is conservatively correct, but could be made more aggressive.
764     assert(parent->isAncestor(to));
765     checkOperation(parent);
766   };
767 
768   // Check for all paths from operation `from` to operation `untilOp` for the
769   // given memory effect.
770   std::function<void(Operation *, Operation *)> recur =
771       [&](Operation *from, Operation *untilOp) {
772         assert(
773             from->getParentRegion()->isAncestor(untilOp->getParentRegion()) &&
774             "Checking for side effect between two operations without a common "
775             "ancestor");
776 
777         // If the operations are in different regions, recursively consider all
778         // path from `from` to the parent of `to` and all paths from the parent
779         // of `to` to `to`.
780         if (from->getParentRegion() != untilOp->getParentRegion()) {
781           recur(from, untilOp->getParentOp());
782           until(untilOp->getParentOp(), untilOp);
783           return;
784         }
785 
786         // Now, assuming that `from` and `to` exist in the same region, perform
787         // a CFG traversal to check all the relevant operations.
788 
789         // Additional blocks to consider.
790         SmallVector<Block *, 2> todoBlocks;
791         {
792           // First consider the parent block of `from` an check all operations
793           // after `from`.
794           for (auto iter = ++from->getIterator(), end = from->getBlock()->end();
795                iter != end && &*iter != untilOp; ++iter) {
796             checkOperation(&*iter);
797           }
798 
799           // If the parent of `from` doesn't contain `to`, add the successors
800           // to the list of blocks to check.
801           if (untilOp->getBlock() != from->getBlock())
802             for (Block *succ : from->getBlock()->getSuccessors())
803               todoBlocks.push_back(succ);
804         }
805 
806         SmallPtrSet<Block *, 4> done;
807         // Traverse the CFG until hitting `to`.
808         while (!todoBlocks.empty()) {
809           Block *blk = todoBlocks.pop_back_val();
810           if (done.count(blk))
811             continue;
812           done.insert(blk);
813           for (auto &op : *blk) {
814             if (&op == untilOp)
815               break;
816             checkOperation(&op);
817             if (&op == blk->getTerminator())
818               for (Block *succ : blk->getSuccessors())
819                 todoBlocks.push_back(succ);
820           }
821         }
822       };
823   recur(start, memOp);
824   return !hasSideEffect;
825 }
826 
827 /// Attempt to eliminate loadOp by replacing it with a value stored into memory
828 /// which the load is guaranteed to retrieve. This check involves three
829 /// components: 1) The store and load must be on the same location 2) The store
830 /// must dominate (and therefore must always occur prior to) the load 3) No
831 /// other operations will overwrite the memory loaded between the given load
832 /// and store.  If such a value exists, the replaced `loadOp` will be added to
833 /// `loadOpsToErase` and its memref will be added to `memrefsToErase`.
834 static LogicalResult forwardStoreToLoad(
835     AffineReadOpInterface loadOp, SmallVectorImpl<Operation *> &loadOpsToErase,
836     SmallPtrSetImpl<Value> &memrefsToErase, DominanceInfo &domInfo) {
837 
838   // The store op candidate for forwarding that satisfies all conditions
839   // to replace the load, if any.
840   Operation *lastWriteStoreOp = nullptr;
841 
842   for (auto *user : loadOp.getMemRef().getUsers()) {
843     auto storeOp = dyn_cast<AffineWriteOpInterface>(user);
844     if (!storeOp)
845       continue;
846     MemRefAccess srcAccess(storeOp);
847     MemRefAccess destAccess(loadOp);
848 
849     // 1. Check if the store and the load have mathematically equivalent
850     // affine access functions; this implies that they statically refer to the
851     // same single memref element. As an example this filters out cases like:
852     //     store %A[%i0 + 1]
853     //     load %A[%i0]
854     //     store %A[%M]
855     //     load %A[%N]
856     // Use the AffineValueMap difference based memref access equality checking.
857     if (srcAccess != destAccess)
858       continue;
859 
860     // 2. The store has to dominate the load op to be candidate.
861     if (!domInfo.dominates(storeOp, loadOp))
862       continue;
863 
864     // 3. Ensure there is no intermediate operation which could replace the
865     // value in memory.
866     if (!hasNoInterveningEffect<MemoryEffects::Write>(storeOp, loadOp))
867       continue;
868 
869     // We now have a candidate for forwarding.
870     assert(lastWriteStoreOp == nullptr &&
871            "multiple simulataneous replacement stores");
872     lastWriteStoreOp = storeOp;
873   }
874 
875   if (!lastWriteStoreOp)
876     return failure();
877 
878   // Perform the actual store to load forwarding.
879   Value storeVal =
880       cast<AffineWriteOpInterface>(lastWriteStoreOp).getValueToStore();
881   // Check if 2 values have the same shape. This is needed for affine vector
882   // loads and stores.
883   if (storeVal.getType() != loadOp.getValue().getType())
884     return failure();
885   loadOp.getValue().replaceAllUsesWith(storeVal);
886   // Record the memref for a later sweep to optimize away.
887   memrefsToErase.insert(loadOp.getMemRef());
888   // Record this to erase later.
889   loadOpsToErase.push_back(loadOp);
890   return success();
891 }
892 
893 // This attempts to find stores which have no impact on the final result.
894 // A writing op writeA will be eliminated if there exists an op writeB if
895 // 1) writeA and writeB have mathematically equivalent affine access functions.
896 // 2) writeB postdominates writeA.
897 // 3) There is no potential read between writeA and writeB.
898 static void findUnusedStore(AffineWriteOpInterface writeA,
899                             SmallVectorImpl<Operation *> &opsToErase,
900                             PostDominanceInfo &postDominanceInfo) {
901 
902   for (Operation *user : writeA.getMemRef().getUsers()) {
903     // Only consider writing operations.
904     auto writeB = dyn_cast<AffineWriteOpInterface>(user);
905     if (!writeB)
906       continue;
907 
908     // The operations must be distinct.
909     if (writeB == writeA)
910       continue;
911 
912     // Both operations must lie in the same region.
913     if (writeB->getParentRegion() != writeA->getParentRegion())
914       continue;
915 
916     // Both operations must write to the same memory.
917     MemRefAccess srcAccess(writeB);
918     MemRefAccess destAccess(writeA);
919 
920     if (srcAccess != destAccess)
921       continue;
922 
923     // writeB must postdominate writeA.
924     if (!postDominanceInfo.postDominates(writeB, writeA))
925       continue;
926 
927     // There cannot be an operation which reads from memory between
928     // the two writes.
929     if (!hasNoInterveningEffect<MemoryEffects::Read>(writeA, writeB))
930       continue;
931 
932     opsToErase.push_back(writeA);
933     break;
934   }
935 }
936 
937 // The load to load forwarding / redundant load elimination is similar to the
938 // store to load forwarding.
939 // loadA will be be replaced with loadB if:
940 // 1) loadA and loadB have mathematically equivalent affine access functions.
941 // 2) loadB dominates loadA.
942 // 3) There is no write between loadA and loadB.
943 static void loadCSE(AffineReadOpInterface loadA,
944                     SmallVectorImpl<Operation *> &loadOpsToErase,
945                     DominanceInfo &domInfo) {
946   SmallVector<AffineReadOpInterface, 4> loadCandidates;
947   for (auto *user : loadA.getMemRef().getUsers()) {
948     auto loadB = dyn_cast<AffineReadOpInterface>(user);
949     if (!loadB || loadB == loadA)
950       continue;
951 
952     MemRefAccess srcAccess(loadB);
953     MemRefAccess destAccess(loadA);
954 
955     // 1. The accesses have to be to the same location.
956     if (srcAccess != destAccess) {
957       continue;
958     }
959 
960     // 2. The store has to dominate the load op to be candidate.
961     if (!domInfo.dominates(loadB, loadA))
962       continue;
963 
964     // 3. There is no write between loadA and loadB.
965     if (!hasNoInterveningEffect<MemoryEffects::Write>(loadB.getOperation(),
966                                                       loadA))
967       continue;
968 
969     // Check if two values have the same shape. This is needed for affine vector
970     // loads.
971     if (loadB.getValue().getType() != loadA.getValue().getType())
972       continue;
973 
974     loadCandidates.push_back(loadB);
975   }
976 
977   // Of the legal load candidates, use the one that dominates all others
978   // to minimize the subsequent need to loadCSE
979   Value loadB;
980   for (AffineReadOpInterface option : loadCandidates) {
981     if (llvm::all_of(loadCandidates, [&](AffineReadOpInterface depStore) {
982           return depStore == option ||
983                  domInfo.dominates(option.getOperation(),
984                                    depStore.getOperation());
985         })) {
986       loadB = option.getValue();
987       break;
988     }
989   }
990 
991   if (loadB) {
992     loadA.getValue().replaceAllUsesWith(loadB);
993     // Record this to erase later.
994     loadOpsToErase.push_back(loadA);
995   }
996 }
997 
998 // The store to load forwarding and load CSE rely on three conditions:
999 //
1000 // 1) store/load providing a replacement value and load being replaced need to
1001 // have mathematically equivalent affine access functions (checked after full
1002 // composition of load/store operands); this implies that they access the same
1003 // single memref element for all iterations of the common surrounding loop,
1004 //
1005 // 2) the store/load op should dominate the load op,
1006 //
1007 // 3) no operation that may write to memory read by the load being replaced can
1008 // occur after executing the instruction (load or store) providing the
1009 // replacement value and before the load being replaced (thus potentially
1010 // allowing overwriting the memory read by the load).
1011 //
1012 // The above conditions are simple to check, sufficient, and powerful for most
1013 // cases in practice - they are sufficient, but not necessary --- since they
1014 // don't reason about loops that are guaranteed to execute at least once or
1015 // multiple sources to forward from.
1016 //
1017 // TODO: more forwarding can be done when support for
1018 // loop/conditional live-out SSA values is available.
1019 // TODO: do general dead store elimination for memref's. This pass
1020 // currently only eliminates the stores only if no other loads/uses (other
1021 // than dealloc) remain.
1022 //
1023 void mlir::affineScalarReplace(FuncOp f, DominanceInfo &domInfo,
1024                                PostDominanceInfo &postDomInfo) {
1025   // Load op's whose results were replaced by those forwarded from stores.
1026   SmallVector<Operation *, 8> opsToErase;
1027 
1028   // A list of memref's that are potentially dead / could be eliminated.
1029   SmallPtrSet<Value, 4> memrefsToErase;
1030 
1031   // Walk all load's and perform store to load forwarding.
1032   f.walk([&](AffineReadOpInterface loadOp) {
1033     if (failed(
1034             forwardStoreToLoad(loadOp, opsToErase, memrefsToErase, domInfo))) {
1035       loadCSE(loadOp, opsToErase, domInfo);
1036     }
1037   });
1038 
1039   // Erase all load op's whose results were replaced with store fwd'ed ones.
1040   for (auto *op : opsToErase)
1041     op->erase();
1042   opsToErase.clear();
1043 
1044   // Walk all store's and perform unused store elimination
1045   f.walk([&](AffineWriteOpInterface storeOp) {
1046     findUnusedStore(storeOp, opsToErase, postDomInfo);
1047   });
1048   // Erase all store op's which don't impact the program
1049   for (auto *op : opsToErase)
1050     op->erase();
1051 
1052   // Check if the store fwd'ed memrefs are now left with only stores and can
1053   // thus be completely deleted. Note: the canonicalize pass should be able
1054   // to do this as well, but we'll do it here since we collected these anyway.
1055   for (auto memref : memrefsToErase) {
1056     // If the memref hasn't been alloc'ed in this function, skip.
1057     Operation *defOp = memref.getDefiningOp();
1058     if (!defOp || !isa<memref::AllocOp>(defOp))
1059       // TODO: if the memref was returned by a 'call' operation, we
1060       // could still erase it if the call had no side-effects.
1061       continue;
1062     if (llvm::any_of(memref.getUsers(), [&](Operation *ownerOp) {
1063           return !isa<AffineWriteOpInterface, memref::DeallocOp>(ownerOp);
1064         }))
1065       continue;
1066 
1067     // Erase all stores, the dealloc, and the alloc on the memref.
1068     for (auto *user : llvm::make_early_inc_range(memref.getUsers()))
1069       user->erase();
1070     defOp->erase();
1071   }
1072 }
1073 
1074 // Perform the replacement in `op`.
1075 LogicalResult mlir::replaceAllMemRefUsesWith(Value oldMemRef, Value newMemRef,
1076                                              Operation *op,
1077                                              ArrayRef<Value> extraIndices,
1078                                              AffineMap indexRemap,
1079                                              ArrayRef<Value> extraOperands,
1080                                              ArrayRef<Value> symbolOperands,
1081                                              bool allowNonDereferencingOps) {
1082   unsigned newMemRefRank = newMemRef.getType().cast<MemRefType>().getRank();
1083   (void)newMemRefRank; // unused in opt mode
1084   unsigned oldMemRefRank = oldMemRef.getType().cast<MemRefType>().getRank();
1085   (void)oldMemRefRank; // unused in opt mode
1086   if (indexRemap) {
1087     assert(indexRemap.getNumSymbols() == symbolOperands.size() &&
1088            "symbolic operand count mismatch");
1089     assert(indexRemap.getNumInputs() ==
1090            extraOperands.size() + oldMemRefRank + symbolOperands.size());
1091     assert(indexRemap.getNumResults() + extraIndices.size() == newMemRefRank);
1092   } else {
1093     assert(oldMemRefRank + extraIndices.size() == newMemRefRank);
1094   }
1095 
1096   // Assert same elemental type.
1097   assert(oldMemRef.getType().cast<MemRefType>().getElementType() ==
1098          newMemRef.getType().cast<MemRefType>().getElementType());
1099 
1100   SmallVector<unsigned, 2> usePositions;
1101   for (const auto &opEntry : llvm::enumerate(op->getOperands())) {
1102     if (opEntry.value() == oldMemRef)
1103       usePositions.push_back(opEntry.index());
1104   }
1105 
1106   // If memref doesn't appear, nothing to do.
1107   if (usePositions.empty())
1108     return success();
1109 
1110   if (usePositions.size() > 1) {
1111     // TODO: extend it for this case when needed (rare).
1112     assert(false && "multiple dereferencing uses in a single op not supported");
1113     return failure();
1114   }
1115 
1116   unsigned memRefOperandPos = usePositions.front();
1117 
1118   OpBuilder builder(op);
1119   // The following checks if op is dereferencing memref and performs the access
1120   // index rewrites.
1121   auto affMapAccInterface = dyn_cast<AffineMapAccessInterface>(op);
1122   if (!affMapAccInterface) {
1123     if (!allowNonDereferencingOps) {
1124       // Failure: memref used in a non-dereferencing context (potentially
1125       // escapes); no replacement in these cases unless allowNonDereferencingOps
1126       // is set.
1127       return failure();
1128     }
1129     op->setOperand(memRefOperandPos, newMemRef);
1130     return success();
1131   }
1132   // Perform index rewrites for the dereferencing op and then replace the op
1133   NamedAttribute oldMapAttrPair =
1134       affMapAccInterface.getAffineMapAttrForMemRef(oldMemRef);
1135   AffineMap oldMap = oldMapAttrPair.getValue().cast<AffineMapAttr>().getValue();
1136   unsigned oldMapNumInputs = oldMap.getNumInputs();
1137   SmallVector<Value, 4> oldMapOperands(
1138       op->operand_begin() + memRefOperandPos + 1,
1139       op->operand_begin() + memRefOperandPos + 1 + oldMapNumInputs);
1140 
1141   // Apply 'oldMemRefOperands = oldMap(oldMapOperands)'.
1142   SmallVector<Value, 4> oldMemRefOperands;
1143   SmallVector<Value, 4> affineApplyOps;
1144   oldMemRefOperands.reserve(oldMemRefRank);
1145   if (oldMap != builder.getMultiDimIdentityMap(oldMap.getNumDims())) {
1146     for (auto resultExpr : oldMap.getResults()) {
1147       auto singleResMap = AffineMap::get(oldMap.getNumDims(),
1148                                          oldMap.getNumSymbols(), resultExpr);
1149       auto afOp = builder.create<AffineApplyOp>(op->getLoc(), singleResMap,
1150                                                 oldMapOperands);
1151       oldMemRefOperands.push_back(afOp);
1152       affineApplyOps.push_back(afOp);
1153     }
1154   } else {
1155     oldMemRefOperands.assign(oldMapOperands.begin(), oldMapOperands.end());
1156   }
1157 
1158   // Construct new indices as a remap of the old ones if a remapping has been
1159   // provided. The indices of a memref come right after it, i.e.,
1160   // at position memRefOperandPos + 1.
1161   SmallVector<Value, 4> remapOperands;
1162   remapOperands.reserve(extraOperands.size() + oldMemRefRank +
1163                         symbolOperands.size());
1164   remapOperands.append(extraOperands.begin(), extraOperands.end());
1165   remapOperands.append(oldMemRefOperands.begin(), oldMemRefOperands.end());
1166   remapOperands.append(symbolOperands.begin(), symbolOperands.end());
1167 
1168   SmallVector<Value, 4> remapOutputs;
1169   remapOutputs.reserve(oldMemRefRank);
1170 
1171   if (indexRemap &&
1172       indexRemap != builder.getMultiDimIdentityMap(indexRemap.getNumDims())) {
1173     // Remapped indices.
1174     for (auto resultExpr : indexRemap.getResults()) {
1175       auto singleResMap = AffineMap::get(
1176           indexRemap.getNumDims(), indexRemap.getNumSymbols(), resultExpr);
1177       auto afOp = builder.create<AffineApplyOp>(op->getLoc(), singleResMap,
1178                                                 remapOperands);
1179       remapOutputs.push_back(afOp);
1180       affineApplyOps.push_back(afOp);
1181     }
1182   } else {
1183     // No remapping specified.
1184     remapOutputs.assign(remapOperands.begin(), remapOperands.end());
1185   }
1186 
1187   SmallVector<Value, 4> newMapOperands;
1188   newMapOperands.reserve(newMemRefRank);
1189 
1190   // Prepend 'extraIndices' in 'newMapOperands'.
1191   for (Value extraIndex : extraIndices) {
1192     assert(extraIndex.getDefiningOp()->getNumResults() == 1 &&
1193            "single result op's expected to generate these indices");
1194     assert((isValidDim(extraIndex) || isValidSymbol(extraIndex)) &&
1195            "invalid memory op index");
1196     newMapOperands.push_back(extraIndex);
1197   }
1198 
1199   // Append 'remapOutputs' to 'newMapOperands'.
1200   newMapOperands.append(remapOutputs.begin(), remapOutputs.end());
1201 
1202   // Create new fully composed AffineMap for new op to be created.
1203   assert(newMapOperands.size() == newMemRefRank);
1204   auto newMap = builder.getMultiDimIdentityMap(newMemRefRank);
1205   // TODO: Avoid creating/deleting temporary AffineApplyOps here.
1206   fullyComposeAffineMapAndOperands(&newMap, &newMapOperands);
1207   newMap = simplifyAffineMap(newMap);
1208   canonicalizeMapAndOperands(&newMap, &newMapOperands);
1209   // Remove any affine.apply's that became dead as a result of composition.
1210   for (Value value : affineApplyOps)
1211     if (value.use_empty())
1212       value.getDefiningOp()->erase();
1213 
1214   OperationState state(op->getLoc(), op->getName());
1215   // Construct the new operation using this memref.
1216   state.operands.reserve(op->getNumOperands() + extraIndices.size());
1217   // Insert the non-memref operands.
1218   state.operands.append(op->operand_begin(),
1219                         op->operand_begin() + memRefOperandPos);
1220   // Insert the new memref value.
1221   state.operands.push_back(newMemRef);
1222 
1223   // Insert the new memref map operands.
1224   state.operands.append(newMapOperands.begin(), newMapOperands.end());
1225 
1226   // Insert the remaining operands unmodified.
1227   state.operands.append(op->operand_begin() + memRefOperandPos + 1 +
1228                             oldMapNumInputs,
1229                         op->operand_end());
1230 
1231   // Result types don't change. Both memref's are of the same elemental type.
1232   state.types.reserve(op->getNumResults());
1233   for (auto result : op->getResults())
1234     state.types.push_back(result.getType());
1235 
1236   // Add attribute for 'newMap', other Attributes do not change.
1237   auto newMapAttr = AffineMapAttr::get(newMap);
1238   for (auto namedAttr : op->getAttrs()) {
1239     if (namedAttr.getName() == oldMapAttrPair.getName())
1240       state.attributes.push_back({namedAttr.getName(), newMapAttr});
1241     else
1242       state.attributes.push_back(namedAttr);
1243   }
1244 
1245   // Create the new operation.
1246   auto *repOp = builder.create(state);
1247   op->replaceAllUsesWith(repOp);
1248   op->erase();
1249 
1250   return success();
1251 }
1252 
1253 LogicalResult mlir::replaceAllMemRefUsesWith(
1254     Value oldMemRef, Value newMemRef, ArrayRef<Value> extraIndices,
1255     AffineMap indexRemap, ArrayRef<Value> extraOperands,
1256     ArrayRef<Value> symbolOperands, Operation *domOpFilter,
1257     Operation *postDomOpFilter, bool allowNonDereferencingOps,
1258     bool replaceInDeallocOp) {
1259   unsigned newMemRefRank = newMemRef.getType().cast<MemRefType>().getRank();
1260   (void)newMemRefRank; // unused in opt mode
1261   unsigned oldMemRefRank = oldMemRef.getType().cast<MemRefType>().getRank();
1262   (void)oldMemRefRank;
1263   if (indexRemap) {
1264     assert(indexRemap.getNumSymbols() == symbolOperands.size() &&
1265            "symbol operand count mismatch");
1266     assert(indexRemap.getNumInputs() ==
1267            extraOperands.size() + oldMemRefRank + symbolOperands.size());
1268     assert(indexRemap.getNumResults() + extraIndices.size() == newMemRefRank);
1269   } else {
1270     assert(oldMemRefRank + extraIndices.size() == newMemRefRank);
1271   }
1272 
1273   // Assert same elemental type.
1274   assert(oldMemRef.getType().cast<MemRefType>().getElementType() ==
1275          newMemRef.getType().cast<MemRefType>().getElementType());
1276 
1277   std::unique_ptr<DominanceInfo> domInfo;
1278   std::unique_ptr<PostDominanceInfo> postDomInfo;
1279   if (domOpFilter)
1280     domInfo =
1281         std::make_unique<DominanceInfo>(domOpFilter->getParentOfType<FuncOp>());
1282 
1283   if (postDomOpFilter)
1284     postDomInfo = std::make_unique<PostDominanceInfo>(
1285         postDomOpFilter->getParentOfType<FuncOp>());
1286 
1287   // Walk all uses of old memref; collect ops to perform replacement. We use a
1288   // DenseSet since an operation could potentially have multiple uses of a
1289   // memref (although rare), and the replacement later is going to erase ops.
1290   DenseSet<Operation *> opsToReplace;
1291   for (auto *op : oldMemRef.getUsers()) {
1292     // Skip this use if it's not dominated by domOpFilter.
1293     if (domOpFilter && !domInfo->dominates(domOpFilter, op))
1294       continue;
1295 
1296     // Skip this use if it's not post-dominated by postDomOpFilter.
1297     if (postDomOpFilter && !postDomInfo->postDominates(postDomOpFilter, op))
1298       continue;
1299 
1300     // Skip dealloc's - no replacement is necessary, and a memref replacement
1301     // at other uses doesn't hurt these dealloc's.
1302     if (isa<memref::DeallocOp>(op) && !replaceInDeallocOp)
1303       continue;
1304 
1305     // Check if the memref was used in a non-dereferencing context. It is fine
1306     // for the memref to be used in a non-dereferencing way outside of the
1307     // region where this replacement is happening.
1308     if (!isa<AffineMapAccessInterface>(*op)) {
1309       if (!allowNonDereferencingOps) {
1310         LLVM_DEBUG(llvm::dbgs()
1311                    << "Memref replacement failed: non-deferencing memref op: \n"
1312                    << *op << '\n');
1313         return failure();
1314       }
1315       // Non-dereferencing ops with the MemRefsNormalizable trait are
1316       // supported for replacement.
1317       if (!op->hasTrait<OpTrait::MemRefsNormalizable>()) {
1318         LLVM_DEBUG(llvm::dbgs() << "Memref replacement failed: use without a "
1319                                    "memrefs normalizable trait: \n"
1320                                 << *op << '\n');
1321         return failure();
1322       }
1323     }
1324 
1325     // We'll first collect and then replace --- since replacement erases the op
1326     // that has the use, and that op could be postDomFilter or domFilter itself!
1327     opsToReplace.insert(op);
1328   }
1329 
1330   for (auto *op : opsToReplace) {
1331     if (failed(replaceAllMemRefUsesWith(
1332             oldMemRef, newMemRef, op, extraIndices, indexRemap, extraOperands,
1333             symbolOperands, allowNonDereferencingOps)))
1334       llvm_unreachable("memref replacement guaranteed to succeed here");
1335   }
1336 
1337   return success();
1338 }
1339 
1340 /// Given an operation, inserts one or more single result affine
1341 /// apply operations, results of which are exclusively used by this operation
1342 /// operation. The operands of these newly created affine apply ops are
1343 /// guaranteed to be loop iterators or terminal symbols of a function.
1344 ///
1345 /// Before
1346 ///
1347 /// affine.for %i = 0 to #map(%N)
1348 ///   %idx = affine.apply (d0) -> (d0 mod 2) (%i)
1349 ///   "send"(%idx, %A, ...)
1350 ///   "compute"(%idx)
1351 ///
1352 /// After
1353 ///
1354 /// affine.for %i = 0 to #map(%N)
1355 ///   %idx = affine.apply (d0) -> (d0 mod 2) (%i)
1356 ///   "send"(%idx, %A, ...)
1357 ///   %idx_ = affine.apply (d0) -> (d0 mod 2) (%i)
1358 ///   "compute"(%idx_)
1359 ///
1360 /// This allows applying different transformations on send and compute (for eg.
1361 /// different shifts/delays).
1362 ///
1363 /// Returns nullptr either if none of opInst's operands were the result of an
1364 /// affine.apply and thus there was no affine computation slice to create, or if
1365 /// all the affine.apply op's supplying operands to this opInst did not have any
1366 /// uses besides this opInst; otherwise returns the list of affine.apply
1367 /// operations created in output argument `sliceOps`.
1368 void mlir::createAffineComputationSlice(
1369     Operation *opInst, SmallVectorImpl<AffineApplyOp> *sliceOps) {
1370   // Collect all operands that are results of affine apply ops.
1371   SmallVector<Value, 4> subOperands;
1372   subOperands.reserve(opInst->getNumOperands());
1373   for (auto operand : opInst->getOperands())
1374     if (isa_and_nonnull<AffineApplyOp>(operand.getDefiningOp()))
1375       subOperands.push_back(operand);
1376 
1377   // Gather sequence of AffineApplyOps reachable from 'subOperands'.
1378   SmallVector<Operation *, 4> affineApplyOps;
1379   getReachableAffineApplyOps(subOperands, affineApplyOps);
1380   // Skip transforming if there are no affine maps to compose.
1381   if (affineApplyOps.empty())
1382     return;
1383 
1384   // Check if all uses of the affine apply op's lie only in this op op, in
1385   // which case there would be nothing to do.
1386   bool localized = true;
1387   for (auto *op : affineApplyOps) {
1388     for (auto result : op->getResults()) {
1389       for (auto *user : result.getUsers()) {
1390         if (user != opInst) {
1391           localized = false;
1392           break;
1393         }
1394       }
1395     }
1396   }
1397   if (localized)
1398     return;
1399 
1400   OpBuilder builder(opInst);
1401   SmallVector<Value, 4> composedOpOperands(subOperands);
1402   auto composedMap = builder.getMultiDimIdentityMap(composedOpOperands.size());
1403   fullyComposeAffineMapAndOperands(&composedMap, &composedOpOperands);
1404 
1405   // Create an affine.apply for each of the map results.
1406   sliceOps->reserve(composedMap.getNumResults());
1407   for (auto resultExpr : composedMap.getResults()) {
1408     auto singleResMap = AffineMap::get(composedMap.getNumDims(),
1409                                        composedMap.getNumSymbols(), resultExpr);
1410     sliceOps->push_back(builder.create<AffineApplyOp>(
1411         opInst->getLoc(), singleResMap, composedOpOperands));
1412   }
1413 
1414   // Construct the new operands that include the results from the composed
1415   // affine apply op above instead of existing ones (subOperands). So, they
1416   // differ from opInst's operands only for those operands in 'subOperands', for
1417   // which they will be replaced by the corresponding one from 'sliceOps'.
1418   SmallVector<Value, 4> newOperands(opInst->getOperands());
1419   for (unsigned i = 0, e = newOperands.size(); i < e; i++) {
1420     // Replace the subOperands from among the new operands.
1421     unsigned j, f;
1422     for (j = 0, f = subOperands.size(); j < f; j++) {
1423       if (newOperands[i] == subOperands[j])
1424         break;
1425     }
1426     if (j < subOperands.size()) {
1427       newOperands[i] = (*sliceOps)[j];
1428     }
1429   }
1430   for (unsigned idx = 0, e = newOperands.size(); idx < e; idx++) {
1431     opInst->setOperand(idx, newOperands[idx]);
1432   }
1433 }
1434 
1435 /// Enum to set patterns of affine expr in tiled-layout map.
1436 /// TileFloorDiv: <dim expr> div <tile size>
1437 /// TileMod: <dim expr> mod <tile size>
1438 /// TileNone: None of the above
1439 /// Example:
1440 /// #tiled_2d_128x256 = affine_map<(d0, d1)
1441 ///            -> (d0 div 128, d1 div 256, d0 mod 128, d1 mod 256)>
1442 /// "d0 div 128" and "d1 div 256" ==> TileFloorDiv
1443 /// "d0 mod 128" and "d1 mod 256" ==> TileMod
1444 enum TileExprPattern { TileFloorDiv, TileMod, TileNone };
1445 
1446 /// Check if `map` is a tiled layout. In the tiled layout, specific k dimensions
1447 /// being floordiv'ed by respective tile sizes appeare in a mod with the same
1448 /// tile sizes, and no other expression involves those k dimensions. This
1449 /// function stores a vector of tuples (`tileSizePos`) including AffineExpr for
1450 /// tile size, positions of corresponding `floordiv` and `mod`. If it is not a
1451 /// tiled layout, an empty vector is returned.
1452 static LogicalResult getTileSizePos(
1453     AffineMap map,
1454     SmallVectorImpl<std::tuple<AffineExpr, unsigned, unsigned>> &tileSizePos) {
1455   // Create `floordivExprs` which is a vector of tuples including LHS and RHS of
1456   // `floordiv` and its position in `map` output.
1457   // Example: #tiled_2d_128x256 = affine_map<(d0, d1)
1458   //                -> (d0 div 128, d1 div 256, d0 mod 128, d1 mod 256)>
1459   // In this example, `floordivExprs` includes {d0, 128, 0} and {d1, 256, 1}.
1460   SmallVector<std::tuple<AffineExpr, AffineExpr, unsigned>, 4> floordivExprs;
1461   unsigned pos = 0;
1462   for (AffineExpr expr : map.getResults()) {
1463     if (expr.getKind() == AffineExprKind::FloorDiv) {
1464       AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
1465       if (binaryExpr.getRHS().isa<AffineConstantExpr>())
1466         floordivExprs.emplace_back(
1467             std::make_tuple(binaryExpr.getLHS(), binaryExpr.getRHS(), pos));
1468     }
1469     pos++;
1470   }
1471   // Not tiled layout if `floordivExprs` is empty.
1472   if (floordivExprs.empty()) {
1473     tileSizePos = SmallVector<std::tuple<AffineExpr, unsigned, unsigned>>{};
1474     return success();
1475   }
1476 
1477   // Check if LHS of `floordiv` is used in LHS of `mod`. If not used, `map` is
1478   // not tiled layout.
1479   for (std::tuple<AffineExpr, AffineExpr, unsigned> fexpr : floordivExprs) {
1480     AffineExpr floordivExprLHS = std::get<0>(fexpr);
1481     AffineExpr floordivExprRHS = std::get<1>(fexpr);
1482     unsigned floordivPos = std::get<2>(fexpr);
1483 
1484     // Walk affinexpr of `map` output except `fexpr`, and check if LHS and RHS
1485     // of `fexpr` are used in LHS and RHS of `mod`. If LHS of `fexpr` is used
1486     // other expr, the map is not tiled layout. Example of non tiled layout:
1487     //   affine_map<(d0, d1, d2) -> (d0, d1, d2 floordiv 256, d2 floordiv 256)>
1488     //   affine_map<(d0, d1, d2) -> (d0, d1, d2 floordiv 256, d2 mod 128)>
1489     //   affine_map<(d0, d1, d2) -> (d0, d1, d2 floordiv 256, d2 mod 256, d2 mod
1490     //   256)>
1491     bool found = false;
1492     pos = 0;
1493     for (AffineExpr expr : map.getResults()) {
1494       bool notTiled = false;
1495       if (pos != floordivPos) {
1496         expr.walk([&](AffineExpr e) {
1497           if (e == floordivExprLHS) {
1498             if (expr.getKind() == AffineExprKind::Mod) {
1499               AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>();
1500               // If LHS and RHS of `mod` are the same with those of floordiv.
1501               if (floordivExprLHS == binaryExpr.getLHS() &&
1502                   floordivExprRHS == binaryExpr.getRHS()) {
1503                 // Save tile size (RHS of `mod`), and position of `floordiv` and
1504                 // `mod` if same expr with `mod` is not found yet.
1505                 if (!found) {
1506                   tileSizePos.emplace_back(
1507                       std::make_tuple(binaryExpr.getRHS(), floordivPos, pos));
1508                   found = true;
1509                 } else {
1510                   // Non tiled layout: Have multilpe `mod` with the same LHS.
1511                   // eg. affine_map<(d0, d1, d2) -> (d0, d1, d2 floordiv 256, d2
1512                   // mod 256, d2 mod 256)>
1513                   notTiled = true;
1514                 }
1515               } else {
1516                 // Non tiled layout: RHS of `mod` is different from `floordiv`.
1517                 // eg. affine_map<(d0, d1, d2) -> (d0, d1, d2 floordiv 256, d2
1518                 // mod 128)>
1519                 notTiled = true;
1520               }
1521             } else {
1522               // Non tiled layout: LHS is the same, but not `mod`.
1523               // eg. affine_map<(d0, d1, d2) -> (d0, d1, d2 floordiv 256, d2
1524               // floordiv 256)>
1525               notTiled = true;
1526             }
1527           }
1528         });
1529       }
1530       if (notTiled) {
1531         tileSizePos = SmallVector<std::tuple<AffineExpr, unsigned, unsigned>>{};
1532         return success();
1533       }
1534       pos++;
1535     }
1536   }
1537   return success();
1538 }
1539 
1540 /// Check if `dim` dimension of memrefType with `layoutMap` becomes dynamic
1541 /// after normalization. Dimensions that include dynamic dimensions in the map
1542 /// output will become dynamic dimensions. Return true if `dim` is dynamic
1543 /// dimension.
1544 ///
1545 /// Example:
1546 /// #map0 = affine_map<(d0, d1) -> (d0, d1 floordiv 32, d1 mod 32)>
1547 ///
1548 /// If d1 is dynamic dimension, 2nd and 3rd dimension of map output are dynamic.
1549 /// memref<4x?xf32, #map0>  ==>  memref<4x?x?xf32>
1550 static bool
1551 isNormalizedMemRefDynamicDim(unsigned dim, AffineMap layoutMap,
1552                              SmallVectorImpl<unsigned> &inMemrefTypeDynDims,
1553                              MLIRContext *context) {
1554   bool isDynamicDim = false;
1555   AffineExpr expr = layoutMap.getResults()[dim];
1556   // Check if affine expr of the dimension includes dynamic dimension of input
1557   // memrefType.
1558   expr.walk([&inMemrefTypeDynDims, &isDynamicDim, &context](AffineExpr e) {
1559     if (e.isa<AffineDimExpr>()) {
1560       for (unsigned dm : inMemrefTypeDynDims) {
1561         if (e == getAffineDimExpr(dm, context)) {
1562           isDynamicDim = true;
1563         }
1564       }
1565     }
1566   });
1567   return isDynamicDim;
1568 }
1569 
1570 /// Create affine expr to calculate dimension size for a tiled-layout map.
1571 static AffineExpr createDimSizeExprForTiledLayout(AffineExpr oldMapOutput,
1572                                                   TileExprPattern pat) {
1573   // Create map output for the patterns.
1574   // "floordiv <tile size>" ==> "ceildiv <tile size>"
1575   // "mod <tile size>" ==> "<tile size>"
1576   AffineExpr newMapOutput;
1577   AffineBinaryOpExpr binaryExpr = nullptr;
1578   switch (pat) {
1579   case TileExprPattern::TileMod:
1580     binaryExpr = oldMapOutput.cast<AffineBinaryOpExpr>();
1581     newMapOutput = binaryExpr.getRHS();
1582     break;
1583   case TileExprPattern::TileFloorDiv:
1584     binaryExpr = oldMapOutput.cast<AffineBinaryOpExpr>();
1585     newMapOutput = getAffineBinaryOpExpr(
1586         AffineExprKind::CeilDiv, binaryExpr.getLHS(), binaryExpr.getRHS());
1587     break;
1588   default:
1589     newMapOutput = oldMapOutput;
1590   }
1591   return newMapOutput;
1592 }
1593 
1594 /// Create new maps to calculate each dimension size of `newMemRefType`, and
1595 /// create `newDynamicSizes` from them by using AffineApplyOp.
1596 ///
1597 /// Steps for normalizing dynamic memrefs for a tiled layout map
1598 /// Example:
1599 ///    #map0 = affine_map<(d0, d1) -> (d0, d1 floordiv 32, d1 mod 32)>
1600 ///    %0 = dim %arg0, %c1 :memref<4x?xf32>
1601 ///    %1 = alloc(%0) : memref<4x?xf32, #map0>
1602 ///
1603 /// (Before this function)
1604 /// 1. Check if `map`(#map0) is a tiled layout using `getTileSizePos()`. Only
1605 /// single layout map is supported.
1606 ///
1607 /// 2. Create normalized memrefType using `isNormalizedMemRefDynamicDim()`. It
1608 /// is memref<4x?x?xf32> in the above example.
1609 ///
1610 /// (In this function)
1611 /// 3. Create new maps to calculate each dimension of the normalized memrefType
1612 /// using `createDimSizeExprForTiledLayout()`. In the tiled layout, the
1613 /// dimension size can be calculated by replacing "floordiv <tile size>" with
1614 /// "ceildiv <tile size>" and "mod <tile size>" with "<tile size>".
1615 /// - New map in the above example
1616 ///   #map0 = affine_map<(d0, d1) -> (d0)>
1617 ///   #map1 = affine_map<(d0, d1) -> (d1 ceildiv 32)>
1618 ///   #map2 = affine_map<(d0, d1) -> (32)>
1619 ///
1620 /// 4. Create AffineApplyOp to apply the new maps. The output of AffineApplyOp
1621 /// is used in dynamicSizes of new AllocOp.
1622 ///   %0 = dim %arg0, %c1 : memref<4x?xf32>
1623 ///   %c4 = arith.constant 4 : index
1624 ///   %1 = affine.apply #map1(%c4, %0)
1625 ///   %2 = affine.apply #map2(%c4, %0)
1626 static void createNewDynamicSizes(MemRefType oldMemRefType,
1627                                   MemRefType newMemRefType, AffineMap map,
1628                                   memref::AllocOp *allocOp, OpBuilder b,
1629                                   SmallVectorImpl<Value> &newDynamicSizes) {
1630   // Create new input for AffineApplyOp.
1631   SmallVector<Value, 4> inAffineApply;
1632   ArrayRef<int64_t> oldMemRefShape = oldMemRefType.getShape();
1633   unsigned dynIdx = 0;
1634   for (unsigned d = 0; d < oldMemRefType.getRank(); ++d) {
1635     if (oldMemRefShape[d] < 0) {
1636       // Use dynamicSizes of allocOp for dynamic dimension.
1637       inAffineApply.emplace_back(allocOp->dynamicSizes()[dynIdx]);
1638       dynIdx++;
1639     } else {
1640       // Create ConstantOp for static dimension.
1641       Attribute constantAttr =
1642           b.getIntegerAttr(b.getIndexType(), oldMemRefShape[d]);
1643       inAffineApply.emplace_back(
1644           b.create<arith::ConstantOp>(allocOp->getLoc(), constantAttr));
1645     }
1646   }
1647 
1648   // Create new map to calculate each dimension size of new memref for each
1649   // original map output. Only for dynamic dimesion of `newMemRefType`.
1650   unsigned newDimIdx = 0;
1651   ArrayRef<int64_t> newMemRefShape = newMemRefType.getShape();
1652   SmallVector<std::tuple<AffineExpr, unsigned, unsigned>> tileSizePos;
1653   (void)getTileSizePos(map, tileSizePos);
1654   for (AffineExpr expr : map.getResults()) {
1655     if (newMemRefShape[newDimIdx] < 0) {
1656       // Create new maps to calculate each dimension size of new memref.
1657       enum TileExprPattern pat = TileExprPattern::TileNone;
1658       for (auto pos : tileSizePos) {
1659         if (newDimIdx == std::get<1>(pos))
1660           pat = TileExprPattern::TileFloorDiv;
1661         else if (newDimIdx == std::get<2>(pos))
1662           pat = TileExprPattern::TileMod;
1663       }
1664       AffineExpr newMapOutput = createDimSizeExprForTiledLayout(expr, pat);
1665       AffineMap newMap =
1666           AffineMap::get(map.getNumInputs(), map.getNumSymbols(), newMapOutput);
1667       Value affineApp =
1668           b.create<AffineApplyOp>(allocOp->getLoc(), newMap, inAffineApply);
1669       newDynamicSizes.emplace_back(affineApp);
1670     }
1671     newDimIdx++;
1672   }
1673 }
1674 
1675 // TODO: Currently works for static memrefs with a single layout map.
1676 LogicalResult mlir::normalizeMemRef(memref::AllocOp *allocOp) {
1677   MemRefType memrefType = allocOp->getType();
1678   OpBuilder b(*allocOp);
1679 
1680   // Fetch a new memref type after normalizing the old memref to have an
1681   // identity map layout.
1682   MemRefType newMemRefType =
1683       normalizeMemRefType(memrefType, b, allocOp->symbolOperands().size());
1684   if (newMemRefType == memrefType)
1685     // Either memrefType already had an identity map or the map couldn't be
1686     // transformed to an identity map.
1687     return failure();
1688 
1689   Value oldMemRef = allocOp->getResult();
1690 
1691   SmallVector<Value, 4> symbolOperands(allocOp->symbolOperands());
1692   AffineMap layoutMap = memrefType.getLayout().getAffineMap();
1693   memref::AllocOp newAlloc;
1694   // Check if `layoutMap` is a tiled layout. Only single layout map is
1695   // supported for normalizing dynamic memrefs.
1696   SmallVector<std::tuple<AffineExpr, unsigned, unsigned>> tileSizePos;
1697   (void)getTileSizePos(layoutMap, tileSizePos);
1698   if (newMemRefType.getNumDynamicDims() > 0 && !tileSizePos.empty()) {
1699     MemRefType oldMemRefType = oldMemRef.getType().cast<MemRefType>();
1700     SmallVector<Value, 4> newDynamicSizes;
1701     createNewDynamicSizes(oldMemRefType, newMemRefType, layoutMap, allocOp, b,
1702                           newDynamicSizes);
1703     // Add the new dynamic sizes in new AllocOp.
1704     newAlloc =
1705         b.create<memref::AllocOp>(allocOp->getLoc(), newMemRefType,
1706                                   newDynamicSizes, allocOp->alignmentAttr());
1707   } else {
1708     newAlloc = b.create<memref::AllocOp>(allocOp->getLoc(), newMemRefType,
1709                                          allocOp->alignmentAttr());
1710   }
1711   // Replace all uses of the old memref.
1712   if (failed(replaceAllMemRefUsesWith(oldMemRef, /*newMemRef=*/newAlloc,
1713                                       /*extraIndices=*/{},
1714                                       /*indexRemap=*/layoutMap,
1715                                       /*extraOperands=*/{},
1716                                       /*symbolOperands=*/symbolOperands,
1717                                       /*domOpFilter=*/nullptr,
1718                                       /*postDomOpFilter=*/nullptr,
1719                                       /*allowNonDereferencingOps=*/true))) {
1720     // If it failed (due to escapes for example), bail out.
1721     newAlloc.erase();
1722     return failure();
1723   }
1724   // Replace any uses of the original alloc op and erase it. All remaining uses
1725   // have to be dealloc's; RAMUW above would've failed otherwise.
1726   assert(llvm::all_of(oldMemRef.getUsers(), [](Operation *op) {
1727     return isa<memref::DeallocOp>(op);
1728   }));
1729   oldMemRef.replaceAllUsesWith(newAlloc);
1730   allocOp->erase();
1731   return success();
1732 }
1733 
1734 MemRefType mlir::normalizeMemRefType(MemRefType memrefType, OpBuilder b,
1735                                      unsigned numSymbolicOperands) {
1736   unsigned rank = memrefType.getRank();
1737   if (rank == 0)
1738     return memrefType;
1739 
1740   if (memrefType.getLayout().isIdentity()) {
1741     // Either no maps is associated with this memref or this memref has
1742     // a trivial (identity) map.
1743     return memrefType;
1744   }
1745   AffineMap layoutMap = memrefType.getLayout().getAffineMap();
1746 
1747   // We don't do any checks for one-to-one'ness; we assume that it is
1748   // one-to-one.
1749 
1750   // Normalize only static memrefs and dynamic memrefs with a tiled-layout map
1751   // for now.
1752   // TODO: Normalize the other types of dynamic memrefs.
1753   SmallVector<std::tuple<AffineExpr, unsigned, unsigned>> tileSizePos;
1754   (void)getTileSizePos(layoutMap, tileSizePos);
1755   if (memrefType.getNumDynamicDims() > 0 && tileSizePos.empty())
1756     return memrefType;
1757 
1758   // We have a single map that is not an identity map. Create a new memref
1759   // with the right shape and an identity layout map.
1760   ArrayRef<int64_t> shape = memrefType.getShape();
1761   // FlatAffineValueConstraint may later on use symbolicOperands.
1762   FlatAffineValueConstraints fac(rank, numSymbolicOperands);
1763   SmallVector<unsigned, 4> memrefTypeDynDims;
1764   for (unsigned d = 0; d < rank; ++d) {
1765     // Use constraint system only in static dimensions.
1766     if (shape[d] > 0) {
1767       fac.addBound(IntegerPolyhedron::LB, d, 0);
1768       fac.addBound(IntegerPolyhedron::UB, d, shape[d] - 1);
1769     } else {
1770       memrefTypeDynDims.emplace_back(d);
1771     }
1772   }
1773   // We compose this map with the original index (logical) space to derive
1774   // the upper bounds for the new index space.
1775   unsigned newRank = layoutMap.getNumResults();
1776   if (failed(fac.composeMatchingMap(layoutMap)))
1777     return memrefType;
1778   // TODO: Handle semi-affine maps.
1779   // Project out the old data dimensions.
1780   fac.projectOut(newRank, fac.getNumIds() - newRank - fac.getNumLocalIds());
1781   SmallVector<int64_t, 4> newShape(newRank);
1782   for (unsigned d = 0; d < newRank; ++d) {
1783     // Check if each dimension of normalized memrefType is dynamic.
1784     bool isDynDim = isNormalizedMemRefDynamicDim(
1785         d, layoutMap, memrefTypeDynDims, b.getContext());
1786     if (isDynDim) {
1787       newShape[d] = -1;
1788     } else {
1789       // The lower bound for the shape is always zero.
1790       auto ubConst = fac.getConstantBound(IntegerPolyhedron::UB, d);
1791       // For a static memref and an affine map with no symbols, this is
1792       // always bounded.
1793       assert(ubConst.hasValue() && "should always have an upper bound");
1794       if (ubConst.getValue() < 0)
1795         // This is due to an invalid map that maps to a negative space.
1796         return memrefType;
1797       // If dimension of new memrefType is dynamic, the value is -1.
1798       newShape[d] = ubConst.getValue() + 1;
1799     }
1800   }
1801 
1802   // Create the new memref type after trivializing the old layout map.
1803   MemRefType newMemRefType =
1804       MemRefType::Builder(memrefType)
1805           .setShape(newShape)
1806           .setLayout(AffineMapAttr::get(b.getMultiDimIdentityMap(newRank)));
1807 
1808   return newMemRefType;
1809 }
1810