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