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