1 //===- Loops.cpp - conversion from Linalg named and generic ops to loops --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PassDetail.h"
10 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
11 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
12 #include "mlir/Dialect/Linalg/Passes.h"
13 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
14 #include "mlir/Dialect/Linalg/Utils/Utils.h"
15 #include "mlir/Dialect/SCF/Transforms.h"
16 #include "mlir/Dialect/StandardOps/Utils/Utils.h"
17 #include "mlir/IR/AffineExpr.h"
18 #include "mlir/IR/AffineMap.h"
19 #include "mlir/IR/BlockAndValueMapping.h"
20 #include "mlir/Support/LLVM.h"
21 #include "mlir/Transforms/DialectConversion.h"
22 #include "mlir/Transforms/FoldUtils.h"
23 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
24 #include "llvm/ADT/TypeSwitch.h"
25 
26 using namespace mlir;
27 using namespace mlir::linalg;
28 
29 static SmallVector<Value> makeCanonicalAffineApplies(OpBuilder &b, Location loc,
30                                                      AffineMap map,
31                                                      ArrayRef<Value> vals) {
32   if (map.isEmpty())
33     return {};
34 
35   assert(map.getNumInputs() == vals.size());
36   SmallVector<Value> res;
37   res.reserve(map.getNumResults());
38   auto dims = map.getNumDims();
39   for (auto e : map.getResults()) {
40     auto exprMap = AffineMap::get(dims, map.getNumSymbols(), e);
41     SmallVector<Value> operands(vals.begin(), vals.end());
42     canonicalizeMapAndOperands(&exprMap, &operands);
43     res.push_back(b.create<AffineApplyOp>(loc, exprMap, operands));
44   }
45   return res;
46 }
47 
48 template <typename LoadOpTy, typename StoreOpTy, typename OpType>
49 static void inlineRegionAndEmitStore(OpBuilder &b, Location loc, OpType op,
50                                      ArrayRef<Value> indexedValues,
51                                      ArrayRef<SmallVector<Value>> indexing,
52                                      ArrayRef<Value> outputBuffers) {
53   auto &block = op->getRegion(0).front();
54   BlockAndValueMapping map;
55   map.map(block.getArguments(), indexedValues);
56   for (auto &op : block.without_terminator()) {
57     auto *newOp = b.clone(op, map);
58     map.map(op.getResults(), newOp->getResults());
59   }
60 
61   Operation *terminator = block.getTerminator();
62   for (OpOperand &operand : terminator->getOpOperands()) {
63     Value toStore = map.lookupOrDefault(operand.get());
64     b.create<StoreOpTy>(loc, toStore, outputBuffers[operand.getOperandNumber()],
65                         indexing[operand.getOperandNumber()]);
66   }
67 }
68 
69 // Returns a pair that contains input indices and output indices of a
70 // SingleInputPoolingOp `op`.
71 struct InputAndOutputIndices {
72   SmallVector<Value> inputs;
73   SmallVector<Value> outputs;
74 };
75 template <typename SingleInputPoolingOp>
76 static InputAndOutputIndices
77 getInputAndOutputIndices(OpBuilder &b, Location loc, ArrayRef<Value> allIvs,
78                          SingleInputPoolingOp op) {
79   auto mapsRange = op.indexing_maps().template getAsRange<AffineMapAttr>();
80   auto maps = llvm::to_vector<8>(
81       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
82   return InputAndOutputIndices{
83       makeCanonicalAffineApplies(b, loc, maps[0], allIvs),
84       makeCanonicalAffineApplies(b, loc, maps[2], allIvs)};
85 }
86 
87 /// Emits the MLIR for the scalar part of the generic op by:
88 ///   1. Emitting load ops for each input and output view in order. This is
89 ///      achieved by applying the appropriate input or output map to the
90 ///      enclosing induction variables.
91 ///   2. Emitting a call to `op.fun()` that takes as arguments the scalars
92 ///      from point 1. above.
93 ///   3. Emitting store ops to store the results of 2. to the output
94 ///      views.
95 ///
96 /// An example output may resemble:
97 ///
98 /// ```
99 ///    scf.for %i = %c0 to %0 step %c1 {
100 ///      scf.for %j = %c0 to %1 step %c1 {
101 ///        scf.for %k = %c0 to %4 step %c1 {
102 ///          %11 = load %arg0[%i, %j] :
103 ///            memref<?x?xf32, stride_specification>
104 ///          %12 = load %arg1[%i, %j, %k] :
105 ///            memref<?x?x?xf32, stride_specification>
106 ///          %13 = load %arg2[%i, %k, %j] :
107 ///            memref<?x?x?xf32, stride_specification>
108 ///          %14:2 = call @foo(%11, %12, %13) : (f32, f32, f32) -> (f32, f32)
109 ///          store %14#0, %arg1[%i, %j, %k] :
110 ///            memref<?x?x?Xf32, stride_specification>
111 ///          store %14#1, %arg2[%i, %k, %j] :
112 ///            memref<?x?x?Xf32, stride_specification>
113 ///       }
114 ///      }
115 ///    }
116 /// ```
117 template <typename LoadOpTy, typename StoreOpTy>
118 static void emitScalarImplementation(OpBuilder &b, Location loc,
119                                      ArrayRef<Value> allIvs,
120                                      LinalgOp linalgOp) {
121   assert(linalgOp.hasBufferSemantics() &&
122          "expected linalg op with buffer semantics");
123   SmallVector<Value> indexedValues;
124   indexedValues.reserve(linalgOp.getNumInputsAndOutputs());
125 
126   auto allIvsPlusDims = SmallVector<Value>(allIvs.begin(), allIvs.end());
127 
128   // TODO: Avoid the loads if the corresponding argument of the
129   // region has no uses.
130   // 1.a. Emit load from input operand or for scalars access the operand itself.
131   for (OpOperand *inputOperand : linalgOp.getInputOperands()) {
132     if (linalgOp.isScalar(inputOperand)) {
133       indexedValues.push_back(inputOperand->get());
134       continue;
135     }
136     auto indexing = makeCanonicalAffineApplies(
137         b, loc, linalgOp.getTiedIndexingMap(inputOperand), allIvsPlusDims);
138     indexedValues.push_back(
139         b.create<LoadOpTy>(loc, inputOperand->get(), indexing));
140   }
141   // 1.b. Emit load from output views.
142   for (OpOperand *outputOperand : linalgOp.getOutputOperands()) {
143     SmallVector<Value> indexing = makeCanonicalAffineApplies(
144         b, loc, linalgOp.getTiedIndexingMap(outputOperand), allIvsPlusDims);
145     indexedValues.push_back(
146         b.create<LoadOpTy>(loc, outputOperand->get(), indexing));
147   }
148 
149   // TODO: When a region inliner exists, use it.
150   // 2. Inline region, currently only works for a single basic block.
151   // 3. Emit store.
152   SmallVector<SmallVector<Value>, 8> indexing;
153   SmallVector<Value> outputBuffers;
154   for (OpOperand *outputOperand : linalgOp.getOutputBufferOperands()) {
155     indexing.push_back(makeCanonicalAffineApplies(
156         b, loc, linalgOp.getTiedIndexingMap(outputOperand), allIvsPlusDims));
157     outputBuffers.push_back(outputOperand->get());
158   }
159   inlineRegionAndEmitStore<LoadOpTy, StoreOpTy>(b, loc, linalgOp, indexedValues,
160                                                 indexing, outputBuffers);
161 }
162 
163 /// Replace the index operations in the body of the loop nest by the matching
164 /// induction variables.
165 static void replaceIndexOpsByInductionVariables(LinalgOp linalgOp,
166                                                 PatternRewriter &rewriter,
167                                                 ArrayRef<Operation *> loopOps) {
168   // Extract the induction variables of the loop nest from outer to inner.
169   SmallVector<Value> allIvs;
170   for (Operation *loopOp : loopOps) {
171     llvm::TypeSwitch<Operation *>(loopOp)
172         .Case([&](scf::ParallelOp parallelOp) {
173           allIvs.append(parallelOp.getInductionVars().begin(),
174                         parallelOp.getInductionVars().end());
175         })
176         .Case([&](scf::ForOp forOp) {
177           allIvs.push_back(forOp.getInductionVar());
178         })
179         .Case([&](AffineForOp affineForOp) {
180           allIvs.push_back(affineForOp.getInductionVar());
181         })
182         .Default([&](Operation *op) { assert(false && "unexpected op"); });
183   }
184   assert(linalgOp.getNumLoops() == allIvs.size() &&
185          "expected the number of loops and induction variables to match");
186   // Replace the index operations in the body of the innermost loop op.
187   if (!loopOps.empty()) {
188     LoopLikeOpInterface loopOp = loopOps.back();
189     for (IndexOp indexOp :
190          llvm::make_early_inc_range(loopOp.getLoopBody().getOps<IndexOp>()))
191       rewriter.replaceOp(indexOp, allIvs[indexOp.dim()]);
192   }
193 }
194 
195 template <typename LoopTy>
196 static Optional<LinalgLoops> linalgOpToLoopsImpl(PatternRewriter &rewriter,
197                                                  LinalgOp linalgOp) {
198   using LoadOpTy =
199       typename std::conditional<std::is_same<LoopTy, AffineForOp>::value,
200                                 AffineLoadOp, memref::LoadOp>::type;
201   using StoreOpTy =
202       typename std::conditional<std::is_same<LoopTy, AffineForOp>::value,
203                                 AffineStoreOp, memref::StoreOp>::type;
204 
205   // The flattened loopToOperandRangesMaps is expected to be an invertible
206   // permutation map (which is asserted in the inverse calculation).
207   assert(linalgOp.hasBufferSemantics() &&
208          "expected linalg op with buffer semantics");
209 
210   auto loopRanges = linalgOp.createLoopRanges(rewriter, linalgOp.getLoc());
211   auto iteratorTypes = llvm::to_vector<4>(linalgOp.iterator_types().getValue());
212 
213   SmallVector<Value> allIvs;
214   GenerateLoopNest<LoopTy>::doit(
215       rewriter, linalgOp.getLoc(), loopRanges, linalgOp, iteratorTypes,
216       [&](OpBuilder &b, Location loc, ValueRange ivs,
217           ValueRange operandValuesToUse) -> scf::ValueVector {
218         assert(operandValuesToUse == linalgOp->getOperands() &&
219                "expect operands are captured and not passed by loop argument");
220         allIvs.append(ivs.begin(), ivs.end());
221         emitScalarImplementation<LoadOpTy, StoreOpTy>(b, loc, allIvs, linalgOp);
222         return scf::ValueVector{};
223       });
224   // Number of loop ops might be different from the number of ivs since some
225   // loops like affine.parallel and scf.parallel have multiple ivs.
226   SetVector<Operation *> loopSet;
227   for (Value iv : allIvs) {
228     if (!iv)
229       return {};
230     // The induction variable is a block argument of the entry block of the
231     // loop operation.
232     BlockArgument ivVal = iv.dyn_cast<BlockArgument>();
233     if (!ivVal)
234       return {};
235     loopSet.insert(ivVal.getOwner()->getParentOp());
236   }
237   LinalgLoops loops(loopSet.begin(), loopSet.end());
238   // Replace all index operations in the loop body.
239   replaceIndexOpsByInductionVariables(linalgOp, rewriter, loops);
240   return loops;
241 }
242 
243 namespace {
244 template <typename LoopType>
245 class LinalgRewritePattern : public RewritePattern {
246 public:
247   LinalgRewritePattern(MLIRContext *context)
248       : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, context) {}
249 
250   LogicalResult matchAndRewrite(Operation *op,
251                                 PatternRewriter &rewriter) const override {
252     auto linalgOp = dyn_cast<LinalgOp>(op);
253     if (!isa<LinalgOp>(op))
254       return failure();
255     if (!linalgOpToLoopsImpl<LoopType>(rewriter, linalgOp))
256       return failure();
257     rewriter.eraseOp(op);
258     return success();
259   }
260 };
261 
262 /// Converts tiled_loop to SCF loop nests. All parallel dimensions are collected
263 /// into an scf.parallel loop and all sequential dimensions will result in the
264 /// nested scf.for loop nest. The pattern assumes that a tiled loop with
265 /// iterator_types ["reduction", "parallel", "reduction"] can be reordered. It
266 /// is true for the tiling that is currently suppported by Linalg.
267 struct TiledLoopToSCFPattern : public OpRewritePattern<TiledLoopOp> {
268   using OpRewritePattern<TiledLoopOp>::OpRewritePattern;
269 
270   LogicalResult matchAndRewrite(TiledLoopOp tiledLoop,
271                                 PatternRewriter &rewriter) const override {
272     // Fail conversion if the `tiled_loop` has not been bufferized.
273     if (!tiledLoop.hasBufferSemantics())
274       return failure();
275 
276     // Collect loop control parameters for parallel and sequential dimensions.
277     SmallVector<Value, 3> seqLBs, seqUBs, seqSteps, seqIVs;
278     SmallVector<Value, 3> parLBs, parUBs, parSteps, parIVs;
279     for (auto en : llvm::enumerate(
280              llvm::zip(tiledLoop.lowerBound(), tiledLoop.upperBound(),
281                        tiledLoop.step(), tiledLoop.getInductionVars()))) {
282       Value lb, ub, step, iv;
283       std::tie(lb, ub, step, iv) = en.value();
284       if (tiledLoop.isParallelDimension(en.index())) {
285         parLBs.push_back(lb);
286         parUBs.push_back(ub);
287         parSteps.push_back(step);
288         parIVs.push_back(iv);
289       } else {
290         seqLBs.push_back(lb);
291         seqUBs.push_back(ub);
292         seqSteps.push_back(step);
293         seqIVs.push_back(iv);
294       }
295     }
296 
297     Location loc = tiledLoop.getLoc();
298     auto generateForLoopNestAndCloneBody = [&](OpBuilder &builder, Location loc,
299                                                ValueRange ivs) {
300       BlockAndValueMapping bvm;
301       bvm.map(parIVs, ivs);
302       bvm.map(tiledLoop.getRegionInputArgs(), tiledLoop.inputs());
303       bvm.map(tiledLoop.getRegionOutputArgs(), tiledLoop.outputs());
304 
305       // If not all dimensions of the tiled loop are parallel, an scf.for loop
306       // nest is generated.
307       if (!seqIVs.empty()) {
308         scf::LoopNest nest =
309             scf::buildLoopNest(builder, loc, seqLBs, seqUBs, seqSteps,
310                                [&](OpBuilder &builder, Location loc,
311                                    ValueRange ivs) { bvm.map(seqIVs, ivs); });
312         builder.setInsertionPointToStart(nest.loops.back().getBody());
313       }
314       for (auto &op : tiledLoop.getBody()->without_terminator())
315         builder.clone(op, bvm);
316     };
317 
318     if (parIVs.empty())
319       generateForLoopNestAndCloneBody(rewriter, loc, llvm::None);
320     else
321       rewriter.create<scf::ParallelOp>(loc, parLBs, parUBs, parSteps,
322                                        generateForLoopNestAndCloneBody);
323     rewriter.eraseOp(tiledLoop);
324     return success();
325   }
326 };
327 
328 /// Local folding pattern for AffineApplyOp that we can apply greedily.
329 /// This replaces AffineApplyOp by the proper value in cases where the
330 /// associated map is trivial.
331 /// A trivial map here is defined as a map with a single result and either:
332 ///   1. Zero operand + returns a single AffineConstantExpr
333 ///   2. One operand + returns a single AffineDimExpr
334 ///   3. One operand + returns a single AffineSymbolExpr
335 //
336 /// In the first case, the AffineApplyOp is replaced by a new constant. In the
337 /// other cases, it is replaced by its unique operand.
338 struct FoldAffineOp : public RewritePattern {
339   FoldAffineOp(MLIRContext *context)
340       : RewritePattern(AffineApplyOp::getOperationName(), 0, context) {}
341 
342   LogicalResult matchAndRewrite(Operation *op,
343                                 PatternRewriter &rewriter) const override {
344     AffineApplyOp affineApplyOp = cast<AffineApplyOp>(op);
345     auto map = affineApplyOp.getAffineMap();
346     if (map.getNumResults() != 1 || map.getNumInputs() > 1)
347       return failure();
348 
349     AffineExpr expr = map.getResult(0);
350     if (map.getNumInputs() == 0) {
351       if (auto val = expr.dyn_cast<AffineConstantExpr>()) {
352         rewriter.replaceOpWithNewOp<ConstantIndexOp>(op, val.getValue());
353         return success();
354       }
355       return failure();
356     }
357     if (expr.dyn_cast<AffineDimExpr>() || expr.dyn_cast<AffineSymbolExpr>()) {
358       rewriter.replaceOp(op, op->getOperand(0));
359       return success();
360     }
361     return failure();
362   }
363 };
364 
365 template <typename LoopType>
366 static void lowerLinalgToLoopsImpl(FuncOp funcOp) {
367   MLIRContext *context = funcOp.getContext();
368   RewritePatternSet patterns(context);
369   patterns.add<LinalgRewritePattern<LoopType>>(context);
370   memref::DimOp::getCanonicalizationPatterns(patterns, context);
371   tensor::DimOp::getCanonicalizationPatterns(patterns, context);
372   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
373   patterns.add<FoldAffineOp>(context);
374   // Just apply the patterns greedily.
375   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
376 }
377 
378 struct LowerToAffineLoops
379     : public LinalgLowerToAffineLoopsBase<LowerToAffineLoops> {
380   void getDependentDialects(DialectRegistry &registry) const override {
381     registry.insert<memref::MemRefDialect>();
382   }
383   void runOnFunction() override {
384     lowerLinalgToLoopsImpl<AffineForOp>(getFunction());
385   }
386 };
387 
388 struct LowerToLoops : public LinalgLowerToLoopsBase<LowerToLoops> {
389   void getDependentDialects(DialectRegistry &registry) const override {
390     registry.insert<memref::MemRefDialect, scf::SCFDialect>();
391   }
392   void runOnFunction() override {
393     lowerLinalgToLoopsImpl<scf::ForOp>(getFunction());
394   }
395 };
396 
397 struct LowerToParallelLoops
398     : public LinalgLowerToParallelLoopsBase<LowerToParallelLoops> {
399   void runOnFunction() override {
400     lowerLinalgToLoopsImpl<scf::ParallelOp>(getFunction());
401   }
402 };
403 
404 struct LowerTiledLoopsToSCF
405     : public LinalgLowerTiledLoopsToSCFBase<LowerTiledLoopsToSCF> {
406   void runOnFunction() override {
407     MLIRContext *context = &getContext();
408     RewritePatternSet patterns(context);
409     populateTiledLoopToSCFPattern(patterns);
410     (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns));
411   }
412 };
413 } // namespace
414 
415 /// Rewrite a TiledLoopOp with bounds/step that potentially do not divide evenly
416 /// into two TiledLoopOps: One where the step divides the iteration space
417 /// evenly, followed another one for the last (partial) iteration (if any). This
418 /// function only rewrites the `idx`-th loop of the loop nest represented by
419 /// the TiledLoopOp. To peel the entire loop nest, this function must be called
420 /// multiple times.
421 ///
422 /// This function rewrites the given TiledLoopOp in-place and creates a new
423 /// TiledLoopOp for the last iteration. It replaces all uses of the original
424 /// TiledLoopOp with the results of the newly generated one.
425 ///
426 /// The newly generated TiledLoopOp is returned via `result`. The boundary
427 /// at which the loop is split (new upper bound) is returned via `splitBound`.
428 /// The return value indicates whether the TiledLoopOp was rewritten or not.
429 static LogicalResult peelTiledLoop(RewriterBase &b, TiledLoopOp loopOp,
430                                    int64_t idx, TiledLoopOp &result,
431                                    Value &splitBound) {
432   Value lb = loopOp.lowerBound()[idx], ub = loopOp.upperBound()[idx],
433         step = loopOp.step()[idx];
434   auto ubInt = getConstantIntValue(ub);
435 
436   auto loc = loopOp.getLoc();
437   AffineExpr exprLb, exprUb, exprStep;
438   bindSymbols(b.getContext(), exprLb, exprUb, exprStep);
439   // New upper bound: %ub - (%ub - %lb) mod %step
440   auto modMap = AffineMap::get(0, 3, {exprUb - ((exprUb - exprLb) % exprStep)});
441   SmallVector<Value> operands{lb, ub, step};
442   mlir::canonicalizeMapAndOperands(&modMap, &operands);
443   modMap = mlir::simplifyAffineMap(modMap);
444   RewriterBase::InsertionGuard guard(b);
445   b.setInsertionPoint(loopOp);
446   splitBound = b.createOrFold<AffineApplyOp>(loc, modMap, operands);
447   // No specialization necessary if step already divides upper bound evenly.
448   if (splitBound == ub || (ubInt && ubInt == getConstantIntValue(splitBound)))
449     return failure();
450 
451   // Create remainder loop.
452   b.setInsertionPointAfter(loopOp);
453   auto remainderLoop = cast<TiledLoopOp>(b.clone(*loopOp.getOperation()));
454   loopOp.replaceAllUsesWith(remainderLoop->getResults());
455   // Outputs: Take tensors from main loop's results. Take memrefs from main
456   // loop's outputs.
457   SmallVector<Value> remainderOutputs;
458   for (unsigned o = 0, t = 0; o < loopOp.getNumOutputs(); ++o) {
459     remainderOutputs.push_back(loopOp.outputs()[o].getType().isa<MemRefType>()
460                                    ? loopOp.outputs()[o]
461                                    : loopOp->getResult(t++));
462   }
463   remainderLoop.outputsMutable().assign(remainderOutputs);
464 
465   // Set new loop bounds.
466   b.updateRootInPlace(loopOp, [&]() {
467     SmallVector<Value> ubs = loopOp.upperBound();
468     ubs[idx] = splitBound;
469     loopOp.upperBoundMutable().assign(ubs);
470   });
471   SmallVector<Value> lbs = remainderLoop.lowerBound();
472   lbs[idx] = splitBound;
473   remainderLoop.lowerBoundMutable().assign(lbs);
474 
475   result = remainderLoop;
476   return success();
477 }
478 
479 template <typename OpTy, bool IsMin>
480 static void
481 rewriteAffineOpAfterPeeling(RewriterBase &rewriter, TiledLoopOp mainLoop,
482                             TiledLoopOp remainderLoop, Value mainIv,
483                             Value remainderIv, Value ub, Value step) {
484   mainLoop.walk([&](OpTy affineOp) {
485     AffineMap map = affineOp.getAffineMap();
486     (void)scf::rewritePeeledMinMaxOp(rewriter, affineOp, map,
487                                      affineOp.operands(), IsMin, mainIv, ub,
488                                      step, /*insideLoop=*/true);
489   });
490   remainderLoop.walk([&](OpTy affineOp) {
491     AffineMap map = affineOp.getAffineMap();
492     (void)scf::rewritePeeledMinMaxOp(rewriter, affineOp, map,
493                                      affineOp.operands(), IsMin, remainderIv,
494                                      ub, step, /*insideLoop=*/false);
495   });
496 }
497 
498 LogicalResult mlir::linalg::peelAndCanonicalizeTiledLoop(RewriterBase &rewriter,
499                                                          TiledLoopOp loopOp,
500                                                          int64_t idx,
501                                                          TiledLoopOp &result) {
502   int64_t numLoops = loopOp.iterator_types().size();
503   if (idx < 0 || numLoops <= idx)
504     return failure();
505 
506   Value ub = loopOp.upperBound()[idx];
507   TiledLoopOp remainderLoop;
508   Value splitBound;
509   if (failed(peelTiledLoop(rewriter, loopOp, idx, remainderLoop, splitBound)))
510     return failure();
511 
512   // Rewrite affine.min and affine.max ops.
513   Value mainIv = loopOp.getInductionVars()[idx], step = loopOp.step()[idx],
514         remainderIv = remainderLoop.getInductionVars()[idx];
515 
516   rewriteAffineOpAfterPeeling<AffineMinOp, /*IsMin=*/true>(
517       rewriter, loopOp, remainderLoop, mainIv, remainderIv, ub, step);
518   rewriteAffineOpAfterPeeling<AffineMaxOp, /*IsMin=*/false>(
519       rewriter, loopOp, remainderLoop, mainIv, remainderIv, ub, step);
520 
521   result = remainderLoop;
522   return success();
523 }
524 
525 void mlir::linalg::populateTiledLoopToSCFPattern(RewritePatternSet &patterns) {
526   patterns.add<TiledLoopToSCFPattern>(patterns.getContext());
527 }
528 
529 std::unique_ptr<OperationPass<FuncOp>>
530 mlir::createConvertLinalgTiledLoopsToSCFPass() {
531   return std::make_unique<LowerTiledLoopsToSCF>();
532 }
533 
534 std::unique_ptr<OperationPass<FuncOp>> mlir::createConvertLinalgToLoopsPass() {
535   return std::make_unique<LowerToLoops>();
536 }
537 
538 std::unique_ptr<OperationPass<FuncOp>>
539 mlir::createConvertLinalgToParallelLoopsPass() {
540   return std::make_unique<LowerToParallelLoops>();
541 }
542 
543 std::unique_ptr<OperationPass<FuncOp>>
544 mlir::createConvertLinalgToAffineLoopsPass() {
545   return std::make_unique<LowerToAffineLoops>();
546 }
547 
548 /// Emits a loop nest of `affine.for` with the proper body for `linalgOp`.
549 Optional<LinalgLoops>
550 mlir::linalg::linalgOpToAffineLoops(PatternRewriter &rewriter,
551                                     LinalgOp linalgOp) {
552   return linalgOpToLoopsImpl<AffineForOp>(rewriter, linalgOp);
553 }
554 
555 /// Emits a loop nest of `scf.for` with the proper body for `linalgOp`.
556 Optional<LinalgLoops> mlir::linalg::linalgOpToLoops(PatternRewriter &rewriter,
557                                                     LinalgOp linalgOp) {
558   return linalgOpToLoopsImpl<scf::ForOp>(rewriter, linalgOp);
559 }
560 
561 /// Emits a loop nest of `scf.parallel` with the proper body for `linalgOp`.
562 Optional<LinalgLoops>
563 mlir::linalg::linalgOpToParallelLoops(PatternRewriter &rewriter,
564                                       LinalgOp linalgOp) {
565   return linalgOpToLoopsImpl<scf::ParallelOp>(rewriter, linalgOp);
566 }
567