1 //===- AffineToStandard.cpp - Lower affine constructs to primitives -------===//
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 lowers affine constructs (If and For statements, AffineApply
10 // operations) within a function into their standard If and For equivalent ops.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Conversion/AffineToStandard/AffineToStandard.h"
15 
16 #include "../PassDetail.h"
17 #include "mlir/Dialect/Affine/IR/AffineOps.h"
18 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
19 #include "mlir/Dialect/MemRef/IR/MemRef.h"
20 #include "mlir/Dialect/SCF/SCF.h"
21 #include "mlir/Dialect/StandardOps/IR/Ops.h"
22 #include "mlir/Dialect/Vector/VectorOps.h"
23 #include "mlir/IR/AffineExprVisitor.h"
24 #include "mlir/IR/BlockAndValueMapping.h"
25 #include "mlir/IR/Builders.h"
26 #include "mlir/IR/IntegerSet.h"
27 #include "mlir/IR/MLIRContext.h"
28 #include "mlir/Pass/Pass.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "mlir/Transforms/Passes.h"
31 
32 using namespace mlir;
33 using namespace mlir::vector;
34 
35 namespace {
36 /// Visit affine expressions recursively and build the sequence of operations
37 /// that correspond to it.  Visitation functions return an Value of the
38 /// expression subtree they visited or `nullptr` on error.
39 class AffineApplyExpander
40     : public AffineExprVisitor<AffineApplyExpander, Value> {
41 public:
42   /// This internal class expects arguments to be non-null, checks must be
43   /// performed at the call site.
44   AffineApplyExpander(OpBuilder &builder, ValueRange dimValues,
45                       ValueRange symbolValues, Location loc)
46       : builder(builder), dimValues(dimValues), symbolValues(symbolValues),
47         loc(loc) {}
48 
49   template <typename OpTy>
50   Value buildBinaryExpr(AffineBinaryOpExpr expr) {
51     auto lhs = visit(expr.getLHS());
52     auto rhs = visit(expr.getRHS());
53     if (!lhs || !rhs)
54       return nullptr;
55     auto op = builder.create<OpTy>(loc, lhs, rhs);
56     return op.getResult();
57   }
58 
59   Value visitAddExpr(AffineBinaryOpExpr expr) {
60     return buildBinaryExpr<arith::AddIOp>(expr);
61   }
62 
63   Value visitMulExpr(AffineBinaryOpExpr expr) {
64     return buildBinaryExpr<arith::MulIOp>(expr);
65   }
66 
67   /// Euclidean modulo operation: negative RHS is not allowed.
68   /// Remainder of the euclidean integer division is always non-negative.
69   ///
70   /// Implemented as
71   ///
72   ///     a mod b =
73   ///         let remainder = srem a, b;
74   ///             negative = a < 0 in
75   ///         select negative, remainder + b, remainder.
76   Value visitModExpr(AffineBinaryOpExpr expr) {
77     auto rhsConst = expr.getRHS().dyn_cast<AffineConstantExpr>();
78     if (!rhsConst) {
79       emitError(
80           loc,
81           "semi-affine expressions (modulo by non-const) are not supported");
82       return nullptr;
83     }
84     if (rhsConst.getValue() <= 0) {
85       emitError(loc, "modulo by non-positive value is not supported");
86       return nullptr;
87     }
88 
89     auto lhs = visit(expr.getLHS());
90     auto rhs = visit(expr.getRHS());
91     assert(lhs && rhs && "unexpected affine expr lowering failure");
92 
93     Value remainder = builder.create<arith::RemSIOp>(loc, lhs, rhs);
94     Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
95     Value isRemainderNegative = builder.create<arith::CmpIOp>(
96         loc, arith::CmpIPredicate::slt, remainder, zeroCst);
97     Value correctedRemainder =
98         builder.create<arith::AddIOp>(loc, remainder, rhs);
99     Value result = builder.create<SelectOp>(loc, isRemainderNegative,
100                                             correctedRemainder, remainder);
101     return result;
102   }
103 
104   /// Floor division operation (rounds towards negative infinity).
105   ///
106   /// For positive divisors, it can be implemented without branching and with a
107   /// single division operation as
108   ///
109   ///        a floordiv b =
110   ///            let negative = a < 0 in
111   ///            let absolute = negative ? -a - 1 : a in
112   ///            let quotient = absolute / b in
113   ///                negative ? -quotient - 1 : quotient
114   Value visitFloorDivExpr(AffineBinaryOpExpr expr) {
115     auto rhsConst = expr.getRHS().dyn_cast<AffineConstantExpr>();
116     if (!rhsConst) {
117       emitError(
118           loc,
119           "semi-affine expressions (division by non-const) are not supported");
120       return nullptr;
121     }
122     if (rhsConst.getValue() <= 0) {
123       emitError(loc, "division by non-positive value is not supported");
124       return nullptr;
125     }
126 
127     auto lhs = visit(expr.getLHS());
128     auto rhs = visit(expr.getRHS());
129     assert(lhs && rhs && "unexpected affine expr lowering failure");
130 
131     Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
132     Value noneCst = builder.create<arith::ConstantIndexOp>(loc, -1);
133     Value negative = builder.create<arith::CmpIOp>(
134         loc, arith::CmpIPredicate::slt, lhs, zeroCst);
135     Value negatedDecremented = builder.create<arith::SubIOp>(loc, noneCst, lhs);
136     Value dividend =
137         builder.create<SelectOp>(loc, negative, negatedDecremented, lhs);
138     Value quotient = builder.create<arith::DivSIOp>(loc, dividend, rhs);
139     Value correctedQuotient =
140         builder.create<arith::SubIOp>(loc, noneCst, quotient);
141     Value result =
142         builder.create<SelectOp>(loc, negative, correctedQuotient, quotient);
143     return result;
144   }
145 
146   /// Ceiling division operation (rounds towards positive infinity).
147   ///
148   /// For positive divisors, it can be implemented without branching and with a
149   /// single division operation as
150   ///
151   ///     a ceildiv b =
152   ///         let negative = a <= 0 in
153   ///         let absolute = negative ? -a : a - 1 in
154   ///         let quotient = absolute / b in
155   ///             negative ? -quotient : quotient + 1
156   Value visitCeilDivExpr(AffineBinaryOpExpr expr) {
157     auto rhsConst = expr.getRHS().dyn_cast<AffineConstantExpr>();
158     if (!rhsConst) {
159       emitError(loc) << "semi-affine expressions (division by non-const) are "
160                         "not supported";
161       return nullptr;
162     }
163     if (rhsConst.getValue() <= 0) {
164       emitError(loc, "division by non-positive value is not supported");
165       return nullptr;
166     }
167     auto lhs = visit(expr.getLHS());
168     auto rhs = visit(expr.getRHS());
169     assert(lhs && rhs && "unexpected affine expr lowering failure");
170 
171     Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
172     Value oneCst = builder.create<arith::ConstantIndexOp>(loc, 1);
173     Value nonPositive = builder.create<arith::CmpIOp>(
174         loc, arith::CmpIPredicate::sle, lhs, zeroCst);
175     Value negated = builder.create<arith::SubIOp>(loc, zeroCst, lhs);
176     Value decremented = builder.create<arith::SubIOp>(loc, lhs, oneCst);
177     Value dividend =
178         builder.create<SelectOp>(loc, nonPositive, negated, decremented);
179     Value quotient = builder.create<arith::DivSIOp>(loc, dividend, rhs);
180     Value negatedQuotient =
181         builder.create<arith::SubIOp>(loc, zeroCst, quotient);
182     Value incrementedQuotient =
183         builder.create<arith::AddIOp>(loc, quotient, oneCst);
184     Value result = builder.create<SelectOp>(loc, nonPositive, negatedQuotient,
185                                             incrementedQuotient);
186     return result;
187   }
188 
189   Value visitConstantExpr(AffineConstantExpr expr) {
190     auto op = builder.create<arith::ConstantIndexOp>(loc, expr.getValue());
191     return op.getResult();
192   }
193 
194   Value visitDimExpr(AffineDimExpr expr) {
195     assert(expr.getPosition() < dimValues.size() &&
196            "affine dim position out of range");
197     return dimValues[expr.getPosition()];
198   }
199 
200   Value visitSymbolExpr(AffineSymbolExpr expr) {
201     assert(expr.getPosition() < symbolValues.size() &&
202            "symbol dim position out of range");
203     return symbolValues[expr.getPosition()];
204   }
205 
206 private:
207   OpBuilder &builder;
208   ValueRange dimValues;
209   ValueRange symbolValues;
210 
211   Location loc;
212 };
213 } // namespace
214 
215 /// Create a sequence of operations that implement the `expr` applied to the
216 /// given dimension and symbol values.
217 mlir::Value mlir::expandAffineExpr(OpBuilder &builder, Location loc,
218                                    AffineExpr expr, ValueRange dimValues,
219                                    ValueRange symbolValues) {
220   return AffineApplyExpander(builder, dimValues, symbolValues, loc).visit(expr);
221 }
222 
223 /// Create a sequence of operations that implement the `affineMap` applied to
224 /// the given `operands` (as it it were an AffineApplyOp).
225 Optional<SmallVector<Value, 8>> mlir::expandAffineMap(OpBuilder &builder,
226                                                       Location loc,
227                                                       AffineMap affineMap,
228                                                       ValueRange operands) {
229   auto numDims = affineMap.getNumDims();
230   auto expanded = llvm::to_vector<8>(
231       llvm::map_range(affineMap.getResults(),
232                       [numDims, &builder, loc, operands](AffineExpr expr) {
233                         return expandAffineExpr(builder, loc, expr,
234                                                 operands.take_front(numDims),
235                                                 operands.drop_front(numDims));
236                       }));
237   if (llvm::all_of(expanded, [](Value v) { return v; }))
238     return expanded;
239   return None;
240 }
241 
242 /// Given a range of values, emit the code that reduces them with "min" or "max"
243 /// depending on the provided comparison predicate.  The predicate defines which
244 /// comparison to perform, "lt" for "min", "gt" for "max" and is used for the
245 /// `cmpi` operation followed by the `select` operation:
246 ///
247 ///   %cond   = arith.cmpi "predicate" %v0, %v1
248 ///   %result = select %cond, %v0, %v1
249 ///
250 /// Multiple values are scanned in a linear sequence.  This creates a data
251 /// dependences that wouldn't exist in a tree reduction, but is easier to
252 /// recognize as a reduction by the subsequent passes.
253 static Value buildMinMaxReductionSeq(Location loc,
254                                      arith::CmpIPredicate predicate,
255                                      ValueRange values, OpBuilder &builder) {
256   assert(!llvm::empty(values) && "empty min/max chain");
257 
258   auto valueIt = values.begin();
259   Value value = *valueIt++;
260   for (; valueIt != values.end(); ++valueIt) {
261     auto cmpOp = builder.create<arith::CmpIOp>(loc, predicate, value, *valueIt);
262     value = builder.create<SelectOp>(loc, cmpOp.getResult(), value, *valueIt);
263   }
264 
265   return value;
266 }
267 
268 /// Emit instructions that correspond to computing the maximum value among the
269 /// values of a (potentially) multi-output affine map applied to `operands`.
270 static Value lowerAffineMapMax(OpBuilder &builder, Location loc, AffineMap map,
271                                ValueRange operands) {
272   if (auto values = expandAffineMap(builder, loc, map, operands))
273     return buildMinMaxReductionSeq(loc, arith::CmpIPredicate::sgt, *values,
274                                    builder);
275   return nullptr;
276 }
277 
278 /// Emit instructions that correspond to computing the minimum value among the
279 /// values of a (potentially) multi-output affine map applied to `operands`.
280 static Value lowerAffineMapMin(OpBuilder &builder, Location loc, AffineMap map,
281                                ValueRange operands) {
282   if (auto values = expandAffineMap(builder, loc, map, operands))
283     return buildMinMaxReductionSeq(loc, arith::CmpIPredicate::slt, *values,
284                                    builder);
285   return nullptr;
286 }
287 
288 /// Emit instructions that correspond to the affine map in the upper bound
289 /// applied to the respective operands, and compute the minimum value across
290 /// the results.
291 Value mlir::lowerAffineUpperBound(AffineForOp op, OpBuilder &builder) {
292   return lowerAffineMapMin(builder, op.getLoc(), op.getUpperBoundMap(),
293                            op.getUpperBoundOperands());
294 }
295 
296 /// Emit instructions that correspond to the affine map in the lower bound
297 /// applied to the respective operands, and compute the maximum value across
298 /// the results.
299 Value mlir::lowerAffineLowerBound(AffineForOp op, OpBuilder &builder) {
300   return lowerAffineMapMax(builder, op.getLoc(), op.getLowerBoundMap(),
301                            op.getLowerBoundOperands());
302 }
303 
304 namespace {
305 class AffineMinLowering : public OpRewritePattern<AffineMinOp> {
306 public:
307   using OpRewritePattern<AffineMinOp>::OpRewritePattern;
308 
309   LogicalResult matchAndRewrite(AffineMinOp op,
310                                 PatternRewriter &rewriter) const override {
311     Value reduced =
312         lowerAffineMapMin(rewriter, op.getLoc(), op.map(), op.operands());
313     if (!reduced)
314       return failure();
315 
316     rewriter.replaceOp(op, reduced);
317     return success();
318   }
319 };
320 
321 class AffineMaxLowering : public OpRewritePattern<AffineMaxOp> {
322 public:
323   using OpRewritePattern<AffineMaxOp>::OpRewritePattern;
324 
325   LogicalResult matchAndRewrite(AffineMaxOp op,
326                                 PatternRewriter &rewriter) const override {
327     Value reduced =
328         lowerAffineMapMax(rewriter, op.getLoc(), op.map(), op.operands());
329     if (!reduced)
330       return failure();
331 
332     rewriter.replaceOp(op, reduced);
333     return success();
334   }
335 };
336 
337 /// Affine yields ops are removed.
338 class AffineYieldOpLowering : public OpRewritePattern<AffineYieldOp> {
339 public:
340   using OpRewritePattern<AffineYieldOp>::OpRewritePattern;
341 
342   LogicalResult matchAndRewrite(AffineYieldOp op,
343                                 PatternRewriter &rewriter) const override {
344     if (isa<scf::ParallelOp>(op->getParentOp())) {
345       // scf.parallel does not yield any values via its terminator scf.yield but
346       // models reductions differently using additional ops in its region.
347       rewriter.replaceOpWithNewOp<scf::YieldOp>(op);
348       return success();
349     }
350     rewriter.replaceOpWithNewOp<scf::YieldOp>(op, op.operands());
351     return success();
352   }
353 };
354 
355 class AffineForLowering : public OpRewritePattern<AffineForOp> {
356 public:
357   using OpRewritePattern<AffineForOp>::OpRewritePattern;
358 
359   LogicalResult matchAndRewrite(AffineForOp op,
360                                 PatternRewriter &rewriter) const override {
361     Location loc = op.getLoc();
362     Value lowerBound = lowerAffineLowerBound(op, rewriter);
363     Value upperBound = lowerAffineUpperBound(op, rewriter);
364     Value step = rewriter.create<arith::ConstantIndexOp>(loc, op.getStep());
365     auto scfForOp = rewriter.create<scf::ForOp>(loc, lowerBound, upperBound,
366                                                 step, op.getIterOperands());
367     rewriter.eraseBlock(scfForOp.getBody());
368     rewriter.inlineRegionBefore(op.region(), scfForOp.getRegion(),
369                                 scfForOp.getRegion().end());
370     rewriter.replaceOp(op, scfForOp.getResults());
371     return success();
372   }
373 };
374 
375 /// Convert an `affine.parallel` (loop nest) operation into a `scf.parallel`
376 /// operation.
377 class AffineParallelLowering : public OpRewritePattern<AffineParallelOp> {
378 public:
379   using OpRewritePattern<AffineParallelOp>::OpRewritePattern;
380 
381   LogicalResult matchAndRewrite(AffineParallelOp op,
382                                 PatternRewriter &rewriter) const override {
383     Location loc = op.getLoc();
384     SmallVector<Value, 8> steps;
385     SmallVector<Value, 8> upperBoundTuple;
386     SmallVector<Value, 8> lowerBoundTuple;
387     SmallVector<Value, 8> identityVals;
388     // Emit IR computing the lower and upper bound by expanding the map
389     // expression.
390     lowerBoundTuple.reserve(op.getNumDims());
391     upperBoundTuple.reserve(op.getNumDims());
392     for (unsigned i = 0, e = op.getNumDims(); i < e; ++i) {
393       Value lower = lowerAffineMapMax(rewriter, loc, op.getLowerBoundMap(i),
394                                       op.getLowerBoundsOperands());
395       if (!lower)
396         return rewriter.notifyMatchFailure(op, "couldn't convert lower bounds");
397       lowerBoundTuple.push_back(lower);
398 
399       Value upper = lowerAffineMapMin(rewriter, loc, op.getUpperBoundMap(i),
400                                       op.getUpperBoundsOperands());
401       if (!upper)
402         return rewriter.notifyMatchFailure(op, "couldn't convert upper bounds");
403       upperBoundTuple.push_back(upper);
404     }
405     steps.reserve(op.steps().size());
406     for (Attribute step : op.steps())
407       steps.push_back(rewriter.create<arith::ConstantIndexOp>(
408           loc, step.cast<IntegerAttr>().getInt()));
409 
410     // Get the terminator op.
411     Operation *affineParOpTerminator = op.getBody()->getTerminator();
412     scf::ParallelOp parOp;
413     if (op.results().empty()) {
414       // Case with no reduction operations/return values.
415       parOp = rewriter.create<scf::ParallelOp>(loc, lowerBoundTuple,
416                                                upperBoundTuple, steps,
417                                                /*bodyBuilderFn=*/nullptr);
418       rewriter.eraseBlock(parOp.getBody());
419       rewriter.inlineRegionBefore(op.region(), parOp.getRegion(),
420                                   parOp.getRegion().end());
421       rewriter.replaceOp(op, parOp.getResults());
422       return success();
423     }
424     // Case with affine.parallel with reduction operations/return values.
425     // scf.parallel handles the reduction operation differently unlike
426     // affine.parallel.
427     ArrayRef<Attribute> reductions = op.reductions().getValue();
428     for (auto pair : llvm::zip(reductions, op.getResultTypes())) {
429       // For each of the reduction operations get the identity values for
430       // initialization of the result values.
431       Attribute reduction = std::get<0>(pair);
432       Type resultType = std::get<1>(pair);
433       Optional<AtomicRMWKind> reductionOp = symbolizeAtomicRMWKind(
434           static_cast<uint64_t>(reduction.cast<IntegerAttr>().getInt()));
435       assert(reductionOp.hasValue() &&
436              "Reduction operation cannot be of None Type");
437       AtomicRMWKind reductionOpValue = reductionOp.getValue();
438       identityVals.push_back(
439           getIdentityValue(reductionOpValue, resultType, rewriter, loc));
440     }
441     parOp = rewriter.create<scf::ParallelOp>(
442         loc, lowerBoundTuple, upperBoundTuple, steps, identityVals,
443         /*bodyBuilderFn=*/nullptr);
444 
445     //  Copy the body of the affine.parallel op.
446     rewriter.eraseBlock(parOp.getBody());
447     rewriter.inlineRegionBefore(op.region(), parOp.getRegion(),
448                                 parOp.getRegion().end());
449     assert(reductions.size() == affineParOpTerminator->getNumOperands() &&
450            "Unequal number of reductions and operands.");
451     for (unsigned i = 0, end = reductions.size(); i < end; i++) {
452       // For each of the reduction operations get the respective mlir::Value.
453       Optional<AtomicRMWKind> reductionOp =
454           symbolizeAtomicRMWKind(reductions[i].cast<IntegerAttr>().getInt());
455       assert(reductionOp.hasValue() &&
456              "Reduction Operation cannot be of None Type");
457       AtomicRMWKind reductionOpValue = reductionOp.getValue();
458       rewriter.setInsertionPoint(&parOp.getBody()->back());
459       auto reduceOp = rewriter.create<scf::ReduceOp>(
460           loc, affineParOpTerminator->getOperand(i));
461       rewriter.setInsertionPointToEnd(&reduceOp.getReductionOperator().front());
462       Value reductionResult = getReductionOp(
463           reductionOpValue, rewriter, loc,
464           reduceOp.getReductionOperator().front().getArgument(0),
465           reduceOp.getReductionOperator().front().getArgument(1));
466       rewriter.create<scf::ReduceReturnOp>(loc, reductionResult);
467     }
468     rewriter.replaceOp(op, parOp.getResults());
469     return success();
470   }
471 };
472 
473 class AffineIfLowering : public OpRewritePattern<AffineIfOp> {
474 public:
475   using OpRewritePattern<AffineIfOp>::OpRewritePattern;
476 
477   LogicalResult matchAndRewrite(AffineIfOp op,
478                                 PatternRewriter &rewriter) const override {
479     auto loc = op.getLoc();
480 
481     // Now we just have to handle the condition logic.
482     auto integerSet = op.getIntegerSet();
483     Value zeroConstant = rewriter.create<arith::ConstantIndexOp>(loc, 0);
484     SmallVector<Value, 8> operands(op.getOperands());
485     auto operandsRef = llvm::makeArrayRef(operands);
486 
487     // Calculate cond as a conjunction without short-circuiting.
488     Value cond = nullptr;
489     for (unsigned i = 0, e = integerSet.getNumConstraints(); i < e; ++i) {
490       AffineExpr constraintExpr = integerSet.getConstraint(i);
491       bool isEquality = integerSet.isEq(i);
492 
493       // Build and apply an affine expression
494       auto numDims = integerSet.getNumDims();
495       Value affResult = expandAffineExpr(rewriter, loc, constraintExpr,
496                                          operandsRef.take_front(numDims),
497                                          operandsRef.drop_front(numDims));
498       if (!affResult)
499         return failure();
500       auto pred =
501           isEquality ? arith::CmpIPredicate::eq : arith::CmpIPredicate::sge;
502       Value cmpVal =
503           rewriter.create<arith::CmpIOp>(loc, pred, affResult, zeroConstant);
504       cond = cond
505                  ? rewriter.create<arith::AndIOp>(loc, cond, cmpVal).getResult()
506                  : cmpVal;
507     }
508     cond = cond ? cond
509                 : rewriter.create<arith::ConstantIntOp>(loc, /*value=*/1,
510                                                         /*width=*/1);
511 
512     bool hasElseRegion = !op.elseRegion().empty();
513     auto ifOp = rewriter.create<scf::IfOp>(loc, op.getResultTypes(), cond,
514                                            hasElseRegion);
515     rewriter.inlineRegionBefore(op.thenRegion(), &ifOp.getThenRegion().back());
516     rewriter.eraseBlock(&ifOp.getThenRegion().back());
517     if (hasElseRegion) {
518       rewriter.inlineRegionBefore(op.elseRegion(),
519                                   &ifOp.getElseRegion().back());
520       rewriter.eraseBlock(&ifOp.getElseRegion().back());
521     }
522 
523     // Replace the Affine IfOp finally.
524     rewriter.replaceOp(op, ifOp.getResults());
525     return success();
526   }
527 };
528 
529 /// Convert an "affine.apply" operation into a sequence of arithmetic
530 /// operations using the StandardOps dialect.
531 class AffineApplyLowering : public OpRewritePattern<AffineApplyOp> {
532 public:
533   using OpRewritePattern<AffineApplyOp>::OpRewritePattern;
534 
535   LogicalResult matchAndRewrite(AffineApplyOp op,
536                                 PatternRewriter &rewriter) const override {
537     auto maybeExpandedMap =
538         expandAffineMap(rewriter, op.getLoc(), op.getAffineMap(),
539                         llvm::to_vector<8>(op.getOperands()));
540     if (!maybeExpandedMap)
541       return failure();
542     rewriter.replaceOp(op, *maybeExpandedMap);
543     return success();
544   }
545 };
546 
547 /// Apply the affine map from an 'affine.load' operation to its operands, and
548 /// feed the results to a newly created 'memref.load' operation (which replaces
549 /// the original 'affine.load').
550 class AffineLoadLowering : public OpRewritePattern<AffineLoadOp> {
551 public:
552   using OpRewritePattern<AffineLoadOp>::OpRewritePattern;
553 
554   LogicalResult matchAndRewrite(AffineLoadOp op,
555                                 PatternRewriter &rewriter) const override {
556     // Expand affine map from 'affineLoadOp'.
557     SmallVector<Value, 8> indices(op.getMapOperands());
558     auto resultOperands =
559         expandAffineMap(rewriter, op.getLoc(), op.getAffineMap(), indices);
560     if (!resultOperands)
561       return failure();
562 
563     // Build vector.load memref[expandedMap.results].
564     rewriter.replaceOpWithNewOp<memref::LoadOp>(op, op.getMemRef(),
565                                                 *resultOperands);
566     return success();
567   }
568 };
569 
570 /// Apply the affine map from an 'affine.prefetch' operation to its operands,
571 /// and feed the results to a newly created 'memref.prefetch' operation (which
572 /// replaces the original 'affine.prefetch').
573 class AffinePrefetchLowering : public OpRewritePattern<AffinePrefetchOp> {
574 public:
575   using OpRewritePattern<AffinePrefetchOp>::OpRewritePattern;
576 
577   LogicalResult matchAndRewrite(AffinePrefetchOp op,
578                                 PatternRewriter &rewriter) const override {
579     // Expand affine map from 'affinePrefetchOp'.
580     SmallVector<Value, 8> indices(op.getMapOperands());
581     auto resultOperands =
582         expandAffineMap(rewriter, op.getLoc(), op.getAffineMap(), indices);
583     if (!resultOperands)
584       return failure();
585 
586     // Build memref.prefetch memref[expandedMap.results].
587     rewriter.replaceOpWithNewOp<memref::PrefetchOp>(
588         op, op.memref(), *resultOperands, op.isWrite(), op.localityHint(),
589         op.isDataCache());
590     return success();
591   }
592 };
593 
594 /// Apply the affine map from an 'affine.store' operation to its operands, and
595 /// feed the results to a newly created 'memref.store' operation (which replaces
596 /// the original 'affine.store').
597 class AffineStoreLowering : public OpRewritePattern<AffineStoreOp> {
598 public:
599   using OpRewritePattern<AffineStoreOp>::OpRewritePattern;
600 
601   LogicalResult matchAndRewrite(AffineStoreOp op,
602                                 PatternRewriter &rewriter) const override {
603     // Expand affine map from 'affineStoreOp'.
604     SmallVector<Value, 8> indices(op.getMapOperands());
605     auto maybeExpandedMap =
606         expandAffineMap(rewriter, op.getLoc(), op.getAffineMap(), indices);
607     if (!maybeExpandedMap)
608       return failure();
609 
610     // Build memref.store valueToStore, memref[expandedMap.results].
611     rewriter.replaceOpWithNewOp<memref::StoreOp>(
612         op, op.getValueToStore(), op.getMemRef(), *maybeExpandedMap);
613     return success();
614   }
615 };
616 
617 /// Apply the affine maps from an 'affine.dma_start' operation to each of their
618 /// respective map operands, and feed the results to a newly created
619 /// 'memref.dma_start' operation (which replaces the original
620 /// 'affine.dma_start').
621 class AffineDmaStartLowering : public OpRewritePattern<AffineDmaStartOp> {
622 public:
623   using OpRewritePattern<AffineDmaStartOp>::OpRewritePattern;
624 
625   LogicalResult matchAndRewrite(AffineDmaStartOp op,
626                                 PatternRewriter &rewriter) const override {
627     SmallVector<Value, 8> operands(op.getOperands());
628     auto operandsRef = llvm::makeArrayRef(operands);
629 
630     // Expand affine map for DMA source memref.
631     auto maybeExpandedSrcMap = expandAffineMap(
632         rewriter, op.getLoc(), op.getSrcMap(),
633         operandsRef.drop_front(op.getSrcMemRefOperandIndex() + 1));
634     if (!maybeExpandedSrcMap)
635       return failure();
636     // Expand affine map for DMA destination memref.
637     auto maybeExpandedDstMap = expandAffineMap(
638         rewriter, op.getLoc(), op.getDstMap(),
639         operandsRef.drop_front(op.getDstMemRefOperandIndex() + 1));
640     if (!maybeExpandedDstMap)
641       return failure();
642     // Expand affine map for DMA tag memref.
643     auto maybeExpandedTagMap = expandAffineMap(
644         rewriter, op.getLoc(), op.getTagMap(),
645         operandsRef.drop_front(op.getTagMemRefOperandIndex() + 1));
646     if (!maybeExpandedTagMap)
647       return failure();
648 
649     // Build memref.dma_start operation with affine map results.
650     rewriter.replaceOpWithNewOp<memref::DmaStartOp>(
651         op, op.getSrcMemRef(), *maybeExpandedSrcMap, op.getDstMemRef(),
652         *maybeExpandedDstMap, op.getNumElements(), op.getTagMemRef(),
653         *maybeExpandedTagMap, op.getStride(), op.getNumElementsPerStride());
654     return success();
655   }
656 };
657 
658 /// Apply the affine map from an 'affine.dma_wait' operation tag memref,
659 /// and feed the results to a newly created 'memref.dma_wait' operation (which
660 /// replaces the original 'affine.dma_wait').
661 class AffineDmaWaitLowering : public OpRewritePattern<AffineDmaWaitOp> {
662 public:
663   using OpRewritePattern<AffineDmaWaitOp>::OpRewritePattern;
664 
665   LogicalResult matchAndRewrite(AffineDmaWaitOp op,
666                                 PatternRewriter &rewriter) const override {
667     // Expand affine map for DMA tag memref.
668     SmallVector<Value, 8> indices(op.getTagIndices());
669     auto maybeExpandedTagMap =
670         expandAffineMap(rewriter, op.getLoc(), op.getTagMap(), indices);
671     if (!maybeExpandedTagMap)
672       return failure();
673 
674     // Build memref.dma_wait operation with affine map results.
675     rewriter.replaceOpWithNewOp<memref::DmaWaitOp>(
676         op, op.getTagMemRef(), *maybeExpandedTagMap, op.getNumElements());
677     return success();
678   }
679 };
680 
681 /// Apply the affine map from an 'affine.vector_load' operation to its operands,
682 /// and feed the results to a newly created 'vector.load' operation (which
683 /// replaces the original 'affine.vector_load').
684 class AffineVectorLoadLowering : public OpRewritePattern<AffineVectorLoadOp> {
685 public:
686   using OpRewritePattern<AffineVectorLoadOp>::OpRewritePattern;
687 
688   LogicalResult matchAndRewrite(AffineVectorLoadOp op,
689                                 PatternRewriter &rewriter) const override {
690     // Expand affine map from 'affineVectorLoadOp'.
691     SmallVector<Value, 8> indices(op.getMapOperands());
692     auto resultOperands =
693         expandAffineMap(rewriter, op.getLoc(), op.getAffineMap(), indices);
694     if (!resultOperands)
695       return failure();
696 
697     // Build vector.load memref[expandedMap.results].
698     rewriter.replaceOpWithNewOp<vector::LoadOp>(
699         op, op.getVectorType(), op.getMemRef(), *resultOperands);
700     return success();
701   }
702 };
703 
704 /// Apply the affine map from an 'affine.vector_store' operation to its
705 /// operands, and feed the results to a newly created 'vector.store' operation
706 /// (which replaces the original 'affine.vector_store').
707 class AffineVectorStoreLowering : public OpRewritePattern<AffineVectorStoreOp> {
708 public:
709   using OpRewritePattern<AffineVectorStoreOp>::OpRewritePattern;
710 
711   LogicalResult matchAndRewrite(AffineVectorStoreOp op,
712                                 PatternRewriter &rewriter) const override {
713     // Expand affine map from 'affineVectorStoreOp'.
714     SmallVector<Value, 8> indices(op.getMapOperands());
715     auto maybeExpandedMap =
716         expandAffineMap(rewriter, op.getLoc(), op.getAffineMap(), indices);
717     if (!maybeExpandedMap)
718       return failure();
719 
720     rewriter.replaceOpWithNewOp<vector::StoreOp>(
721         op, op.getValueToStore(), op.getMemRef(), *maybeExpandedMap);
722     return success();
723   }
724 };
725 
726 } // namespace
727 
728 void mlir::populateAffineToStdConversionPatterns(RewritePatternSet &patterns) {
729   // clang-format off
730   patterns.add<
731       AffineApplyLowering,
732       AffineDmaStartLowering,
733       AffineDmaWaitLowering,
734       AffineLoadLowering,
735       AffineMinLowering,
736       AffineMaxLowering,
737       AffineParallelLowering,
738       AffinePrefetchLowering,
739       AffineStoreLowering,
740       AffineForLowering,
741       AffineIfLowering,
742       AffineYieldOpLowering>(patterns.getContext());
743   // clang-format on
744 }
745 
746 void mlir::populateAffineToVectorConversionPatterns(
747     RewritePatternSet &patterns) {
748   // clang-format off
749   patterns.add<
750       AffineVectorLoadLowering,
751       AffineVectorStoreLowering>(patterns.getContext());
752   // clang-format on
753 }
754 
755 namespace {
756 class LowerAffinePass : public ConvertAffineToStandardBase<LowerAffinePass> {
757   void runOnOperation() override {
758     RewritePatternSet patterns(&getContext());
759     populateAffineToStdConversionPatterns(patterns);
760     populateAffineToVectorConversionPatterns(patterns);
761     ConversionTarget target(getContext());
762     target
763         .addLegalDialect<arith::ArithmeticDialect, memref::MemRefDialect,
764                          scf::SCFDialect, StandardOpsDialect, VectorDialect>();
765     if (failed(applyPartialConversion(getOperation(), target,
766                                       std::move(patterns))))
767       signalPassFailure();
768   }
769 };
770 } // namespace
771 
772 /// Lowers If and For operations within a function into their lower level CFG
773 /// equivalent blocks.
774 std::unique_ptr<Pass> mlir::createLowerAffinePass() {
775   return std::make_unique<LowerAffinePass>();
776 }
777