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/Affine/EDSC/Intrinsics.h"
11 #include "mlir/Dialect/Linalg/EDSC/FoldedIntrinsics.h"
12 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
13 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
14 #include "mlir/Dialect/Linalg/Passes.h"
15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
16 #include "mlir/Dialect/Linalg/Utils/Utils.h"
17 #include "mlir/Dialect/SCF/EDSC/Builders.h"
18 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.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 
26 using namespace mlir;
27 using namespace mlir::edsc;
28 using namespace mlir::edsc::intrinsics;
29 using namespace mlir::linalg;
30 
31 using edsc::op::operator+;
32 
33 static SmallVector<Value, 8> makeCanonicalAffineApplies(OpBuilder &b,
34                                                         Location loc,
35                                                         AffineMap map,
36                                                         ArrayRef<Value> vals) {
37   if (map.isEmpty())
38     return {};
39 
40   assert(map.getNumInputs() == vals.size());
41   SmallVector<Value, 8> res;
42   res.reserve(map.getNumResults());
43   auto dims = map.getNumDims();
44   for (auto e : map.getResults()) {
45     auto exprMap = AffineMap::get(dims, map.getNumSymbols(), e);
46     SmallVector<Value, 4> operands(vals.begin(), vals.end());
47     canonicalizeMapAndOperands(&exprMap, &operands);
48     res.push_back(affine_apply(exprMap, operands));
49   }
50   return res;
51 }
52 
53 static SmallVector<Value, 4> permuteIvs(ArrayRef<Value> ivs,
54                                         Optional<AffineMap> permutation) {
55   return permutation ? applyMapToValues(ScopedContext::getBuilderRef(),
56                                         ScopedContext::getLocation(),
57                                         permutation.getValue(), ivs)
58                      : SmallVector<Value, 4>(ivs.begin(), ivs.end());
59 }
60 
61 /// Creates a number of ranges equal to the number of dimensions in the `map`.
62 /// The returned ranges correspond to the loop ranges, in the proper order, for
63 /// which new loops will be created.
64 /// The function supports only maps that are invertible and have results of type
65 /// DimExpr or (DimExpr + DimExpr - SymbolExpr floordiv ConstExpr).
66 /// It expects a non-inverted, concatenated map and last values in
67 /// allViewSizes will be applied to the symbols in the map if it contains any.
68 static SmallVector<SubViewOp::Range, 4> emitLoopRanges(OpBuilder &b,
69                                                        Location loc,
70                                                        AffineMap map,
71                                                        ValueRange viewSizes) {
72   unsigned numDims = map.getNumDims(), numRes = map.getNumResults();
73   unsigned numSym = map.getNumSymbols();
74   assert(viewSizes.size() == numRes + numSym &&
75          "viewSizes must contain sizes of all views and values for symbols");
76   SmallVector<SubViewOp::Range, 4> res(numDims);
77   for (unsigned idx = 0; idx < numRes; ++idx) {
78     auto result = map.getResult(idx);
79     if (auto d = result.dyn_cast<AffineDimExpr>()) {
80       if (res[d.getPosition()].offset)
81         continue;
82       res[d.getPosition()] = SubViewOp::Range{
83           std_constant_index(0), viewSizes[idx], std_constant_index(1)};
84     }
85 
86     // If the access pattern is of form (m, n)[s] -> (m + n - s floordiv 2),
87     // then the bounds are:
88     //   (s floordiv 2) <= m <= (size(m) + s floordiv 2 - s + 1).
89     // where size(n) is applied to the symbol s.
90     // This is done statically now.
91     if (auto binOp = result.dyn_cast<AffineBinaryOpExpr>()) {
92       auto lhs = binOp.getLHS().dyn_cast<AffineBinaryOpExpr>();
93       auto rhs = binOp.getRHS().dyn_cast<AffineBinaryOpExpr>();
94       if (!lhs || !rhs || binOp.getKind() != AffineExprKind::Add ||
95           lhs.getKind() != AffineExprKind::Add ||
96           rhs.getKind() != mlir::AffineExprKind::Mul)
97         continue;
98 
99       auto m = lhs.getLHS().dyn_cast<AffineDimExpr>();
100       auto n = lhs.getRHS().dyn_cast<AffineDimExpr>();
101       auto fDiv = rhs.getLHS().dyn_cast<AffineBinaryOpExpr>();
102       auto minusOne = rhs.getRHS().dyn_cast<AffineConstantExpr>();
103       if (!m || !n || !fDiv || !minusOne ||
104           fDiv.getKind() != AffineExprKind::FloorDiv ||
105           fDiv.getLHS().getKind() != AffineExprKind::SymbolId ||
106           fDiv.getRHS().getKind() != AffineExprKind::Constant)
107         continue;
108 
109       auto s = fDiv.getLHS().dyn_cast<AffineSymbolExpr>();
110       if (minusOne.getValue() != -1)
111         continue;
112 
113       int mPos = m.getPosition();
114       AffineExpr one = getAffineConstantExpr(1, s.getContext());
115       AffineExpr sizeOfM = getAffineSymbolExpr(numSym, s.getContext());
116       // Construction of upper bound (size(m) + s floordiv 2 - s + 1).
117       AffineExpr upperOffsetExpr = sizeOfM + fDiv + one - s;
118       AffineMap fromMap = AffineMap::get(numDims, numSym + 1, fDiv);
119       AffineMap toMap = AffineMap::get(numDims, numSym + 1, upperOffsetExpr);
120       SmallVector<Value, 8> values(viewSizes.begin(),
121                                    viewSizes.begin() + numDims);
122       values.insert(values.end(), viewSizes.begin() + numRes, viewSizes.end());
123       values.push_back(viewSizes[mPos]);
124       // Construction of the lower bound (s floordiv 2).
125       Value from = applyMapToValues(b, loc, fromMap, values).front();
126       Value to = applyMapToValues(b, loc, toMap, values).front();
127       res[mPos] = SubViewOp::Range{from, to, std_constant_index(1)};
128     }
129   }
130   return res;
131 }
132 
133 template <typename IndexedValueType, typename OpType>
134 static void inlineRegionAndEmitStore(OpType op, ArrayRef<Value> indexedValues,
135                                      ArrayRef<SmallVector<Value, 8>> indexing,
136                                      ArrayRef<Value> outputBuffers) {
137   assert(op.getOperation()->getNumRegions() == 1 &&
138          "Expected single region op");
139   auto &b = ScopedContext::getBuilderRef();
140   auto &block = op.region().front();
141   BlockAndValueMapping map;
142   map.map(block.getArguments(), indexedValues);
143   for (auto &op : block.without_terminator()) {
144     assert(op.getNumRegions() == 0 && "expected a non-nested region");
145     auto *newOp = b.clone(op, map);
146     map.map(op.getResults(), newOp->getResults());
147   }
148 
149   Operation &terminator = block.back();
150   assert(isa<YieldOp>(terminator) &&
151          "expected a yield op in the end of the region");
152   for (unsigned i = 0, e = terminator.getNumOperands(); i < e; ++i) {
153     IndexedValueType O(outputBuffers[i]);
154     O(indexing[i]) = map.lookupOrDefault(terminator.getOperand(i));
155   }
156 }
157 
158 // Returns a pair that contains input indices and output indices of a
159 // SingleInputPoolingOp `op`.
160 struct InputAndOutputIndices {
161   SmallVector<Value, 8> inputs;
162   SmallVector<Value, 8> outputs;
163 };
164 template <typename SingleInputPoolingOp>
165 static InputAndOutputIndices getInputAndOutputIndices(ArrayRef<Value> allIvs,
166                                                       SingleInputPoolingOp op) {
167   auto &b = ScopedContext::getBuilderRef();
168   auto loc = ScopedContext::getLocation();
169   auto mapsRange = op.indexing_maps().template getAsRange<AffineMapAttr>();
170   auto maps = llvm::to_vector<8>(
171       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
172   return InputAndOutputIndices{
173       makeCanonicalAffineApplies(b, loc, maps[0], allIvs),
174       makeCanonicalAffineApplies(b, loc, maps[2], allIvs)};
175 }
176 
177 namespace {
178 
179 /// Emits the MLIR for the scalar part of the generic op by:
180 ///   1. Emitting load ops for each input and output view in order. This is
181 ///      achieved by applying the appropriate input or output map to the
182 ///      enclosing induction variables.
183 ///   2. Emitting a call to `op.fun()` that takes as arguments the scalars
184 ///      from point 1. above.
185 ///   3. Emitting store ops to store the results of 2. to the output
186 ///      views.
187 ///
188 /// An example output may resemble:
189 ///
190 /// ```
191 ///    scf.for %i = %c0 to %0 step %c1 {
192 ///      scf.for %j = %c0 to %1 step %c1 {
193 ///        scf.for %k = %c0 to %4 step %c1 {
194 ///          %11 = load %arg0[%i, %j] :
195 ///            memref<?x?xf32, stride_specification>
196 ///          %12 = load %arg1[%i, %j, %k] :
197 ///            memref<?x?x?xf32, stride_specification>
198 ///          %13 = load %arg2[%i, %k, %j] :
199 ///            memref<?x?x?xf32, stride_specification>
200 ///          %14:2 = call @foo(%11, %12, %13) : (f32, f32, f32) -> (f32, f32)
201 ///          store %14#0, %arg1[%i, %j, %k] :
202 ///            memref<?x?x?Xf32, stride_specification>
203 ///          store %14#1, %arg2[%i, %k, %j] :
204 ///            memref<?x?x?Xf32, stride_specification>
205 ///       }
206 ///      }
207 ///    }
208 /// ```
209 // TODO: need a LinalgStructuredOpInterface.
210 template <typename IndexedValueType, typename LinalgStructuredOpType>
211 void emitScalarImplementation(ArrayRef<Value> allIvs,
212                               LinalgStructuredOpType linalgOp) {
213   assert(linalgOp.hasBufferSemantics() &&
214          "expected linalg op with buffer semantics");
215   auto &b = ScopedContext::getBuilderRef();
216   auto loc = ScopedContext::getLocation();
217   unsigned nInputs = linalgOp.getNumInputs();
218   unsigned nOutputs = linalgOp.getNumOutputs();
219   SmallVector<Value, 4> indexedValues;
220   indexedValues.reserve(nInputs + nOutputs);
221 
222   auto attr = linalgOp.template getAttrOfType<IntegerAttr>("symbol_source");
223   auto allIvsPlusDims = SmallVector<Value, 4>(allIvs.begin(), allIvs.end());
224   if (attr) {
225     auto operand = linalgOp.getOperand(attr.getInt());
226     auto shapedType = operand.getType().template cast<ShapedType>();
227     allIvsPlusDims.reserve(allIvs.size() + shapedType.getRank());
228     for (unsigned idx = 0, e = shapedType.getRank(); idx < e; ++idx)
229       allIvsPlusDims.push_back(b.create<DimOp>(loc, operand, idx));
230   }
231 
232   // TODO: Avoid the loads if the corresponding argument of the
233   // region has no uses.
234   // 1.a. Emit load from input views.
235   for (unsigned i = 0; i < nInputs; ++i) {
236     auto indexing = makeCanonicalAffineApplies(
237         b, loc, linalgOp.getInputIndexingMap(i), allIvsPlusDims);
238     // Passing through IndexedValueType emits the proper load operation.
239     indexedValues.push_back(IndexedValueType(linalgOp.getInput(i))(indexing));
240   }
241   // 1.b. Emit load from output views.
242   for (unsigned i = 0; i < nOutputs; ++i) {
243     auto indexing = makeCanonicalAffineApplies(
244         b, loc, linalgOp.getOutputIndexingMap(i), allIvsPlusDims);
245     // Passing through IndexedValueType emits the proper load operation.
246     indexedValues.push_back(
247         IndexedValueType(linalgOp.getOutputBuffer(i))(indexing));
248   }
249 
250   // TODO: When a region inliner exists, use it.
251   // 2. Inline region, currently only works for a single basic block.
252   // 3. Emit store.
253   SmallVector<SmallVector<Value, 8>, 8> indexing;
254   SmallVector<Value, 8> outputBuffers;
255   for (unsigned i = 0; i < nOutputs; ++i) {
256     indexing.push_back(makeCanonicalAffineApplies(
257         b, loc, linalgOp.getOutputIndexingMap(i), allIvsPlusDims));
258     outputBuffers.push_back(linalgOp.getOutputBuffer(i));
259   }
260   inlineRegionAndEmitStore<IndexedValueType>(linalgOp, indexedValues, indexing,
261                                              outputBuffers);
262 }
263 
264 template <typename IndexedValueType>
265 void emitScalarImplementation(ArrayRef<Value> allIvs, CopyOp copyOp) {
266   assert(copyOp.hasBufferSemantics() &&
267          "expected linalg op with buffer semantics");
268   auto nPar = copyOp.getNumParallelLoops();
269   assert(nPar == allIvs.size());
270   auto inputIvs =
271       permuteIvs(allIvs.take_front(nPar), copyOp.inputPermutation());
272   auto outputIvs =
273       permuteIvs(allIvs.take_front(nPar), copyOp.outputPermutation());
274   SmallVector<Value, 8> iivs(inputIvs.begin(), inputIvs.end());
275   SmallVector<Value, 8> oivs(outputIvs.begin(), outputIvs.end());
276   IndexedValueType O(copyOp.getOutputBuffer(0)), I(copyOp.getInput(0));
277   // Emit the proper scalar assignment, whether we are dealing with a 0-D or
278   // an n-D loop nest; with or without permutations.
279   // clang-format off
280     nPar > 0 ? O(oivs) = I(iivs) :
281                O() = I();
282   // clang-format on
283 }
284 
285 template <typename IndexedValueType>
286 void emitScalarImplementation(ArrayRef<Value> allIvs, FillOp fillOp) {
287   assert(fillOp.hasBufferSemantics() &&
288          "expected linalg op with buffer semantics");
289   auto nPar = fillOp.getNumParallelLoops();
290   assert(nPar == allIvs.size());
291   auto ivs = SmallVector<Value, 4>(allIvs.begin(), allIvs.begin() + nPar);
292   IndexedValueType O(fillOp.getOutputBuffer(0));
293   // Emit the proper scalar assignment, whether we are dealing with a 0-D or
294   // an n-D loop nest; with or without permutations.
295   nPar > 0 ? O(ivs) = fillOp.value() : O() = fillOp.value();
296 }
297 
298 template <typename IndexedValueType>
299 void emitScalarImplementation(ArrayRef<Value> allIvs, DotOp dotOp) {
300   assert(dotOp.hasBufferSemantics() &&
301          "expected linalg op with buffer semantics");
302   assert(allIvs.size() == 1);
303   Value r_i(allIvs[0]);
304   IndexedValueType A(dotOp.getInput(0)), B(dotOp.getInput(1)),
305       C(dotOp.getOutputBuffer(0));
306   // Emit scalar form.
307   C() = C() + A(r_i) * B(r_i);
308 }
309 
310 template <typename IndexedValueType>
311 Value getConvOpInput(ConvOp convOp, StdIndexedValue im,
312                      MutableArrayRef<Value> imIdx) {
313   // TODO: add a level of indirection to linalg.generic.
314   if (!convOp.padding())
315     return im(imIdx);
316 
317   auto *context = ScopedContext::getContext();
318   Value zeroIndex = std_constant_index(0);
319   SmallVector<Value, 8> conds;
320   SmallVector<Value, 8> clampedImIdx;
321   for (auto iter : llvm::enumerate(imIdx)) {
322     int idx = iter.index();
323     auto dim = iter.value();
324     // Only need to iterate over the window dimensions.
325     if (idx == 0 || idx == static_cast<int>(imIdx.size()) - 1) {
326       clampedImIdx.push_back(dim);
327       continue;
328     }
329 
330     using edsc::op::sge;
331     using edsc::op::slt;
332     using edsc::op::operator||;
333     Value leftOutOfBound = slt(dim, zeroIndex);
334     if (conds.empty())
335       conds.push_back(leftOutOfBound);
336     else
337       conds.push_back(conds.back() || leftOutOfBound);
338     Value rightBound = std_dim(convOp.input(), idx);
339     conds.push_back(conds.back() || (sge(dim, rightBound)));
340 
341     // When padding is involved, the indices will only be shifted to negative,
342     // so having a max op is enough.
343     auto maxMap = AffineMap::get(/*dimCount=*/1, 0,
344                                  {getAffineDimExpr(/*position=*/0, context),
345                                   getAffineConstantExpr(0, context)},
346                                  context);
347     clampedImIdx.push_back(affine_max(dim.getType(), maxMap, ValueRange{dim}));
348   }
349 
350   auto &b = ScopedContext::getBuilderRef();
351   Type type = convOp.input().getType().cast<MemRefType>().getElementType();
352   Value zero = std_constant(type, b.getZeroAttr(type));
353   Value readInput = im(clampedImIdx);
354   return conds.empty() ? readInput
355                        : (Value)std_select(conds.back(), zero, readInput);
356 }
357 
358 /// Returns true is `convOp` has a non-zero padding.
359 static bool hasPadding(ConvOp convOp) {
360   for (unsigned i = 0, e = convOp.getNumSpatialDimensions(); i < e; ++i) {
361     if (convOp.getLowPad(i) > 0 || convOp.getHighPad(i) > 0)
362       return true;
363   }
364   return false;
365 }
366 
367 template <typename IndexedValueType>
368 static void emitScalarImplementation(ArrayRef<Value> allIvs, ConvOp convOp) {
369   assert(convOp.hasBufferSemantics() &&
370          "expected linalg op with buffer semantics");
371   auto &b = ScopedContext::getBuilderRef();
372   auto loc = ScopedContext::getLocation();
373   auto mapsRange = convOp.indexing_maps().getAsRange<AffineMapAttr>();
374   auto maps = llvm::to_vector<8>(
375       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
376   SmallVector<Value, 8> fIdx(
377       makeCanonicalAffineApplies(b, loc, maps[0], allIvs));
378   SmallVector<Value, 8> imIdx(
379       makeCanonicalAffineApplies(b, loc, maps[1], allIvs));
380   SmallVector<Value, 8> oIdx(
381       makeCanonicalAffineApplies(b, loc, maps[2], allIvs));
382 
383   IndexedValueType F(convOp.filter()), O(convOp.output());
384 
385   // Emit scalar form. Padded conv involves an affine.max in the memory access
386   // which is not allowed by affine.load. Override to use an StdIndexedValue
387   // when there is non-zero padding.
388   if (hasPadding(convOp)) {
389     StdIndexedValue I(convOp.input());
390     Value paddedInput = getConvOpInput<IndexedValueType>(convOp, I, imIdx);
391     O(oIdx) += F(fIdx) * paddedInput;
392   } else {
393     IndexedValueType I(convOp.input());
394     O(oIdx) += F(fIdx) * I(imIdx);
395   }
396 }
397 
398 template <typename IndexedValueType>
399 void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMaxOp op) {
400   InputAndOutputIndices indices = getInputAndOutputIndices(allIvs, op);
401   // Emit scalar form.
402   IndexedValueType output(op.output());
403   IndexedValueType input(op.input());
404   Value lhs = output(indices.outputs);
405   Value rhs = input(indices.inputs);
406   using edsc::op::sgt;
407   Value maxValue = std_select(sgt(lhs, rhs), lhs, rhs);
408   output(indices.outputs) = maxValue;
409 }
410 
411 template <typename IndexedValueType>
412 void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMinOp op) {
413   InputAndOutputIndices indices = getInputAndOutputIndices(allIvs, op);
414   // Emit scalar form.
415   IndexedValueType output(op.output());
416   IndexedValueType input(op.input());
417   Value lhs = output(indices.outputs);
418   Value rhs = input(indices.inputs);
419   using edsc::op::slt;
420   Value minValue = std_select(slt(lhs, rhs), lhs, rhs);
421   output(indices.outputs) = minValue;
422 }
423 template <typename IndexedValueType>
424 void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingSumOp op) {
425   auto indices = getInputAndOutputIndices(allIvs, op);
426   IndexedValueType input(op.input()), output(op.output());
427 
428   // Emit scalar form.
429   output(indices.outputs) += input(indices.inputs);
430 }
431 /// Emits the MLIR for the scalar part of the indexed generic op by:
432 ///   1. Emitting load ops for each input and output view in order. This is
433 ///      achieved by applying the appropriate input or output map to the
434 ///      enclosing induction variables.
435 ///   2. Emitting a call to `op.fun()` that takes as arguments the induction
436 ///      variables and the scalars from point 1. above.
437 ///   3. Emitting store ops to store the results of 2. to the output views.
438 ///
439 /// An example output may resemble:
440 ///
441 /// ```
442 ///    scf.for %i = %c0 to %0 step %c1 {
443 ///      scf.for %j = %c0 to %1 step %c1 {
444 ///        scf.for %k = %c0 to %4 step %c1 {
445 ///          %11 = load %arg0[%i, %j] :
446 ///            memref<?x?xf32, stride_specification>
447 ///          %12 = load %arg1[%i, %j, %k] :
448 ///            memref<?x?x?xf32, stride_specification>
449 ///          %13 = load %arg2[%i, %k, %j] :
450 ///            memref<?x?x?xf32, stride_specification>
451 ///          %14:2 = call @foo(%i, %j, %k, %11, %12, %13) :
452 ///            (index, index, index, f32, f32, f32) -> (f32, f32)
453 ///          store %14#0, %arg1[%i, %j, %k] :
454 ///            memref<?x?x?Xf32, stride_specification>
455 ///          store %14#1, %arg2[%i, %k, %j] :
456 ///            memref<?x?x?Xf32, stride_specification>
457 ///       }
458 ///      }
459 ///    }
460 /// ```
461 template <typename IndexedValueType>
462 static void emitScalarImplementation(ArrayRef<Value> allIvs,
463                                      IndexedGenericOp indexedGenericOp) {
464   assert(indexedGenericOp.hasBufferSemantics() &&
465          "expected linalg op with buffer semantics");
466   auto &b = ScopedContext::getBuilderRef();
467   auto loc = ScopedContext::getLocation();
468   unsigned nInputs = indexedGenericOp.getNumInputs();
469   unsigned nOutputs = indexedGenericOp.getNumOutputs();
470   unsigned nLoops = allIvs.size();
471   SmallVector<Value, 4> indexedValues;
472   indexedValues.reserve(nLoops + nInputs + nOutputs);
473   for (unsigned i = 0; i < nLoops; ++i)
474     indexedValues.push_back(allIvs[i]);
475 
476   // TODO: Avoid the loads if the corresponding argument of the
477   // region has no uses.
478   // 1.a. Emit load from input views.
479   for (unsigned i = 0; i < nInputs; ++i) {
480     auto indexing = makeCanonicalAffineApplies(
481         b, loc, indexedGenericOp.getInputIndexingMap(i), allIvs);
482     // Pass input i through IndexedValueType emits the proper load operation.
483     indexedValues.push_back(
484         IndexedValueType(indexedGenericOp.getInput(i))(indexing));
485   }
486   // 1.b. Emit load from output views.
487   for (unsigned i = 0; i < nOutputs; ++i) {
488     auto indexing = makeCanonicalAffineApplies(
489         b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs);
490     // Pass output i through IndexedValueType emits the proper load operation.
491     indexedValues.push_back(
492         IndexedValueType(indexedGenericOp.getOutputBuffer(i))(indexing));
493   }
494 
495   // TODO: When a region inliner exists, use it.
496   // 2. Inline region, currently only works for a single basic block.
497   // 3. Emit store.
498   SmallVector<SmallVector<Value, 8>, 8> indexing;
499   SmallVector<Value, 8> outputBuffers;
500   for (unsigned i = 0; i < nOutputs; ++i) {
501     indexing.push_back(makeCanonicalAffineApplies(
502         b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs));
503     outputBuffers.push_back(indexedGenericOp.getOutputBuffer(i));
504   }
505   inlineRegionAndEmitStore<IndexedValueType>(indexedGenericOp, indexedValues,
506                                              indexing, outputBuffers);
507 }
508 
509 template <typename LoopTy, typename ConcreteOpTy>
510 Optional<LinalgLoops> linalgOpToLoopsImpl(Operation *op, OpBuilder &builder) {
511   using IndexedValueTy = typename GenerateLoopNest<LoopTy>::IndexedValueTy;
512 
513   ScopedContext scope(builder, op->getLoc());
514 
515   // The flattened loopToOperandRangesMaps is expected to be an invertible
516   // permutation map (which is asserted in the inverse calculation).
517   auto linalgOp = cast<ConcreteOpTy>(op);
518   assert(linalgOp.hasBufferSemantics() &&
519          "expected linalg op with buffer semantics");
520   auto mapsRange =
521       linalgOp.indexing_maps().template getAsRange<AffineMapAttr>();
522   auto maps = llvm::to_vector<8>(
523       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
524   SmallVector<Value, 8> sizes = getViewSizes(builder, linalgOp);
525   AffineMap map = concatAffineMaps(maps);
526   auto loopRanges = emitLoopRanges(scope.getBuilderRef(), scope.getLocation(),
527                                    map, getViewSizes(builder, linalgOp));
528   SmallVector<Value, 4> allIvs;
529   GenerateLoopNest<LoopTy>::doit(
530       loopRanges, linalgOp.iterator_types().getValue(), [&](ValueRange ivs) {
531         allIvs.append(ivs.begin(), ivs.end());
532         emitScalarImplementation<IndexedValueTy>(allIvs, linalgOp);
533       });
534   // Number of loop ops might be different from the number of ivs since some
535   // loops like affine.parallel and scf.parallel have multiple ivs.
536   llvm::SetVector<Operation *> loopSet;
537   for (Value iv : allIvs) {
538     if (!iv)
539       return {};
540     // The induction variable is a block argument of the entry block of the
541     // loop operation.
542     BlockArgument ivVal = iv.dyn_cast<BlockArgument>();
543     if (!ivVal)
544       return {};
545     loopSet.insert(ivVal.getOwner()->getParentOp());
546   }
547   LinalgLoops loops(loopSet.begin(), loopSet.end());
548   return loops;
549 }
550 
551 template <typename LoopType, typename ConcreteOp>
552 class LinalgRewritePattern : public RewritePattern {
553 public:
554   explicit LinalgRewritePattern(MLIRContext *context)
555       : RewritePattern(ConcreteOp::getOperationName(), 1, context) {}
556 
557   LogicalResult matchAndRewrite(Operation *op,
558                                 PatternRewriter &rewriter) const override {
559     if (!linalgOpToLoopsImpl<LoopType, ConcreteOp>(op, rewriter))
560       return failure();
561     rewriter.eraseOp(op);
562     return success();
563   }
564 };
565 
566 template <typename LoopType, typename ConcreteOp>
567 void insertOnePattern(OwningRewritePatternList &patterns, MLIRContext *ctx) {
568   patterns.insert<LinalgRewritePattern<LoopType, ConcreteOp>>(ctx);
569 }
570 
571 template <typename LoopType, typename... Args>
572 void insertPatterns(OwningRewritePatternList &patterns, MLIRContext *ctx) {
573   (void)std::initializer_list<int>{
574       0, (insertOnePattern<LoopType, Args>(patterns, ctx), 0)...};
575 }
576 
577 /// Local folding pattern for AffineApplyOp that we can apply greedily.
578 /// This replaces AffineApplyOp by the proper value in cases where the
579 /// associated map is trivial.
580 /// A trivial map here is defined as a map with a single result and either:
581 ///   1. Zero operand + returns a single AffineConstantExpr
582 ///   2. One operand + returns a single AffineDimExpr
583 ///   3. One operand + returns a single AffineSymbolExpr
584 //
585 /// In the first case, the AffineApplyOp is replaced by a new constant. In the
586 /// other cases, it is replaced by its unique operand.
587 struct FoldAffineOp : public RewritePattern {
588   FoldAffineOp(MLIRContext *context)
589       : RewritePattern(AffineApplyOp::getOperationName(), 0, context) {}
590 
591   LogicalResult matchAndRewrite(Operation *op,
592                                 PatternRewriter &rewriter) const override {
593     AffineApplyOp affineApplyOp = cast<AffineApplyOp>(op);
594     auto map = affineApplyOp.getAffineMap();
595     if (map.getNumResults() != 1 || map.getNumInputs() > 1)
596       return failure();
597 
598     AffineExpr expr = map.getResult(0);
599     if (map.getNumInputs() == 0) {
600       if (auto val = expr.dyn_cast<AffineConstantExpr>()) {
601         rewriter.replaceOpWithNewOp<ConstantIndexOp>(op, val.getValue());
602         return success();
603       }
604       return failure();
605     }
606     if (expr.dyn_cast<AffineDimExpr>() || expr.dyn_cast<AffineSymbolExpr>()) {
607       rewriter.replaceOp(op, op->getOperand(0));
608       return success();
609     }
610     return failure();
611   }
612 };
613 } // namespace
614 
615 template <typename LoopType>
616 static void lowerLinalgToLoopsImpl(FuncOp funcOp, MLIRContext *context) {
617   OwningRewritePatternList patterns;
618   // Canonicalization and folding patterns applied greedily allow cleaning up
619   // the emitted IR on the fly.
620   // TODO: fold view and subview ops?
621   insertPatterns<LoopType,
622 #define GET_OP_LIST
623 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
624                  >(patterns, context);
625 
626   DimOp::getCanonicalizationPatterns(patterns, context);
627   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
628   patterns.insert<FoldAffineOp>(context);
629   // Just apply the patterns greedily.
630   applyPatternsAndFoldGreedily(funcOp, patterns);
631 }
632 
633 namespace {
634 struct LowerToAffineLoops
635     : public LinalgLowerToAffineLoopsBase<LowerToAffineLoops> {
636   void runOnFunction() override {
637     lowerLinalgToLoopsImpl<AffineForOp>(getFunction(), &getContext());
638   }
639 };
640 struct LowerToLoops : public LinalgLowerToLoopsBase<LowerToLoops> {
641   void runOnFunction() override {
642     lowerLinalgToLoopsImpl<scf::ForOp>(getFunction(), &getContext());
643   }
644 };
645 struct LowerToParallelLoops
646     : public LinalgLowerToParallelLoopsBase<LowerToParallelLoops> {
647   void runOnFunction() override {
648     lowerLinalgToLoopsImpl<scf::ParallelOp>(getFunction(), &getContext());
649   }
650 };
651 } // namespace
652 
653 std::unique_ptr<OperationPass<FuncOp>> mlir::createConvertLinalgToLoopsPass() {
654   return std::make_unique<LowerToLoops>();
655 }
656 
657 std::unique_ptr<OperationPass<FuncOp>>
658 mlir::createConvertLinalgToParallelLoopsPass() {
659   return std::make_unique<LowerToParallelLoops>();
660 }
661 
662 std::unique_ptr<OperationPass<FuncOp>>
663 mlir::createConvertLinalgToAffineLoopsPass() {
664   return std::make_unique<LowerToAffineLoops>();
665 }
666 
667 // TODO: gradually remove this layer as more ops become "named".
668 template <typename LoopTy>
669 static Optional<LinalgLoops> linalgOpToLoopsImplSwitch(Operation *op,
670                                                        OpBuilder &builder) {
671   assert(isa<LinalgOp>(op) && "LinalgOp expected");
672   if (isa<CopyOp>(op))
673     return linalgOpToLoopsImpl<LoopTy, CopyOp>(op, builder);
674   if (isa<FillOp>(op))
675     return linalgOpToLoopsImpl<LoopTy, FillOp>(op, builder);
676   if (isa<DotOp>(op))
677     return linalgOpToLoopsImpl<LoopTy, DotOp>(op, builder);
678   if (isa<ConvOp>(op))
679     return linalgOpToLoopsImpl<LoopTy, ConvOp>(op, builder);
680   if (isa<PoolingMaxOp>(op))
681     return linalgOpToLoopsImpl<LoopTy, PoolingMaxOp>(op, builder);
682   if (isa<PoolingMinOp>(op))
683     return linalgOpToLoopsImpl<LoopTy, PoolingMinOp>(op, builder);
684   if (isa<PoolingSumOp>(op))
685     return linalgOpToLoopsImpl<LoopTy, PoolingSumOp>(op, builder);
686   if (isa<IndexedGenericOp>(op))
687     return linalgOpToLoopsImpl<LoopTy, IndexedGenericOp>(op, builder);
688 
689   // TODO: Cases below are generic and need a LinalgStructuredOpInterface.
690   if (isa<GenericOp>(op))
691     return linalgOpToLoopsImpl<LoopTy, GenericOp>(op, builder);
692   if (isa<MatmulOp>(op))
693     return linalgOpToLoopsImpl<LoopTy, MatmulOp>(op, builder);
694   if (isa<MatvecOp>(op))
695     return linalgOpToLoopsImpl<LoopTy, MatvecOp>(op, builder);
696   if (isa<BatchMatmulOp>(op))
697     return linalgOpToLoopsImpl<LoopTy, BatchMatmulOp>(op, builder);
698   llvm_unreachable("Unexpected op in linalgOpToLoopsImpl");
699 }
700 
701 /// Emits a loop nest with the proper body for `op`.
702 template <typename LoopTy>
703 Optional<LinalgLoops> mlir::linalg::linalgLowerOpToLoops(OpBuilder &builder,
704                                                          Operation *op) {
705   return linalgOpToLoopsImplSwitch<LoopTy>(op, builder);
706 }
707 
708 template Optional<LinalgLoops>
709 mlir::linalg::linalgLowerOpToLoops<AffineForOp>(OpBuilder &builder,
710                                                 Operation *op);
711 template Optional<LinalgLoops>
712 mlir::linalg::linalgLowerOpToLoops<scf::ForOp>(OpBuilder &builder,
713                                                Operation *op);
714 template Optional<LinalgLoops>
715 mlir::linalg::linalgLowerOpToLoops<scf::ParallelOp>(OpBuilder &builder,
716                                                     Operation *op);
717 
718 /// Emits a loop nest of `affine.for` with the proper body for `op`.
719 LogicalResult mlir::linalg::linalgOpToAffineLoops(OpBuilder &builder,
720                                                   Operation *op) {
721   Optional<LinalgLoops> loops = linalgLowerOpToLoops<AffineForOp>(builder, op);
722   return loops ? success() : failure();
723 }
724 
725 /// Emits a loop nest of `scf.for` with the proper body for `op`.
726 LogicalResult mlir::linalg::linalgOpToLoops(OpBuilder &builder, Operation *op) {
727   Optional<LinalgLoops> loops = linalgLowerOpToLoops<scf::ForOp>(builder, op);
728   return loops ? success() : failure();
729 }
730 
731 /// Emits a loop nest of `scf.parallel` with the proper body for `op`.
732 LogicalResult mlir::linalg::linalgOpToParallelLoops(OpBuilder &builder,
733                                                     Operation *op) {
734   Optional<LinalgLoops> loops =
735       linalgLowerOpToLoops<scf::ParallelOp>(builder, op);
736   return loops ? success() : failure();
737 }
738