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